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
8enet/AppOpsX
opsxlib/src/main/java/com/zzzmode/appopsx/server/LifecycleAgent.java
// Path: opsxlib/src/main/java/com/zzzmode/appopsx/common/Actions.java // public final class Actions { // // public static final String ACTION_SERVER_STARTED="com.zzzmode.appopsx.action.SERVER_STARTED"; // public static final String ACTION_SERVER_CONNECTED="com.zzzmode.appopsx.action.SERVER_CONNECTED"; // public static final String ACTION_SERVER_DISCONNECTED="com.zzzmode.appopsx.action.SERVER_DISCONNECTED"; // public static final String ACTION_SERVER_STOPED="com.zzzmode.appopsx.action.SERVER_STOPED"; // } // // Path: opsxlib/src/main/java/com/zzzmode/appopsx/common/ServerRunInfo.java // public class ServerRunInfo implements android.os.Parcelable { // // public String protocolVersion = OpsDataTransfer.PROTOCOL_VERSION; // // public String startArgs; // public long startTime; // public long startRealTime; // public long recvBytes; // public long sentBytes; // // public long successCount; // public long errorCount; // // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.protocolVersion); // dest.writeString(this.startArgs); // dest.writeLong(this.startTime); // dest.writeLong(this.startRealTime); // dest.writeLong(this.recvBytes); // dest.writeLong(this.sentBytes); // dest.writeLong(this.successCount); // dest.writeLong(this.errorCount); // } // // public ServerRunInfo() { // } // // protected ServerRunInfo(Parcel in) { // this.protocolVersion = in.readString(); // this.startArgs = in.readString(); // this.startTime = in.readLong(); // this.startRealTime = in.readLong(); // this.recvBytes = in.readLong(); // this.sentBytes = in.readLong(); // this.successCount = in.readLong(); // this.errorCount = in.readLong(); // } // // public static final Creator<ServerRunInfo> CREATOR = new Creator<ServerRunInfo>() { // @Override // public ServerRunInfo createFromParcel(Parcel source) { // return new ServerRunInfo(source); // } // // @Override // public ServerRunInfo[] newArray(int size) { // return new ServerRunInfo[size]; // } // }; // // // @Override // public String toString() { // return "ServerRunInfo{" + // "protocolVersion='" + protocolVersion + '\'' + // ", startArgs='" + startArgs + '\'' + // ", startTime=" + startTime + // ", startRealTime=" + startRealTime + // ", recvBytes=" + recvBytes + // ", sentBytes=" + sentBytes + // ", successCount=" + successCount + // ", errorCount=" + errorCount + // '}'; // } // }
import android.content.Intent; import com.zzzmode.appopsx.common.Actions; import com.zzzmode.appopsx.common.ServerRunInfo; import java.util.Map;
package com.zzzmode.appopsx.server; /** * Created by zl on 2017/10/12. */ class LifecycleAgent { static volatile Map<String, String> sParams;
// Path: opsxlib/src/main/java/com/zzzmode/appopsx/common/Actions.java // public final class Actions { // // public static final String ACTION_SERVER_STARTED="com.zzzmode.appopsx.action.SERVER_STARTED"; // public static final String ACTION_SERVER_CONNECTED="com.zzzmode.appopsx.action.SERVER_CONNECTED"; // public static final String ACTION_SERVER_DISCONNECTED="com.zzzmode.appopsx.action.SERVER_DISCONNECTED"; // public static final String ACTION_SERVER_STOPED="com.zzzmode.appopsx.action.SERVER_STOPED"; // } // // Path: opsxlib/src/main/java/com/zzzmode/appopsx/common/ServerRunInfo.java // public class ServerRunInfo implements android.os.Parcelable { // // public String protocolVersion = OpsDataTransfer.PROTOCOL_VERSION; // // public String startArgs; // public long startTime; // public long startRealTime; // public long recvBytes; // public long sentBytes; // // public long successCount; // public long errorCount; // // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.protocolVersion); // dest.writeString(this.startArgs); // dest.writeLong(this.startTime); // dest.writeLong(this.startRealTime); // dest.writeLong(this.recvBytes); // dest.writeLong(this.sentBytes); // dest.writeLong(this.successCount); // dest.writeLong(this.errorCount); // } // // public ServerRunInfo() { // } // // protected ServerRunInfo(Parcel in) { // this.protocolVersion = in.readString(); // this.startArgs = in.readString(); // this.startTime = in.readLong(); // this.startRealTime = in.readLong(); // this.recvBytes = in.readLong(); // this.sentBytes = in.readLong(); // this.successCount = in.readLong(); // this.errorCount = in.readLong(); // } // // public static final Creator<ServerRunInfo> CREATOR = new Creator<ServerRunInfo>() { // @Override // public ServerRunInfo createFromParcel(Parcel source) { // return new ServerRunInfo(source); // } // // @Override // public ServerRunInfo[] newArray(int size) { // return new ServerRunInfo[size]; // } // }; // // // @Override // public String toString() { // return "ServerRunInfo{" + // "protocolVersion='" + protocolVersion + '\'' + // ", startArgs='" + startArgs + '\'' + // ", startTime=" + startTime + // ", startRealTime=" + startRealTime + // ", recvBytes=" + recvBytes + // ", sentBytes=" + sentBytes + // ", successCount=" + successCount + // ", errorCount=" + errorCount + // '}'; // } // } // Path: opsxlib/src/main/java/com/zzzmode/appopsx/server/LifecycleAgent.java import android.content.Intent; import com.zzzmode.appopsx.common.Actions; import com.zzzmode.appopsx.common.ServerRunInfo; import java.util.Map; package com.zzzmode.appopsx.server; /** * Created by zl on 2017/10/12. */ class LifecycleAgent { static volatile Map<String, String> sParams;
static ServerRunInfo serverRunInfo = new ServerRunInfo();
8enet/AppOpsX
opsxlib/src/main/java/com/zzzmode/appopsx/server/LifecycleAgent.java
// Path: opsxlib/src/main/java/com/zzzmode/appopsx/common/Actions.java // public final class Actions { // // public static final String ACTION_SERVER_STARTED="com.zzzmode.appopsx.action.SERVER_STARTED"; // public static final String ACTION_SERVER_CONNECTED="com.zzzmode.appopsx.action.SERVER_CONNECTED"; // public static final String ACTION_SERVER_DISCONNECTED="com.zzzmode.appopsx.action.SERVER_DISCONNECTED"; // public static final String ACTION_SERVER_STOPED="com.zzzmode.appopsx.action.SERVER_STOPED"; // } // // Path: opsxlib/src/main/java/com/zzzmode/appopsx/common/ServerRunInfo.java // public class ServerRunInfo implements android.os.Parcelable { // // public String protocolVersion = OpsDataTransfer.PROTOCOL_VERSION; // // public String startArgs; // public long startTime; // public long startRealTime; // public long recvBytes; // public long sentBytes; // // public long successCount; // public long errorCount; // // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.protocolVersion); // dest.writeString(this.startArgs); // dest.writeLong(this.startTime); // dest.writeLong(this.startRealTime); // dest.writeLong(this.recvBytes); // dest.writeLong(this.sentBytes); // dest.writeLong(this.successCount); // dest.writeLong(this.errorCount); // } // // public ServerRunInfo() { // } // // protected ServerRunInfo(Parcel in) { // this.protocolVersion = in.readString(); // this.startArgs = in.readString(); // this.startTime = in.readLong(); // this.startRealTime = in.readLong(); // this.recvBytes = in.readLong(); // this.sentBytes = in.readLong(); // this.successCount = in.readLong(); // this.errorCount = in.readLong(); // } // // public static final Creator<ServerRunInfo> CREATOR = new Creator<ServerRunInfo>() { // @Override // public ServerRunInfo createFromParcel(Parcel source) { // return new ServerRunInfo(source); // } // // @Override // public ServerRunInfo[] newArray(int size) { // return new ServerRunInfo[size]; // } // }; // // // @Override // public String toString() { // return "ServerRunInfo{" + // "protocolVersion='" + protocolVersion + '\'' + // ", startArgs='" + startArgs + '\'' + // ", startTime=" + startTime + // ", startRealTime=" + startRealTime + // ", recvBytes=" + recvBytes + // ", sentBytes=" + sentBytes + // ", successCount=" + successCount + // ", errorCount=" + errorCount + // '}'; // } // }
import android.content.Intent; import com.zzzmode.appopsx.common.Actions; import com.zzzmode.appopsx.common.ServerRunInfo; import java.util.Map;
package com.zzzmode.appopsx.server; /** * Created by zl on 2017/10/12. */ class LifecycleAgent { static volatile Map<String, String> sParams; static ServerRunInfo serverRunInfo = new ServerRunInfo(); static void onStarted(){
// Path: opsxlib/src/main/java/com/zzzmode/appopsx/common/Actions.java // public final class Actions { // // public static final String ACTION_SERVER_STARTED="com.zzzmode.appopsx.action.SERVER_STARTED"; // public static final String ACTION_SERVER_CONNECTED="com.zzzmode.appopsx.action.SERVER_CONNECTED"; // public static final String ACTION_SERVER_DISCONNECTED="com.zzzmode.appopsx.action.SERVER_DISCONNECTED"; // public static final String ACTION_SERVER_STOPED="com.zzzmode.appopsx.action.SERVER_STOPED"; // } // // Path: opsxlib/src/main/java/com/zzzmode/appopsx/common/ServerRunInfo.java // public class ServerRunInfo implements android.os.Parcelable { // // public String protocolVersion = OpsDataTransfer.PROTOCOL_VERSION; // // public String startArgs; // public long startTime; // public long startRealTime; // public long recvBytes; // public long sentBytes; // // public long successCount; // public long errorCount; // // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.protocolVersion); // dest.writeString(this.startArgs); // dest.writeLong(this.startTime); // dest.writeLong(this.startRealTime); // dest.writeLong(this.recvBytes); // dest.writeLong(this.sentBytes); // dest.writeLong(this.successCount); // dest.writeLong(this.errorCount); // } // // public ServerRunInfo() { // } // // protected ServerRunInfo(Parcel in) { // this.protocolVersion = in.readString(); // this.startArgs = in.readString(); // this.startTime = in.readLong(); // this.startRealTime = in.readLong(); // this.recvBytes = in.readLong(); // this.sentBytes = in.readLong(); // this.successCount = in.readLong(); // this.errorCount = in.readLong(); // } // // public static final Creator<ServerRunInfo> CREATOR = new Creator<ServerRunInfo>() { // @Override // public ServerRunInfo createFromParcel(Parcel source) { // return new ServerRunInfo(source); // } // // @Override // public ServerRunInfo[] newArray(int size) { // return new ServerRunInfo[size]; // } // }; // // // @Override // public String toString() { // return "ServerRunInfo{" + // "protocolVersion='" + protocolVersion + '\'' + // ", startArgs='" + startArgs + '\'' + // ", startTime=" + startTime + // ", startRealTime=" + startRealTime + // ", recvBytes=" + recvBytes + // ", sentBytes=" + sentBytes + // ", successCount=" + successCount + // ", errorCount=" + errorCount + // '}'; // } // } // Path: opsxlib/src/main/java/com/zzzmode/appopsx/server/LifecycleAgent.java import android.content.Intent; import com.zzzmode.appopsx.common.Actions; import com.zzzmode.appopsx.common.ServerRunInfo; import java.util.Map; package com.zzzmode.appopsx.server; /** * Created by zl on 2017/10/12. */ class LifecycleAgent { static volatile Map<String, String> sParams; static ServerRunInfo serverRunInfo = new ServerRunInfo(); static void onStarted(){
Intent intent = makeIntent(Actions.ACTION_SERVER_STARTED);
8enet/AppOpsX
app/src/main/java/com/zzzmode/appopsx/ui/BaseActivity.java
// Path: app/src/main/java/com/zzzmode/appopsx/ui/core/LangHelper.java // public class LangHelper { // // private static final String TAG = "LangHelper"; // // private static Map<String,Locale> sLocalMap = new HashMap<>(); // private static Locale sDefaultLocal = null; // static { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // sDefaultLocal = LocaleList.getDefault().get(0); // }else { // sDefaultLocal = Locale.getDefault(); // } // // sLocalMap.put("zh-cn",Locale.SIMPLIFIED_CHINESE); // sLocalMap.put("zh-tw",Locale.TRADITIONAL_CHINESE); // sLocalMap.put("en",Locale.ENGLISH); // sLocalMap.put("cs",new Locale("cs","CZ")); // sLocalMap.put("es",new Locale("es")); // sLocalMap.put("ru",new Locale("ru")); // } // // // // // public static void updateLanguage(Context context) { // // Resources resources = context.getResources(); // Configuration config = resources.getConfiguration(); // config.setLocale(getLocaleByLanguage(context)); // DisplayMetrics dm = resources.getDisplayMetrics(); // resources.updateConfiguration(config, dm); // } // // // public static int getLocalIndex(Context context) { // int defSelected = 0; // String defKey = SpHelper.getSharedPreferences(context).getString("pref_app_language", null); // String[] langKeys = context.getResources().getStringArray(R.array.languages_key); // if (defKey != null) { // for (int i = 0; i < langKeys.length; i++) { // if (TextUtils.equals(defKey, langKeys[i])) { // defSelected = i; // break; // } // } // } // return defSelected; // } // // public static Locale getLocaleByLanguage(Context context) { // String language = SpHelper.getSharedPreferences(context).getString("pref_app_language", null); // if(language == null){ // return sDefaultLocal; // } // Locale locale = null; // return (locale = sLocalMap.get(language)) != null ? locale : sDefaultLocal; // } // // // public static Context attachBaseContext(Context context) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // return updateResources(context); // } else { // return context; // } // } // // // @TargetApi(Build.VERSION_CODES.N) // private static Context updateResources(Context context) { // Resources resources = context.getResources(); // Locale locale = getLocaleByLanguage(context); // // Configuration configuration = resources.getConfiguration(); // configuration.setLocale(locale); // configuration.setLocales(new LocaleList(locale)); // return context.createConfigurationContext(configuration); // } // // } // // Path: app/src/main/java/com/zzzmode/appopsx/ui/core/SpHelper.java // public class SpHelper { // // public static SharedPreferences getSharedPreferences(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context); // } // // public static int getThemeMode(Context context) { // if (getSharedPreferences(context).getBoolean("pref_app_daynight_mode", false)) { // return AppCompatDelegate.MODE_NIGHT_YES; // } // return AppCompatDelegate.MODE_NIGHT_NO; // } // // // public static boolean isIgnoredNetOps(Context context,int op){ // return getSharedPreferences(context).getBoolean("pref_ignore_op_code_"+op,false); // } // // public static void ignoredNetOps(Context context,int op){ // getSharedPreferences(context).edit().putBoolean("pref_ignore_op_code_"+op,true).apply(); // } // // }
import android.content.Context; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDelegate; import com.zzzmode.appopsx.ui.core.LangHelper; import com.zzzmode.appopsx.ui.core.SpHelper;
package com.zzzmode.appopsx.ui; /** * Created by zl on 2017/1/7. */ public class BaseActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
// Path: app/src/main/java/com/zzzmode/appopsx/ui/core/LangHelper.java // public class LangHelper { // // private static final String TAG = "LangHelper"; // // private static Map<String,Locale> sLocalMap = new HashMap<>(); // private static Locale sDefaultLocal = null; // static { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // sDefaultLocal = LocaleList.getDefault().get(0); // }else { // sDefaultLocal = Locale.getDefault(); // } // // sLocalMap.put("zh-cn",Locale.SIMPLIFIED_CHINESE); // sLocalMap.put("zh-tw",Locale.TRADITIONAL_CHINESE); // sLocalMap.put("en",Locale.ENGLISH); // sLocalMap.put("cs",new Locale("cs","CZ")); // sLocalMap.put("es",new Locale("es")); // sLocalMap.put("ru",new Locale("ru")); // } // // // // // public static void updateLanguage(Context context) { // // Resources resources = context.getResources(); // Configuration config = resources.getConfiguration(); // config.setLocale(getLocaleByLanguage(context)); // DisplayMetrics dm = resources.getDisplayMetrics(); // resources.updateConfiguration(config, dm); // } // // // public static int getLocalIndex(Context context) { // int defSelected = 0; // String defKey = SpHelper.getSharedPreferences(context).getString("pref_app_language", null); // String[] langKeys = context.getResources().getStringArray(R.array.languages_key); // if (defKey != null) { // for (int i = 0; i < langKeys.length; i++) { // if (TextUtils.equals(defKey, langKeys[i])) { // defSelected = i; // break; // } // } // } // return defSelected; // } // // public static Locale getLocaleByLanguage(Context context) { // String language = SpHelper.getSharedPreferences(context).getString("pref_app_language", null); // if(language == null){ // return sDefaultLocal; // } // Locale locale = null; // return (locale = sLocalMap.get(language)) != null ? locale : sDefaultLocal; // } // // // public static Context attachBaseContext(Context context) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // return updateResources(context); // } else { // return context; // } // } // // // @TargetApi(Build.VERSION_CODES.N) // private static Context updateResources(Context context) { // Resources resources = context.getResources(); // Locale locale = getLocaleByLanguage(context); // // Configuration configuration = resources.getConfiguration(); // configuration.setLocale(locale); // configuration.setLocales(new LocaleList(locale)); // return context.createConfigurationContext(configuration); // } // // } // // Path: app/src/main/java/com/zzzmode/appopsx/ui/core/SpHelper.java // public class SpHelper { // // public static SharedPreferences getSharedPreferences(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context); // } // // public static int getThemeMode(Context context) { // if (getSharedPreferences(context).getBoolean("pref_app_daynight_mode", false)) { // return AppCompatDelegate.MODE_NIGHT_YES; // } // return AppCompatDelegate.MODE_NIGHT_NO; // } // // // public static boolean isIgnoredNetOps(Context context,int op){ // return getSharedPreferences(context).getBoolean("pref_ignore_op_code_"+op,false); // } // // public static void ignoredNetOps(Context context,int op){ // getSharedPreferences(context).edit().putBoolean("pref_ignore_op_code_"+op,true).apply(); // } // // } // Path: app/src/main/java/com/zzzmode/appopsx/ui/BaseActivity.java import android.content.Context; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDelegate; import com.zzzmode.appopsx.ui.core.LangHelper; import com.zzzmode.appopsx.ui.core.SpHelper; package com.zzzmode.appopsx.ui; /** * Created by zl on 2017/1/7. */ public class BaseActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
LangHelper.updateLanguage(this);
8enet/AppOpsX
app/src/main/java/com/zzzmode/appopsx/ui/BaseActivity.java
// Path: app/src/main/java/com/zzzmode/appopsx/ui/core/LangHelper.java // public class LangHelper { // // private static final String TAG = "LangHelper"; // // private static Map<String,Locale> sLocalMap = new HashMap<>(); // private static Locale sDefaultLocal = null; // static { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // sDefaultLocal = LocaleList.getDefault().get(0); // }else { // sDefaultLocal = Locale.getDefault(); // } // // sLocalMap.put("zh-cn",Locale.SIMPLIFIED_CHINESE); // sLocalMap.put("zh-tw",Locale.TRADITIONAL_CHINESE); // sLocalMap.put("en",Locale.ENGLISH); // sLocalMap.put("cs",new Locale("cs","CZ")); // sLocalMap.put("es",new Locale("es")); // sLocalMap.put("ru",new Locale("ru")); // } // // // // // public static void updateLanguage(Context context) { // // Resources resources = context.getResources(); // Configuration config = resources.getConfiguration(); // config.setLocale(getLocaleByLanguage(context)); // DisplayMetrics dm = resources.getDisplayMetrics(); // resources.updateConfiguration(config, dm); // } // // // public static int getLocalIndex(Context context) { // int defSelected = 0; // String defKey = SpHelper.getSharedPreferences(context).getString("pref_app_language", null); // String[] langKeys = context.getResources().getStringArray(R.array.languages_key); // if (defKey != null) { // for (int i = 0; i < langKeys.length; i++) { // if (TextUtils.equals(defKey, langKeys[i])) { // defSelected = i; // break; // } // } // } // return defSelected; // } // // public static Locale getLocaleByLanguage(Context context) { // String language = SpHelper.getSharedPreferences(context).getString("pref_app_language", null); // if(language == null){ // return sDefaultLocal; // } // Locale locale = null; // return (locale = sLocalMap.get(language)) != null ? locale : sDefaultLocal; // } // // // public static Context attachBaseContext(Context context) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // return updateResources(context); // } else { // return context; // } // } // // // @TargetApi(Build.VERSION_CODES.N) // private static Context updateResources(Context context) { // Resources resources = context.getResources(); // Locale locale = getLocaleByLanguage(context); // // Configuration configuration = resources.getConfiguration(); // configuration.setLocale(locale); // configuration.setLocales(new LocaleList(locale)); // return context.createConfigurationContext(configuration); // } // // } // // Path: app/src/main/java/com/zzzmode/appopsx/ui/core/SpHelper.java // public class SpHelper { // // public static SharedPreferences getSharedPreferences(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context); // } // // public static int getThemeMode(Context context) { // if (getSharedPreferences(context).getBoolean("pref_app_daynight_mode", false)) { // return AppCompatDelegate.MODE_NIGHT_YES; // } // return AppCompatDelegate.MODE_NIGHT_NO; // } // // // public static boolean isIgnoredNetOps(Context context,int op){ // return getSharedPreferences(context).getBoolean("pref_ignore_op_code_"+op,false); // } // // public static void ignoredNetOps(Context context,int op){ // getSharedPreferences(context).edit().putBoolean("pref_ignore_op_code_"+op,true).apply(); // } // // }
import android.content.Context; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDelegate; import com.zzzmode.appopsx.ui.core.LangHelper; import com.zzzmode.appopsx.ui.core.SpHelper;
package com.zzzmode.appopsx.ui; /** * Created by zl on 2017/1/7. */ public class BaseActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { LangHelper.updateLanguage(this); super.onCreate(savedInstanceState);
// Path: app/src/main/java/com/zzzmode/appopsx/ui/core/LangHelper.java // public class LangHelper { // // private static final String TAG = "LangHelper"; // // private static Map<String,Locale> sLocalMap = new HashMap<>(); // private static Locale sDefaultLocal = null; // static { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // sDefaultLocal = LocaleList.getDefault().get(0); // }else { // sDefaultLocal = Locale.getDefault(); // } // // sLocalMap.put("zh-cn",Locale.SIMPLIFIED_CHINESE); // sLocalMap.put("zh-tw",Locale.TRADITIONAL_CHINESE); // sLocalMap.put("en",Locale.ENGLISH); // sLocalMap.put("cs",new Locale("cs","CZ")); // sLocalMap.put("es",new Locale("es")); // sLocalMap.put("ru",new Locale("ru")); // } // // // // // public static void updateLanguage(Context context) { // // Resources resources = context.getResources(); // Configuration config = resources.getConfiguration(); // config.setLocale(getLocaleByLanguage(context)); // DisplayMetrics dm = resources.getDisplayMetrics(); // resources.updateConfiguration(config, dm); // } // // // public static int getLocalIndex(Context context) { // int defSelected = 0; // String defKey = SpHelper.getSharedPreferences(context).getString("pref_app_language", null); // String[] langKeys = context.getResources().getStringArray(R.array.languages_key); // if (defKey != null) { // for (int i = 0; i < langKeys.length; i++) { // if (TextUtils.equals(defKey, langKeys[i])) { // defSelected = i; // break; // } // } // } // return defSelected; // } // // public static Locale getLocaleByLanguage(Context context) { // String language = SpHelper.getSharedPreferences(context).getString("pref_app_language", null); // if(language == null){ // return sDefaultLocal; // } // Locale locale = null; // return (locale = sLocalMap.get(language)) != null ? locale : sDefaultLocal; // } // // // public static Context attachBaseContext(Context context) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // return updateResources(context); // } else { // return context; // } // } // // // @TargetApi(Build.VERSION_CODES.N) // private static Context updateResources(Context context) { // Resources resources = context.getResources(); // Locale locale = getLocaleByLanguage(context); // // Configuration configuration = resources.getConfiguration(); // configuration.setLocale(locale); // configuration.setLocales(new LocaleList(locale)); // return context.createConfigurationContext(configuration); // } // // } // // Path: app/src/main/java/com/zzzmode/appopsx/ui/core/SpHelper.java // public class SpHelper { // // public static SharedPreferences getSharedPreferences(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context); // } // // public static int getThemeMode(Context context) { // if (getSharedPreferences(context).getBoolean("pref_app_daynight_mode", false)) { // return AppCompatDelegate.MODE_NIGHT_YES; // } // return AppCompatDelegate.MODE_NIGHT_NO; // } // // // public static boolean isIgnoredNetOps(Context context,int op){ // return getSharedPreferences(context).getBoolean("pref_ignore_op_code_"+op,false); // } // // public static void ignoredNetOps(Context context,int op){ // getSharedPreferences(context).edit().putBoolean("pref_ignore_op_code_"+op,true).apply(); // } // // } // Path: app/src/main/java/com/zzzmode/appopsx/ui/BaseActivity.java import android.content.Context; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDelegate; import com.zzzmode.appopsx.ui.core.LangHelper; import com.zzzmode.appopsx.ui.core.SpHelper; package com.zzzmode.appopsx.ui; /** * Created by zl on 2017/1/7. */ public class BaseActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { LangHelper.updateLanguage(this); super.onCreate(savedInstanceState);
AppCompatDelegate.setDefaultNightMode(SpHelper.getThemeMode(this));
8enet/AppOpsX
app/src/main/java/com/zzzmode/appopsx/ui/main/backup/ExportFragment.java
// Path: app/src/main/java/com/zzzmode/appopsx/ui/model/AppInfo.java // public class AppInfo implements Parcelable { // // public String appName; // public String packageName; // public long time; // public long installTime; // public long updateTime; // public String pinyin; // public ApplicationInfo applicationInfo; // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // // AppInfo appInfo = (AppInfo) o; // // return packageName != null ? packageName.equals(appInfo.packageName) // : appInfo.packageName == null; // // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.appName); // dest.writeString(this.packageName); // } // // public AppInfo() { // } // // protected AppInfo(Parcel in) { // this.appName = in.readString(); // this.packageName = in.readString(); // } // // public static final Parcelable.Creator<AppInfo> CREATOR = new Parcelable.Creator<AppInfo>() { // @Override // public AppInfo createFromParcel(Parcel source) { // return new AppInfo(source); // } // // @Override // public AppInfo[] newArray(int size) { // return new AppInfo[size]; // } // }; // // // @Override // public String toString() { // return "AppInfo{" + // "appName='" + appName + '\'' + // ", packageName='" + packageName + '\'' + // '}'; // } // }
import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.collection.SparseArrayCompat; import com.zzzmode.appopsx.R; import com.zzzmode.appopsx.ui.model.AppInfo; import java.util.ArrayList;
package com.zzzmode.appopsx.ui.main.backup; /** * 导出配置 * Created by zl on 2017/5/7. */ public class ExportFragment extends BaseConfigFragment implements View.OnClickListener { private static final String TAG = "ExportFragment"; private ExportAdapter adapter; private ConfigPresenter mPresenter; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_export, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState);
// Path: app/src/main/java/com/zzzmode/appopsx/ui/model/AppInfo.java // public class AppInfo implements Parcelable { // // public String appName; // public String packageName; // public long time; // public long installTime; // public long updateTime; // public String pinyin; // public ApplicationInfo applicationInfo; // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // // AppInfo appInfo = (AppInfo) o; // // return packageName != null ? packageName.equals(appInfo.packageName) // : appInfo.packageName == null; // // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.appName); // dest.writeString(this.packageName); // } // // public AppInfo() { // } // // protected AppInfo(Parcel in) { // this.appName = in.readString(); // this.packageName = in.readString(); // } // // public static final Parcelable.Creator<AppInfo> CREATOR = new Parcelable.Creator<AppInfo>() { // @Override // public AppInfo createFromParcel(Parcel source) { // return new AppInfo(source); // } // // @Override // public AppInfo[] newArray(int size) { // return new AppInfo[size]; // } // }; // // // @Override // public String toString() { // return "AppInfo{" + // "appName='" + appName + '\'' + // ", packageName='" + packageName + '\'' + // '}'; // } // } // Path: app/src/main/java/com/zzzmode/appopsx/ui/main/backup/ExportFragment.java import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.collection.SparseArrayCompat; import com.zzzmode.appopsx.R; import com.zzzmode.appopsx.ui.model.AppInfo; import java.util.ArrayList; package com.zzzmode.appopsx.ui.main.backup; /** * 导出配置 * Created by zl on 2017/5/7. */ public class ExportFragment extends BaseConfigFragment implements View.OnClickListener { private static final String TAG = "ExportFragment"; private ExportAdapter adapter; private ConfigPresenter mPresenter; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_export, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState);
ArrayList<AppInfo> appInfos = getArguments().getParcelableArrayList(BackupActivity.EXTRA_APPS);
8enet/AppOpsX
opsxlib/src/main/java/com/zzzmode/appopsx/common/OtherOp.java
// Path: apicompat/src/main/java/android/app/AppOpsManager.java // public class AppOpsManager { // // public static final int MODE_ALLOWED = 0; // // // public static final int MODE_IGNORED = 1; // // // public static final int MODE_ERRORED = 2; // // // public static final int MODE_DEFAULT = 3; // // // public static int strOpToOp(String op) { // return 0; // } // // public static String permissionToOp(String s) { // return null; // } // // public static int permissionToOpCode(String s) { // return 0; // } // // public static int strDebugOpToOp(String op) { // throw new IllegalArgumentException("Unknown operation string: " + op); // } // // public static class PackageOps implements Parcelable { // // private final String mPackageName; // private final int mUid; // private final List<OpEntry> mEntries; // // public PackageOps(String packageName, int uid, List<OpEntry> entries) { // mPackageName = packageName; // mUid = uid; // mEntries = entries; // } // // public String getPackageName() { // return mPackageName; // } // // public int getUid() { // return mUid; // } // // public List<OpEntry> getOps() { // return mEntries; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(mPackageName); // dest.writeInt(mUid); // dest.writeInt(mEntries.size()); // for (int i = 0; i < mEntries.size(); i++) { // mEntries.get(i).writeToParcel(dest, flags); // } // } // // PackageOps(Parcel source) { // mPackageName = source.readString(); // mUid = source.readInt(); // mEntries = new ArrayList<OpEntry>(); // final int N = source.readInt(); // for (int i = 0; i < N; i++) { // mEntries.add(OpEntry.CREATOR.createFromParcel(source)); // } // } // // public static final Creator<PackageOps> CREATOR = new Creator<PackageOps>() { // @Override // public PackageOps createFromParcel(Parcel source) { // return new PackageOps(source); // } // // @Override // public PackageOps[] newArray(int size) { // return new PackageOps[size]; // } // }; // } // // // public static class OpEntry implements Parcelable { // // private final int mOp; // private final int mMode; // private final long mTime; // private final long mRejectTime; // private final int mDuration; // private final int mProxyUid; // private final String mProxyPackageName; // // public OpEntry(int op, int mode, long time, long rejectTime, int duration, // int proxyUid, String proxyPackage) { // mOp = op; // mMode = mode; // mTime = time; // mRejectTime = rejectTime; // mDuration = duration; // mProxyUid = proxyUid; // mProxyPackageName = proxyPackage; // } // // public int getOp() { // return mOp; // } // // public int getMode() { // return mMode; // } // // public long getTime() { // return mTime; // } // // public long getRejectTime() { // return mRejectTime; // } // // public boolean isRunning() { // return mDuration == -1; // } // // public int getDuration() { // return mDuration == -1 ? (int) (System.currentTimeMillis() - mTime) : mDuration; // } // // public int getProxyUid() { // return mProxyUid; // } // // public String getProxyPackageName() { // return mProxyPackageName; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(mOp); // dest.writeInt(mMode); // dest.writeLong(mTime); // dest.writeLong(mRejectTime); // dest.writeInt(mDuration); // dest.writeInt(mProxyUid); // dest.writeString(mProxyPackageName); // } // // OpEntry(Parcel source) { // mOp = source.readInt(); // mMode = source.readInt(); // mTime = source.readLong(); // mRejectTime = source.readLong(); // mDuration = source.readInt(); // mProxyUid = source.readInt(); // mProxyPackageName = source.readString(); // } // // public static final Creator<OpEntry> CREATOR = new Creator<OpEntry>() { // @Override // public OpEntry createFromParcel(Parcel source) { // return new OpEntry(source); // } // // @Override // public OpEntry[] newArray(int size) { // return new OpEntry[size]; // } // }; // } // }
import android.Manifest; import android.app.AppOpsManager; import android.util.SparseArray;
} public static boolean isOtherOp(String opName) { return OP_NAME_ACCESS_PHONE_DATA.equals(opName) || OP_NAME_ACCESS_WIFI_NETWORK.equals(opName); } public static String getOpName(int op) { return mData.get(op); } public static String getOpPermName(int op) { return mPerms.get(op); } public static boolean isSupportCount(){ if(sSupportCount == null){ try { Class<?> aClass = Class.forName("android.app.AppOpsManager$OpEntry", false, ClassLoader.getSystemClassLoader()); sSupportCount = ReflectUtils.hasField(aClass,"mAllowedCount"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } return sSupportCount; } public static int getWifiScanOp() { if (s_OP_WIFI_SCAN == null) {
// Path: apicompat/src/main/java/android/app/AppOpsManager.java // public class AppOpsManager { // // public static final int MODE_ALLOWED = 0; // // // public static final int MODE_IGNORED = 1; // // // public static final int MODE_ERRORED = 2; // // // public static final int MODE_DEFAULT = 3; // // // public static int strOpToOp(String op) { // return 0; // } // // public static String permissionToOp(String s) { // return null; // } // // public static int permissionToOpCode(String s) { // return 0; // } // // public static int strDebugOpToOp(String op) { // throw new IllegalArgumentException("Unknown operation string: " + op); // } // // public static class PackageOps implements Parcelable { // // private final String mPackageName; // private final int mUid; // private final List<OpEntry> mEntries; // // public PackageOps(String packageName, int uid, List<OpEntry> entries) { // mPackageName = packageName; // mUid = uid; // mEntries = entries; // } // // public String getPackageName() { // return mPackageName; // } // // public int getUid() { // return mUid; // } // // public List<OpEntry> getOps() { // return mEntries; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(mPackageName); // dest.writeInt(mUid); // dest.writeInt(mEntries.size()); // for (int i = 0; i < mEntries.size(); i++) { // mEntries.get(i).writeToParcel(dest, flags); // } // } // // PackageOps(Parcel source) { // mPackageName = source.readString(); // mUid = source.readInt(); // mEntries = new ArrayList<OpEntry>(); // final int N = source.readInt(); // for (int i = 0; i < N; i++) { // mEntries.add(OpEntry.CREATOR.createFromParcel(source)); // } // } // // public static final Creator<PackageOps> CREATOR = new Creator<PackageOps>() { // @Override // public PackageOps createFromParcel(Parcel source) { // return new PackageOps(source); // } // // @Override // public PackageOps[] newArray(int size) { // return new PackageOps[size]; // } // }; // } // // // public static class OpEntry implements Parcelable { // // private final int mOp; // private final int mMode; // private final long mTime; // private final long mRejectTime; // private final int mDuration; // private final int mProxyUid; // private final String mProxyPackageName; // // public OpEntry(int op, int mode, long time, long rejectTime, int duration, // int proxyUid, String proxyPackage) { // mOp = op; // mMode = mode; // mTime = time; // mRejectTime = rejectTime; // mDuration = duration; // mProxyUid = proxyUid; // mProxyPackageName = proxyPackage; // } // // public int getOp() { // return mOp; // } // // public int getMode() { // return mMode; // } // // public long getTime() { // return mTime; // } // // public long getRejectTime() { // return mRejectTime; // } // // public boolean isRunning() { // return mDuration == -1; // } // // public int getDuration() { // return mDuration == -1 ? (int) (System.currentTimeMillis() - mTime) : mDuration; // } // // public int getProxyUid() { // return mProxyUid; // } // // public String getProxyPackageName() { // return mProxyPackageName; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(mOp); // dest.writeInt(mMode); // dest.writeLong(mTime); // dest.writeLong(mRejectTime); // dest.writeInt(mDuration); // dest.writeInt(mProxyUid); // dest.writeString(mProxyPackageName); // } // // OpEntry(Parcel source) { // mOp = source.readInt(); // mMode = source.readInt(); // mTime = source.readLong(); // mRejectTime = source.readLong(); // mDuration = source.readInt(); // mProxyUid = source.readInt(); // mProxyPackageName = source.readString(); // } // // public static final Creator<OpEntry> CREATOR = new Creator<OpEntry>() { // @Override // public OpEntry createFromParcel(Parcel source) { // return new OpEntry(source); // } // // @Override // public OpEntry[] newArray(int size) { // return new OpEntry[size]; // } // }; // } // } // Path: opsxlib/src/main/java/com/zzzmode/appopsx/common/OtherOp.java import android.Manifest; import android.app.AppOpsManager; import android.util.SparseArray; } public static boolean isOtherOp(String opName) { return OP_NAME_ACCESS_PHONE_DATA.equals(opName) || OP_NAME_ACCESS_WIFI_NETWORK.equals(opName); } public static String getOpName(int op) { return mData.get(op); } public static String getOpPermName(int op) { return mPerms.get(op); } public static boolean isSupportCount(){ if(sSupportCount == null){ try { Class<?> aClass = Class.forName("android.app.AppOpsManager$OpEntry", false, ClassLoader.getSystemClassLoader()); sSupportCount = ReflectUtils.hasField(aClass,"mAllowedCount"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } return sSupportCount; } public static int getWifiScanOp() { if (s_OP_WIFI_SCAN == null) {
s_OP_WIFI_SCAN = (Integer) ReflectUtils.getFieldValue(AppOpsManager.class, "OP_WIFI_SCAN");
8enet/AppOpsX
app/src/main/java/com/zzzmode/appopsx/ui/main/AppItemViewHolder.java
// Path: app/src/main/java/com/zzzmode/appopsx/ui/core/LocalImageLoader.java // public class LocalImageLoader { // // private static LruCache<String, Drawable> sLruCache = null; // // private static void init(Context context) { // if (sLruCache == null) { // // ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); // int maxSize = Math.round(am.getMemoryClass() * 1024 * 1024 * 0.3f); // // sLruCache = new LruCache<String, Drawable>(maxSize) { // @Override // protected int sizeOf(String key, Drawable drawable) { // if (drawable != null) { // if (drawable instanceof BitmapDrawable) { // return ((BitmapDrawable) drawable).getBitmap().getAllocationByteCount(); // } else { // return drawable.getIntrinsicWidth() * drawable.getIntrinsicHeight() * 2; // } // } // return super.sizeOf(key, drawable); // } // // @Override // protected void entryRemoved(boolean evicted, String key, Drawable oldValue, // Drawable newValue) { // super.entryRemoved(evicted, key, oldValue, newValue); // // } // }; // } // } // // public static void load(ImageView view, AppInfo appInfo) { // // Drawable drawable = getDrawable(view.getContext(), appInfo); // // if (drawable != null) { // view.setImageDrawable(drawable); // } else { // view.setImageResource(R.mipmap.ic_launcher); // } // } // // // public static Drawable getDrawable(Context context, AppInfo appInfo) { // init(context); // Drawable drawable = sLruCache.get(appInfo.packageName); // // if (drawable == null && appInfo.applicationInfo != null) { // if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP_MR1) { // drawable = appInfo.applicationInfo.loadUnbadgedIcon(context.getPackageManager()); // }else { // drawable = appInfo.applicationInfo.loadIcon(context.getPackageManager()); // } // UserInfo currentUser = Users.getInstance().getCurrentUser(); // if(currentUser != null && currentUser.isManagedProfile()){ // drawable = context.getPackageManager().getUserBadgedIcon(drawable,currentUser.getUserHandle()); // } // sLruCache.put(appInfo.packageName, drawable); // } // return drawable; // } // // public static void initAdd(Context context, AppInfo appInfo) { // init(context); // if (sLruCache.evictionCount() == 0) { // sLruCache // .put(appInfo.packageName, appInfo.applicationInfo.loadIcon(context.getPackageManager())); // } // } // // public static void clear(){ // sLruCache.evictAll(); // } // // } // // Path: app/src/main/java/com/zzzmode/appopsx/ui/model/AppInfo.java // public class AppInfo implements Parcelable { // // public String appName; // public String packageName; // public long time; // public long installTime; // public long updateTime; // public String pinyin; // public ApplicationInfo applicationInfo; // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // // AppInfo appInfo = (AppInfo) o; // // return packageName != null ? packageName.equals(appInfo.packageName) // : appInfo.packageName == null; // // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.appName); // dest.writeString(this.packageName); // } // // public AppInfo() { // } // // protected AppInfo(Parcel in) { // this.appName = in.readString(); // this.packageName = in.readString(); // } // // public static final Parcelable.Creator<AppInfo> CREATOR = new Parcelable.Creator<AppInfo>() { // @Override // public AppInfo createFromParcel(Parcel source) { // return new AppInfo(source); // } // // @Override // public AppInfo[] newArray(int size) { // return new AppInfo[size]; // } // }; // // // @Override // public String toString() { // return "AppInfo{" + // "appName='" + appName + '\'' + // ", packageName='" + packageName + '\'' + // '}'; // } // }
import androidx.recyclerview.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.zzzmode.appopsx.R; import com.zzzmode.appopsx.ui.core.LocalImageLoader; import com.zzzmode.appopsx.ui.model.AppInfo;
package com.zzzmode.appopsx.ui.main; /** * Created by zl on 2017/5/7. */ public class AppItemViewHolder extends RecyclerView.ViewHolder { private ImageView imgIcon; TextView tvName; public AppItemViewHolder(View itemView) { super(itemView); imgIcon = itemView.findViewById(R.id.app_icon); tvName = itemView.findViewById(R.id.app_name); }
// Path: app/src/main/java/com/zzzmode/appopsx/ui/core/LocalImageLoader.java // public class LocalImageLoader { // // private static LruCache<String, Drawable> sLruCache = null; // // private static void init(Context context) { // if (sLruCache == null) { // // ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); // int maxSize = Math.round(am.getMemoryClass() * 1024 * 1024 * 0.3f); // // sLruCache = new LruCache<String, Drawable>(maxSize) { // @Override // protected int sizeOf(String key, Drawable drawable) { // if (drawable != null) { // if (drawable instanceof BitmapDrawable) { // return ((BitmapDrawable) drawable).getBitmap().getAllocationByteCount(); // } else { // return drawable.getIntrinsicWidth() * drawable.getIntrinsicHeight() * 2; // } // } // return super.sizeOf(key, drawable); // } // // @Override // protected void entryRemoved(boolean evicted, String key, Drawable oldValue, // Drawable newValue) { // super.entryRemoved(evicted, key, oldValue, newValue); // // } // }; // } // } // // public static void load(ImageView view, AppInfo appInfo) { // // Drawable drawable = getDrawable(view.getContext(), appInfo); // // if (drawable != null) { // view.setImageDrawable(drawable); // } else { // view.setImageResource(R.mipmap.ic_launcher); // } // } // // // public static Drawable getDrawable(Context context, AppInfo appInfo) { // init(context); // Drawable drawable = sLruCache.get(appInfo.packageName); // // if (drawable == null && appInfo.applicationInfo != null) { // if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP_MR1) { // drawable = appInfo.applicationInfo.loadUnbadgedIcon(context.getPackageManager()); // }else { // drawable = appInfo.applicationInfo.loadIcon(context.getPackageManager()); // } // UserInfo currentUser = Users.getInstance().getCurrentUser(); // if(currentUser != null && currentUser.isManagedProfile()){ // drawable = context.getPackageManager().getUserBadgedIcon(drawable,currentUser.getUserHandle()); // } // sLruCache.put(appInfo.packageName, drawable); // } // return drawable; // } // // public static void initAdd(Context context, AppInfo appInfo) { // init(context); // if (sLruCache.evictionCount() == 0) { // sLruCache // .put(appInfo.packageName, appInfo.applicationInfo.loadIcon(context.getPackageManager())); // } // } // // public static void clear(){ // sLruCache.evictAll(); // } // // } // // Path: app/src/main/java/com/zzzmode/appopsx/ui/model/AppInfo.java // public class AppInfo implements Parcelable { // // public String appName; // public String packageName; // public long time; // public long installTime; // public long updateTime; // public String pinyin; // public ApplicationInfo applicationInfo; // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // // AppInfo appInfo = (AppInfo) o; // // return packageName != null ? packageName.equals(appInfo.packageName) // : appInfo.packageName == null; // // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.appName); // dest.writeString(this.packageName); // } // // public AppInfo() { // } // // protected AppInfo(Parcel in) { // this.appName = in.readString(); // this.packageName = in.readString(); // } // // public static final Parcelable.Creator<AppInfo> CREATOR = new Parcelable.Creator<AppInfo>() { // @Override // public AppInfo createFromParcel(Parcel source) { // return new AppInfo(source); // } // // @Override // public AppInfo[] newArray(int size) { // return new AppInfo[size]; // } // }; // // // @Override // public String toString() { // return "AppInfo{" + // "appName='" + appName + '\'' + // ", packageName='" + packageName + '\'' + // '}'; // } // } // Path: app/src/main/java/com/zzzmode/appopsx/ui/main/AppItemViewHolder.java import androidx.recyclerview.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.zzzmode.appopsx.R; import com.zzzmode.appopsx.ui.core.LocalImageLoader; import com.zzzmode.appopsx.ui.model.AppInfo; package com.zzzmode.appopsx.ui.main; /** * Created by zl on 2017/5/7. */ public class AppItemViewHolder extends RecyclerView.ViewHolder { private ImageView imgIcon; TextView tvName; public AppItemViewHolder(View itemView) { super(itemView); imgIcon = itemView.findViewById(R.id.app_icon); tvName = itemView.findViewById(R.id.app_name); }
public void bindData(AppInfo appInfo) {
8enet/AppOpsX
app/src/main/java/com/zzzmode/appopsx/ui/main/AppItemViewHolder.java
// Path: app/src/main/java/com/zzzmode/appopsx/ui/core/LocalImageLoader.java // public class LocalImageLoader { // // private static LruCache<String, Drawable> sLruCache = null; // // private static void init(Context context) { // if (sLruCache == null) { // // ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); // int maxSize = Math.round(am.getMemoryClass() * 1024 * 1024 * 0.3f); // // sLruCache = new LruCache<String, Drawable>(maxSize) { // @Override // protected int sizeOf(String key, Drawable drawable) { // if (drawable != null) { // if (drawable instanceof BitmapDrawable) { // return ((BitmapDrawable) drawable).getBitmap().getAllocationByteCount(); // } else { // return drawable.getIntrinsicWidth() * drawable.getIntrinsicHeight() * 2; // } // } // return super.sizeOf(key, drawable); // } // // @Override // protected void entryRemoved(boolean evicted, String key, Drawable oldValue, // Drawable newValue) { // super.entryRemoved(evicted, key, oldValue, newValue); // // } // }; // } // } // // public static void load(ImageView view, AppInfo appInfo) { // // Drawable drawable = getDrawable(view.getContext(), appInfo); // // if (drawable != null) { // view.setImageDrawable(drawable); // } else { // view.setImageResource(R.mipmap.ic_launcher); // } // } // // // public static Drawable getDrawable(Context context, AppInfo appInfo) { // init(context); // Drawable drawable = sLruCache.get(appInfo.packageName); // // if (drawable == null && appInfo.applicationInfo != null) { // if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP_MR1) { // drawable = appInfo.applicationInfo.loadUnbadgedIcon(context.getPackageManager()); // }else { // drawable = appInfo.applicationInfo.loadIcon(context.getPackageManager()); // } // UserInfo currentUser = Users.getInstance().getCurrentUser(); // if(currentUser != null && currentUser.isManagedProfile()){ // drawable = context.getPackageManager().getUserBadgedIcon(drawable,currentUser.getUserHandle()); // } // sLruCache.put(appInfo.packageName, drawable); // } // return drawable; // } // // public static void initAdd(Context context, AppInfo appInfo) { // init(context); // if (sLruCache.evictionCount() == 0) { // sLruCache // .put(appInfo.packageName, appInfo.applicationInfo.loadIcon(context.getPackageManager())); // } // } // // public static void clear(){ // sLruCache.evictAll(); // } // // } // // Path: app/src/main/java/com/zzzmode/appopsx/ui/model/AppInfo.java // public class AppInfo implements Parcelable { // // public String appName; // public String packageName; // public long time; // public long installTime; // public long updateTime; // public String pinyin; // public ApplicationInfo applicationInfo; // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // // AppInfo appInfo = (AppInfo) o; // // return packageName != null ? packageName.equals(appInfo.packageName) // : appInfo.packageName == null; // // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.appName); // dest.writeString(this.packageName); // } // // public AppInfo() { // } // // protected AppInfo(Parcel in) { // this.appName = in.readString(); // this.packageName = in.readString(); // } // // public static final Parcelable.Creator<AppInfo> CREATOR = new Parcelable.Creator<AppInfo>() { // @Override // public AppInfo createFromParcel(Parcel source) { // return new AppInfo(source); // } // // @Override // public AppInfo[] newArray(int size) { // return new AppInfo[size]; // } // }; // // // @Override // public String toString() { // return "AppInfo{" + // "appName='" + appName + '\'' + // ", packageName='" + packageName + '\'' + // '}'; // } // }
import androidx.recyclerview.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.zzzmode.appopsx.R; import com.zzzmode.appopsx.ui.core.LocalImageLoader; import com.zzzmode.appopsx.ui.model.AppInfo;
package com.zzzmode.appopsx.ui.main; /** * Created by zl on 2017/5/7. */ public class AppItemViewHolder extends RecyclerView.ViewHolder { private ImageView imgIcon; TextView tvName; public AppItemViewHolder(View itemView) { super(itemView); imgIcon = itemView.findViewById(R.id.app_icon); tvName = itemView.findViewById(R.id.app_name); } public void bindData(AppInfo appInfo) { tvName.setText(appInfo.appName);
// Path: app/src/main/java/com/zzzmode/appopsx/ui/core/LocalImageLoader.java // public class LocalImageLoader { // // private static LruCache<String, Drawable> sLruCache = null; // // private static void init(Context context) { // if (sLruCache == null) { // // ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); // int maxSize = Math.round(am.getMemoryClass() * 1024 * 1024 * 0.3f); // // sLruCache = new LruCache<String, Drawable>(maxSize) { // @Override // protected int sizeOf(String key, Drawable drawable) { // if (drawable != null) { // if (drawable instanceof BitmapDrawable) { // return ((BitmapDrawable) drawable).getBitmap().getAllocationByteCount(); // } else { // return drawable.getIntrinsicWidth() * drawable.getIntrinsicHeight() * 2; // } // } // return super.sizeOf(key, drawable); // } // // @Override // protected void entryRemoved(boolean evicted, String key, Drawable oldValue, // Drawable newValue) { // super.entryRemoved(evicted, key, oldValue, newValue); // // } // }; // } // } // // public static void load(ImageView view, AppInfo appInfo) { // // Drawable drawable = getDrawable(view.getContext(), appInfo); // // if (drawable != null) { // view.setImageDrawable(drawable); // } else { // view.setImageResource(R.mipmap.ic_launcher); // } // } // // // public static Drawable getDrawable(Context context, AppInfo appInfo) { // init(context); // Drawable drawable = sLruCache.get(appInfo.packageName); // // if (drawable == null && appInfo.applicationInfo != null) { // if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP_MR1) { // drawable = appInfo.applicationInfo.loadUnbadgedIcon(context.getPackageManager()); // }else { // drawable = appInfo.applicationInfo.loadIcon(context.getPackageManager()); // } // UserInfo currentUser = Users.getInstance().getCurrentUser(); // if(currentUser != null && currentUser.isManagedProfile()){ // drawable = context.getPackageManager().getUserBadgedIcon(drawable,currentUser.getUserHandle()); // } // sLruCache.put(appInfo.packageName, drawable); // } // return drawable; // } // // public static void initAdd(Context context, AppInfo appInfo) { // init(context); // if (sLruCache.evictionCount() == 0) { // sLruCache // .put(appInfo.packageName, appInfo.applicationInfo.loadIcon(context.getPackageManager())); // } // } // // public static void clear(){ // sLruCache.evictAll(); // } // // } // // Path: app/src/main/java/com/zzzmode/appopsx/ui/model/AppInfo.java // public class AppInfo implements Parcelable { // // public String appName; // public String packageName; // public long time; // public long installTime; // public long updateTime; // public String pinyin; // public ApplicationInfo applicationInfo; // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // // AppInfo appInfo = (AppInfo) o; // // return packageName != null ? packageName.equals(appInfo.packageName) // : appInfo.packageName == null; // // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.appName); // dest.writeString(this.packageName); // } // // public AppInfo() { // } // // protected AppInfo(Parcel in) { // this.appName = in.readString(); // this.packageName = in.readString(); // } // // public static final Parcelable.Creator<AppInfo> CREATOR = new Parcelable.Creator<AppInfo>() { // @Override // public AppInfo createFromParcel(Parcel source) { // return new AppInfo(source); // } // // @Override // public AppInfo[] newArray(int size) { // return new AppInfo[size]; // } // }; // // // @Override // public String toString() { // return "AppInfo{" + // "appName='" + appName + '\'' + // ", packageName='" + packageName + '\'' + // '}'; // } // } // Path: app/src/main/java/com/zzzmode/appopsx/ui/main/AppItemViewHolder.java import androidx.recyclerview.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.zzzmode.appopsx.R; import com.zzzmode.appopsx.ui.core.LocalImageLoader; import com.zzzmode.appopsx.ui.model.AppInfo; package com.zzzmode.appopsx.ui.main; /** * Created by zl on 2017/5/7. */ public class AppItemViewHolder extends RecyclerView.ViewHolder { private ImageView imgIcon; TextView tvName; public AppItemViewHolder(View itemView) { super(itemView); imgIcon = itemView.findViewById(R.id.app_icon); tvName = itemView.findViewById(R.id.app_name); } public void bindData(AppInfo appInfo) { tvName.setText(appInfo.appName);
LocalImageLoader.load(imgIcon, appInfo);
8enet/AppOpsX
app/src/main/java/com/zzzmode/appopsx/ui/model/AppOpEntry.java
// Path: opsxlib/src/main/java/com/zzzmode/appopsx/common/OpsResult.java // public class OpsResult implements Parcelable { // // private Throwable exception; // private List<PackageOps> list; // // public OpsResult(List<PackageOps> list, Throwable exception) { // this.exception = exception; // this.list = list; // } // // // public Throwable getException() { // return exception; // } // // public List<PackageOps> getList() { // return list; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeSerializable(this.exception); // dest.writeTypedList(this.list); // } // // protected OpsResult(Parcel in) { // this.exception = (Exception) in.readSerializable(); // this.list = in.createTypedArrayList(PackageOps.CREATOR); // } // // public static final Parcelable.Creator<OpsResult> CREATOR = new Parcelable.Creator<OpsResult>() { // @Override // public OpsResult createFromParcel(Parcel source) { // return new OpsResult(source); // } // // @Override // public OpsResult[] newArray(int size) { // return new OpsResult[size]; // } // }; // // // @Override // public String toString() { // return "OpsResult{" + // "exception=" + exception + // ", list=" + list + // '}'; // } // }
import com.zzzmode.appopsx.common.OpsResult;
package com.zzzmode.appopsx.ui.model; /** * Created by zl on 2016/11/24. */ public class AppOpEntry { public AppInfo appInfo;
// Path: opsxlib/src/main/java/com/zzzmode/appopsx/common/OpsResult.java // public class OpsResult implements Parcelable { // // private Throwable exception; // private List<PackageOps> list; // // public OpsResult(List<PackageOps> list, Throwable exception) { // this.exception = exception; // this.list = list; // } // // // public Throwable getException() { // return exception; // } // // public List<PackageOps> getList() { // return list; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeSerializable(this.exception); // dest.writeTypedList(this.list); // } // // protected OpsResult(Parcel in) { // this.exception = (Exception) in.readSerializable(); // this.list = in.createTypedArrayList(PackageOps.CREATOR); // } // // public static final Parcelable.Creator<OpsResult> CREATOR = new Parcelable.Creator<OpsResult>() { // @Override // public OpsResult createFromParcel(Parcel source) { // return new OpsResult(source); // } // // @Override // public OpsResult[] newArray(int size) { // return new OpsResult[size]; // } // }; // // // @Override // public String toString() { // return "OpsResult{" + // "exception=" + exception + // ", list=" + list + // '}'; // } // } // Path: app/src/main/java/com/zzzmode/appopsx/ui/model/AppOpEntry.java import com.zzzmode.appopsx.common.OpsResult; package com.zzzmode.appopsx.ui.model; /** * Created by zl on 2016/11/24. */ public class AppOpEntry { public AppInfo appInfo;
public OpsResult opsResult;
8enet/AppOpsX
app/src/main/java/com/zzzmode/appopsx/ui/main/group/IPermGroupView.java
// Path: app/src/main/java/com/zzzmode/appopsx/ui/model/PermissionGroup.java // public class PermissionGroup { // // public String group; // public String opName; // public String opPermsName; // public String opPermsLab; // public String opPermsDesc; // public int grants; // public int count; // public int icon; // public List<PermissionChildItem> apps; // // @Override // public String toString() { // return "PermissionGroup{" + // "opName='" + opName + '\'' + // ", opPermsName='" + opPermsName + '\'' + // ", opPermsLab='" + opPermsLab + '\'' + // ", opPermsDesc='" + opPermsDesc + '\'' + // ", grants=" + grants + // ", count=" + count + // ", apps=" + apps + // '}'; // } // }
import com.zzzmode.appopsx.ui.model.PermissionGroup; import java.util.List;
package com.zzzmode.appopsx.ui.main.group; /** * Created by zl on 2017/7/17. */ interface IPermGroupView { void changeTitle(int groupPosition,int childPosition,boolean allowed); void refreshItem(int groupPosition,int childPosition);
// Path: app/src/main/java/com/zzzmode/appopsx/ui/model/PermissionGroup.java // public class PermissionGroup { // // public String group; // public String opName; // public String opPermsName; // public String opPermsLab; // public String opPermsDesc; // public int grants; // public int count; // public int icon; // public List<PermissionChildItem> apps; // // @Override // public String toString() { // return "PermissionGroup{" + // "opName='" + opName + '\'' + // ", opPermsName='" + opPermsName + '\'' + // ", opPermsLab='" + opPermsLab + '\'' + // ", opPermsDesc='" + opPermsDesc + '\'' + // ", grants=" + grants + // ", count=" + count + // ", apps=" + apps + // '}'; // } // } // Path: app/src/main/java/com/zzzmode/appopsx/ui/main/group/IPermGroupView.java import com.zzzmode.appopsx.ui.model.PermissionGroup; import java.util.List; package com.zzzmode.appopsx.ui.main.group; /** * Created by zl on 2017/7/17. */ interface IPermGroupView { void changeTitle(int groupPosition,int childPosition,boolean allowed); void refreshItem(int groupPosition,int childPosition);
void showList(List<PermissionGroup> value);
8enet/AppOpsX
opsxlib/src/main/java/com/zzzmode/appopsx/common/SystemServiceCaller.java
// Path: opsxlib/src/main/java/com/zzzmode/appopsx/common/BaseCaller.java // public static final int TYPE_SYSTEM_SERVICE=1;
import static com.zzzmode.appopsx.common.BaseCaller.TYPE_SYSTEM_SERVICE; import android.os.Parcel; import android.os.Parcelable;
@Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.serviceName); dest.writeString(this.methodName); dest.writeStringArray(this.sParamsType); dest.writeArray(this.params); } protected SystemServiceCaller(Parcel in) { this.serviceName = in.readString(); this.methodName = in.readString(); this.sParamsType = in.createStringArray(); this.params = in.readArray(Object[].class.getClassLoader()); } public static final Parcelable.Creator<SystemServiceCaller> CREATOR = new Parcelable.Creator<SystemServiceCaller>() { @Override public SystemServiceCaller createFromParcel(Parcel source) { return new SystemServiceCaller(source); } @Override public SystemServiceCaller[] newArray(int size) { return new SystemServiceCaller[size]; } }; @Override public int getType() {
// Path: opsxlib/src/main/java/com/zzzmode/appopsx/common/BaseCaller.java // public static final int TYPE_SYSTEM_SERVICE=1; // Path: opsxlib/src/main/java/com/zzzmode/appopsx/common/SystemServiceCaller.java import static com.zzzmode.appopsx.common.BaseCaller.TYPE_SYSTEM_SERVICE; import android.os.Parcel; import android.os.Parcelable; @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.serviceName); dest.writeString(this.methodName); dest.writeStringArray(this.sParamsType); dest.writeArray(this.params); } protected SystemServiceCaller(Parcel in) { this.serviceName = in.readString(); this.methodName = in.readString(); this.sParamsType = in.createStringArray(); this.params = in.readArray(Object[].class.getClassLoader()); } public static final Parcelable.Creator<SystemServiceCaller> CREATOR = new Parcelable.Creator<SystemServiceCaller>() { @Override public SystemServiceCaller createFromParcel(Parcel source) { return new SystemServiceCaller(source); } @Override public SystemServiceCaller[] newArray(int size) { return new SystemServiceCaller[size]; } }; @Override public int getType() {
return TYPE_SYSTEM_SERVICE;
DeOldSax/iliasDownloaderTool
src/main/java/plugin/IliasPlugin.java
// Path: src/main/java/model/persistance/Settings.java // public class Settings { // // old Settings path in registry // // myPrefs = prefsRoot.node("DownloaderTool.preferences"); // // // methode to remove all entries: // // public void removeNode() { // // try { // // myPrefs.removeNode(); // // } catch (BackingStoreException e) { // // e.printStackTrace(); // // } // // } // private static final String ILIAS_STORE_FOLDER = System.getProperty("user.home") + "/" // + ".ilias"; // private static Settings instance; // private Storer storer; // private List<Storable> storableObjects; // // private User user; // private Flags flags; // private FileStates fileStates; // private IliasFolderSettings iliasFolderSettings; // // private Settings() { // storableObjects = new ArrayList<Storable>(); // storer = new Storer(ILIAS_STORE_FOLDER); // } // // public static Settings getInstance() { // if (instance == null) { // instance = new Settings(); // } // return instance; // } // // public User getUser() { // if (user == null) { // user = (User) load(new User()); // if (user == null) { // user = new User(); // } // storableObjects.add(user); // } // return user; // } // // public Flags getFlags() { // if (flags == null) { // flags = (Flags) load(new Flags()); // if (flags == null) { // flags = new Flags(); // } // storableObjects.add(flags); // } // return flags; // // } // // public FileStates getFileStates() { // if (fileStates == null) { // fileStates = (FileStates) load(new FileStates()); // if (fileStates == null) { // fileStates = new FileStates(); // } // storableObjects.add(fileStates); // } // return fileStates; // } // // public IliasFolderSettings getIliasFolderSettings() { // if (iliasFolderSettings == null) { // iliasFolderSettings = (IliasFolderSettings) load(new IliasFolderSettings()); // if (iliasFolderSettings == null) { // iliasFolderSettings = new IliasFolderSettings(); // } // storableObjects.add(iliasFolderSettings); // } // return iliasFolderSettings; // } // // public void toggleFileIgnored(IliasFile file) { // if (file.isIgnored()) { // file.setIgnored(false); // } else { // file.setIgnored(true); // } // } // // private Storable load(Storable storeable) { // storeable = storer.load(storeable); // return storeable; // } // // public void store() { // for (Storable storableObject : storableObjects) { // storer.store(storableObject); // } // } // // }
import java.io.IOException; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import org.apache.http.client.CookieStore; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.*; import org.apache.http.ssl.SSLContextBuilder; import model.persistance.Settings;
package plugin; public abstract class IliasPlugin { public enum LoginStatus { WRONG_PASSWORD, CONNECTION_FAILED, SUCCESS }; protected CloseableHttpClient client; private CookieStore cookieStore; private SSLContext sslContext; public IliasPlugin() { newClient(); } public final CloseableHttpClient getClient() { CookieStore clonedCookieStore = new BasicCookieStore(); for (Cookie cookie : this.cookieStore.getCookies()) { clonedCookieStore.addCookie(cookie); } CloseableHttpClient clonedClient;
// Path: src/main/java/model/persistance/Settings.java // public class Settings { // // old Settings path in registry // // myPrefs = prefsRoot.node("DownloaderTool.preferences"); // // // methode to remove all entries: // // public void removeNode() { // // try { // // myPrefs.removeNode(); // // } catch (BackingStoreException e) { // // e.printStackTrace(); // // } // // } // private static final String ILIAS_STORE_FOLDER = System.getProperty("user.home") + "/" // + ".ilias"; // private static Settings instance; // private Storer storer; // private List<Storable> storableObjects; // // private User user; // private Flags flags; // private FileStates fileStates; // private IliasFolderSettings iliasFolderSettings; // // private Settings() { // storableObjects = new ArrayList<Storable>(); // storer = new Storer(ILIAS_STORE_FOLDER); // } // // public static Settings getInstance() { // if (instance == null) { // instance = new Settings(); // } // return instance; // } // // public User getUser() { // if (user == null) { // user = (User) load(new User()); // if (user == null) { // user = new User(); // } // storableObjects.add(user); // } // return user; // } // // public Flags getFlags() { // if (flags == null) { // flags = (Flags) load(new Flags()); // if (flags == null) { // flags = new Flags(); // } // storableObjects.add(flags); // } // return flags; // // } // // public FileStates getFileStates() { // if (fileStates == null) { // fileStates = (FileStates) load(new FileStates()); // if (fileStates == null) { // fileStates = new FileStates(); // } // storableObjects.add(fileStates); // } // return fileStates; // } // // public IliasFolderSettings getIliasFolderSettings() { // if (iliasFolderSettings == null) { // iliasFolderSettings = (IliasFolderSettings) load(new IliasFolderSettings()); // if (iliasFolderSettings == null) { // iliasFolderSettings = new IliasFolderSettings(); // } // storableObjects.add(iliasFolderSettings); // } // return iliasFolderSettings; // } // // public void toggleFileIgnored(IliasFile file) { // if (file.isIgnored()) { // file.setIgnored(false); // } else { // file.setIgnored(true); // } // } // // private Storable load(Storable storeable) { // storeable = storer.load(storeable); // return storeable; // } // // public void store() { // for (Storable storableObject : storableObjects) { // storer.store(storableObject); // } // } // // } // Path: src/main/java/plugin/IliasPlugin.java import java.io.IOException; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import org.apache.http.client.CookieStore; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.*; import org.apache.http.ssl.SSLContextBuilder; import model.persistance.Settings; package plugin; public abstract class IliasPlugin { public enum LoginStatus { WRONG_PASSWORD, CONNECTION_FAILED, SUCCESS }; protected CloseableHttpClient client; private CookieStore cookieStore; private SSLContext sslContext; public IliasPlugin() { newClient(); } public final CloseableHttpClient getClient() { CookieStore clonedCookieStore = new BasicCookieStore(); for (Cookie cookie : this.cookieStore.getCookies()) { clonedCookieStore.addCookie(cookie); } CloseableHttpClient clonedClient;
if (!Settings.getInstance().getFlags().isConnectSecure()) {
DeOldSax/iliasDownloaderTool
src/main/java/model/persistance/IliasTreeProvider.java
// Path: src/main/java/model/IliasFile.java // @Slf4j // public class IliasFile extends IliasTreeNode { // // private static final long serialVersionUID = -6286982393008142116L; // private final int size; // private final String extension; // private final String sizeLabel; // // public IliasFile(String name, String url, IliasFolder parentFolder, int size, String sizeLabel, // String extension) { // super(name, url, parentFolder); // this.size = size; // this.extension = extension; // this.sizeLabel = sizeLabel; // } // // public int getSize() { // return size; // } // // public boolean isIgnored() { // return Settings.getInstance().getFileStates().isIgnored(createStoreKey()) != -1; // } // // public void setIgnored(boolean b) { // if (b) { // Settings.getInstance().getFileStates() // .storeIgnoredFileSize(createStoreKey(), getSize()); // } else { // Settings.getInstance().getFileStates().removeIgnoredFileSize(createStoreKey()); // } // } // // private String createStoreKey() { // String url = super.getUrl(); // Matcher matcher = Pattern.compile("(.*?)(\\d{3,})(.*)").matcher(url); // String digits = ""; // // if (matcher.find()) { // digits = matcher.group(2); // } else { // log.warn("StoreKey digits not found!"); // } // // return digits; // } // // @Override // public final ImageView getGraphic() { // FileAppearanceManager appearanceManager = FileAppearanceManager.getInstance(); // if (isIgnored()) { // return appearanceManager.getIgnoredPicture(getExtension()); // } else if (!(LocalFileStorage.getInstance().contains(this))) { // return appearanceManager.getNotSynchronizedPicture(getExtension()); // } else { // return appearanceManager.getNormalPicture(getExtension()); // } // } // // /** // * Returns the files {@link #extension}. e. g. "pdf" or "txt" <br> // * <b>NOT</b> .pdf ! // * // * @return {@link #extension} // */ // public String getExtension() { // return extension; // } // // public String getSizeLabel() { // return sizeLabel; // } // } // // Path: src/main/java/model/IliasFolder.java // public class IliasFolder extends IliasTreeNode { // private static final long serialVersionUID = 6134132849917192741L; // private final List<IliasTreeNode> childFolders; // // public IliasFolder(String name, String url, IliasFolder parentDirectory) { // super(name, url, parentDirectory); // this.childFolders = new ArrayList<IliasTreeNode>(); // } // // public List<IliasTreeNode> getChildNodes() { // return childFolders; // } // // @Override // public ImageView getGraphic() { // if (LocalFileStorage.getInstance().isFolderSynchronized(this)) { // return new ImageView("img/folder.png"); // } else { // return new ImageView("img/folder_pdf_not_there.png"); // } // } // } // // Path: src/main/java/model/IliasTreeNode.java // public abstract class IliasTreeNode implements Serializable { // private static final long serialVersionUID = -5666402232004312659L; // private final String url; // private final String name; // private String nameChangedByUser; // private final IliasFolder parentFolder; // // public IliasTreeNode(String name, String url, IliasFolder parentFolder) { // this.name = name; // this.url = url; // if (parentFolder != null) { // parentFolder.getChildNodes().add(this); // } // this.parentFolder = parentFolder; // this.nameChangedByUser = null; // } // // public abstract ImageView getGraphic(); // // public String getUrl() { // return url; // } // // public String getName() { // return name; // } // // public void setNameChangedByUser(String nameChangedByUser) { // this.nameChangedByUser = nameChangedByUser; // } // // public IliasFolder getParentFolder() { // return parentFolder; // } // // public IliasTreeNode getRootCourse() { // return getRoot(this); // } // // private IliasTreeNode getRoot(IliasTreeNode directory) { // if (directory.getParentFolder() == null) { // return directory; // } // return getRoot(directory.getParentFolder()); // } // // @Override // public String toString() { // if (nameChangedByUser != null) { // return nameChangedByUser; // } // return name; // } // // }
import java.util.ArrayList; import java.util.List; import model.IliasFile; import model.IliasFolder; import model.IliasTreeNode;
package model.persistance; public class IliasTreeProvider { private static List<IliasFolder> allFiles = null;
// Path: src/main/java/model/IliasFile.java // @Slf4j // public class IliasFile extends IliasTreeNode { // // private static final long serialVersionUID = -6286982393008142116L; // private final int size; // private final String extension; // private final String sizeLabel; // // public IliasFile(String name, String url, IliasFolder parentFolder, int size, String sizeLabel, // String extension) { // super(name, url, parentFolder); // this.size = size; // this.extension = extension; // this.sizeLabel = sizeLabel; // } // // public int getSize() { // return size; // } // // public boolean isIgnored() { // return Settings.getInstance().getFileStates().isIgnored(createStoreKey()) != -1; // } // // public void setIgnored(boolean b) { // if (b) { // Settings.getInstance().getFileStates() // .storeIgnoredFileSize(createStoreKey(), getSize()); // } else { // Settings.getInstance().getFileStates().removeIgnoredFileSize(createStoreKey()); // } // } // // private String createStoreKey() { // String url = super.getUrl(); // Matcher matcher = Pattern.compile("(.*?)(\\d{3,})(.*)").matcher(url); // String digits = ""; // // if (matcher.find()) { // digits = matcher.group(2); // } else { // log.warn("StoreKey digits not found!"); // } // // return digits; // } // // @Override // public final ImageView getGraphic() { // FileAppearanceManager appearanceManager = FileAppearanceManager.getInstance(); // if (isIgnored()) { // return appearanceManager.getIgnoredPicture(getExtension()); // } else if (!(LocalFileStorage.getInstance().contains(this))) { // return appearanceManager.getNotSynchronizedPicture(getExtension()); // } else { // return appearanceManager.getNormalPicture(getExtension()); // } // } // // /** // * Returns the files {@link #extension}. e. g. "pdf" or "txt" <br> // * <b>NOT</b> .pdf ! // * // * @return {@link #extension} // */ // public String getExtension() { // return extension; // } // // public String getSizeLabel() { // return sizeLabel; // } // } // // Path: src/main/java/model/IliasFolder.java // public class IliasFolder extends IliasTreeNode { // private static final long serialVersionUID = 6134132849917192741L; // private final List<IliasTreeNode> childFolders; // // public IliasFolder(String name, String url, IliasFolder parentDirectory) { // super(name, url, parentDirectory); // this.childFolders = new ArrayList<IliasTreeNode>(); // } // // public List<IliasTreeNode> getChildNodes() { // return childFolders; // } // // @Override // public ImageView getGraphic() { // if (LocalFileStorage.getInstance().isFolderSynchronized(this)) { // return new ImageView("img/folder.png"); // } else { // return new ImageView("img/folder_pdf_not_there.png"); // } // } // } // // Path: src/main/java/model/IliasTreeNode.java // public abstract class IliasTreeNode implements Serializable { // private static final long serialVersionUID = -5666402232004312659L; // private final String url; // private final String name; // private String nameChangedByUser; // private final IliasFolder parentFolder; // // public IliasTreeNode(String name, String url, IliasFolder parentFolder) { // this.name = name; // this.url = url; // if (parentFolder != null) { // parentFolder.getChildNodes().add(this); // } // this.parentFolder = parentFolder; // this.nameChangedByUser = null; // } // // public abstract ImageView getGraphic(); // // public String getUrl() { // return url; // } // // public String getName() { // return name; // } // // public void setNameChangedByUser(String nameChangedByUser) { // this.nameChangedByUser = nameChangedByUser; // } // // public IliasFolder getParentFolder() { // return parentFolder; // } // // public IliasTreeNode getRootCourse() { // return getRoot(this); // } // // private IliasTreeNode getRoot(IliasTreeNode directory) { // if (directory.getParentFolder() == null) { // return directory; // } // return getRoot(directory.getParentFolder()); // } // // @Override // public String toString() { // if (nameChangedByUser != null) { // return nameChangedByUser; // } // return name; // } // // } // Path: src/main/java/model/persistance/IliasTreeProvider.java import java.util.ArrayList; import java.util.List; import model.IliasFile; import model.IliasFolder; import model.IliasTreeNode; package model.persistance; public class IliasTreeProvider { private static List<IliasFolder> allFiles = null;
public static List<IliasFile> getAllIliasFiles() {
DeOldSax/iliasDownloaderTool
src/main/java/view/Dashboard.java
// Path: src/main/java/analytics/ActionType.java // public enum ActionType { // START, STOP, SYNCHRONIZE // } // // Path: src/main/java/analytics/AnalyticsLogger.java // public class AnalyticsLogger { // // public static String url = "https://www.iliasdownloadertool.de/api/v1/analytics"; // // public static AnalyticsLogger logger; // // private final String sessionID; // // private final String iliasVersion; // // private final String userID; // // private final String iliasPortal; // // private AnalyticsLogger() { // this.sessionID = generateSessionID(); // this.iliasVersion = new VersionValidator().getVersion(); // this.userID = generateUserID(); // this.iliasPortal = IliasManager.getInstance().getShortName(); // } // // public static AnalyticsLogger getInstance() { // if (logger == null) { // logger = new AnalyticsLogger(); // } // return logger; // } // // private String generateUserID() { // String pluginShortName = IliasManager.getInstance().getShortName(); // User user = Settings.getInstance().getUser(); // // if (user.getName() == null) { // return hash("init"); // } else { // String name = hash(user.getName()); // return hash(name + hash(pluginShortName) + hash("G(xpt+OgoLltz5b#e(Bu-YcYF$cokfmp9349fdjd!-4sdvf2")); // } // } // // private String generateSessionID() { // return hash(UUID.randomUUID().toString()); // } // // public void log(Enum actionType) { // new Thread(() -> { // CloseableHttpClient client = HttpClients.createDefault(); // // HttpPost httpPost = new HttpPost(url); // // SessionLog sessionLog = new SessionLog(this.userID, this.sessionID, actionType, // this.iliasVersion, this.iliasPortal); // // StringEntity entity; // try { // entity = new StringEntity(sessionLog.toJson()); // httpPost.setEntity(entity); // httpPost.setHeader("Accept", "application/json"); // httpPost.setHeader("Content-type", "application/json"); // // client.execute(httpPost); // client.close(); // } catch (Exception e) { // e.printStackTrace(); // } // }).start(); // } // // private String hash(String s) { // SHA3.DigestSHA3 digestSHA3 = new SHA3.Digest256(); // byte[] digest = digestSHA3.digest(s.getBytes()); // // return Hex.toHexString(digest); // } // // }
import java.io.*; import java.security.*; import analytics.ActionType; import analytics.AnalyticsLogger; import javafx.animation.*; import javafx.application.*; import javafx.concurrent.*; import javafx.event.*; import javafx.geometry.*; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.image.*; import javafx.scene.layout.*; import javafx.scene.web.*; import javafx.stage.*; import javafx.util.*; import lombok.extern.slf4j.Slf4j; import model.*; import model.persistance.*; import org.bouncycastle.jce.provider.*; import org.controlsfx.control.textfield.*; import control.*;
package view; @Slf4j public class Dashboard extends Application { private Dashboard dashboard; private Stage stage; private Scene scene; private LoginFader loginFader; private SplitPane splitPane; private StackPane stackPane; private GridPane actualisationTimePane; private BorderPane background; private WebView webView; private static Label lastUpdateTime; private static ResultList resultList; private Button settingsButton; private Button refreshButton; private static Label statusFooterText; private static CoursesTreeView courses; private Button signIn; private GridPane actionBar; private LoginFader loginFader2; private boolean loaderRunning; private CustomTextField searchField; private Button showLocalNotThere; private Button showIgnored; private RotateTransition refreshTransition; static { Security.insertProviderAt(new BouncyCastleProvider(), 1); } public static void main(String[] args) {
// Path: src/main/java/analytics/ActionType.java // public enum ActionType { // START, STOP, SYNCHRONIZE // } // // Path: src/main/java/analytics/AnalyticsLogger.java // public class AnalyticsLogger { // // public static String url = "https://www.iliasdownloadertool.de/api/v1/analytics"; // // public static AnalyticsLogger logger; // // private final String sessionID; // // private final String iliasVersion; // // private final String userID; // // private final String iliasPortal; // // private AnalyticsLogger() { // this.sessionID = generateSessionID(); // this.iliasVersion = new VersionValidator().getVersion(); // this.userID = generateUserID(); // this.iliasPortal = IliasManager.getInstance().getShortName(); // } // // public static AnalyticsLogger getInstance() { // if (logger == null) { // logger = new AnalyticsLogger(); // } // return logger; // } // // private String generateUserID() { // String pluginShortName = IliasManager.getInstance().getShortName(); // User user = Settings.getInstance().getUser(); // // if (user.getName() == null) { // return hash("init"); // } else { // String name = hash(user.getName()); // return hash(name + hash(pluginShortName) + hash("G(xpt+OgoLltz5b#e(Bu-YcYF$cokfmp9349fdjd!-4sdvf2")); // } // } // // private String generateSessionID() { // return hash(UUID.randomUUID().toString()); // } // // public void log(Enum actionType) { // new Thread(() -> { // CloseableHttpClient client = HttpClients.createDefault(); // // HttpPost httpPost = new HttpPost(url); // // SessionLog sessionLog = new SessionLog(this.userID, this.sessionID, actionType, // this.iliasVersion, this.iliasPortal); // // StringEntity entity; // try { // entity = new StringEntity(sessionLog.toJson()); // httpPost.setEntity(entity); // httpPost.setHeader("Accept", "application/json"); // httpPost.setHeader("Content-type", "application/json"); // // client.execute(httpPost); // client.close(); // } catch (Exception e) { // e.printStackTrace(); // } // }).start(); // } // // private String hash(String s) { // SHA3.DigestSHA3 digestSHA3 = new SHA3.Digest256(); // byte[] digest = digestSHA3.digest(s.getBytes()); // // return Hex.toHexString(digest); // } // // } // Path: src/main/java/view/Dashboard.java import java.io.*; import java.security.*; import analytics.ActionType; import analytics.AnalyticsLogger; import javafx.animation.*; import javafx.application.*; import javafx.concurrent.*; import javafx.event.*; import javafx.geometry.*; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.image.*; import javafx.scene.layout.*; import javafx.scene.web.*; import javafx.stage.*; import javafx.util.*; import lombok.extern.slf4j.Slf4j; import model.*; import model.persistance.*; import org.bouncycastle.jce.provider.*; import org.controlsfx.control.textfield.*; import control.*; package view; @Slf4j public class Dashboard extends Application { private Dashboard dashboard; private Stage stage; private Scene scene; private LoginFader loginFader; private SplitPane splitPane; private StackPane stackPane; private GridPane actualisationTimePane; private BorderPane background; private WebView webView; private static Label lastUpdateTime; private static ResultList resultList; private Button settingsButton; private Button refreshButton; private static Label statusFooterText; private static CoursesTreeView courses; private Button signIn; private GridPane actionBar; private LoginFader loginFader2; private boolean loaderRunning; private CustomTextField searchField; private Button showLocalNotThere; private Button showIgnored; private RotateTransition refreshTransition; static { Security.insertProviderAt(new BouncyCastleProvider(), 1); } public static void main(String[] args) {
AnalyticsLogger analyticsLogger = AnalyticsLogger.getInstance();
DeOldSax/iliasDownloaderTool
src/main/java/view/Dashboard.java
// Path: src/main/java/analytics/ActionType.java // public enum ActionType { // START, STOP, SYNCHRONIZE // } // // Path: src/main/java/analytics/AnalyticsLogger.java // public class AnalyticsLogger { // // public static String url = "https://www.iliasdownloadertool.de/api/v1/analytics"; // // public static AnalyticsLogger logger; // // private final String sessionID; // // private final String iliasVersion; // // private final String userID; // // private final String iliasPortal; // // private AnalyticsLogger() { // this.sessionID = generateSessionID(); // this.iliasVersion = new VersionValidator().getVersion(); // this.userID = generateUserID(); // this.iliasPortal = IliasManager.getInstance().getShortName(); // } // // public static AnalyticsLogger getInstance() { // if (logger == null) { // logger = new AnalyticsLogger(); // } // return logger; // } // // private String generateUserID() { // String pluginShortName = IliasManager.getInstance().getShortName(); // User user = Settings.getInstance().getUser(); // // if (user.getName() == null) { // return hash("init"); // } else { // String name = hash(user.getName()); // return hash(name + hash(pluginShortName) + hash("G(xpt+OgoLltz5b#e(Bu-YcYF$cokfmp9349fdjd!-4sdvf2")); // } // } // // private String generateSessionID() { // return hash(UUID.randomUUID().toString()); // } // // public void log(Enum actionType) { // new Thread(() -> { // CloseableHttpClient client = HttpClients.createDefault(); // // HttpPost httpPost = new HttpPost(url); // // SessionLog sessionLog = new SessionLog(this.userID, this.sessionID, actionType, // this.iliasVersion, this.iliasPortal); // // StringEntity entity; // try { // entity = new StringEntity(sessionLog.toJson()); // httpPost.setEntity(entity); // httpPost.setHeader("Accept", "application/json"); // httpPost.setHeader("Content-type", "application/json"); // // client.execute(httpPost); // client.close(); // } catch (Exception e) { // e.printStackTrace(); // } // }).start(); // } // // private String hash(String s) { // SHA3.DigestSHA3 digestSHA3 = new SHA3.Digest256(); // byte[] digest = digestSHA3.digest(s.getBytes()); // // return Hex.toHexString(digest); // } // // }
import java.io.*; import java.security.*; import analytics.ActionType; import analytics.AnalyticsLogger; import javafx.animation.*; import javafx.application.*; import javafx.concurrent.*; import javafx.event.*; import javafx.geometry.*; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.image.*; import javafx.scene.layout.*; import javafx.scene.web.*; import javafx.stage.*; import javafx.util.*; import lombok.extern.slf4j.Slf4j; import model.*; import model.persistance.*; import org.bouncycastle.jce.provider.*; import org.controlsfx.control.textfield.*; import control.*;
private Dashboard dashboard; private Stage stage; private Scene scene; private LoginFader loginFader; private SplitPane splitPane; private StackPane stackPane; private GridPane actualisationTimePane; private BorderPane background; private WebView webView; private static Label lastUpdateTime; private static ResultList resultList; private Button settingsButton; private Button refreshButton; private static Label statusFooterText; private static CoursesTreeView courses; private Button signIn; private GridPane actionBar; private LoginFader loginFader2; private boolean loaderRunning; private CustomTextField searchField; private Button showLocalNotThere; private Button showIgnored; private RotateTransition refreshTransition; static { Security.insertProviderAt(new BouncyCastleProvider(), 1); } public static void main(String[] args) { AnalyticsLogger analyticsLogger = AnalyticsLogger.getInstance();
// Path: src/main/java/analytics/ActionType.java // public enum ActionType { // START, STOP, SYNCHRONIZE // } // // Path: src/main/java/analytics/AnalyticsLogger.java // public class AnalyticsLogger { // // public static String url = "https://www.iliasdownloadertool.de/api/v1/analytics"; // // public static AnalyticsLogger logger; // // private final String sessionID; // // private final String iliasVersion; // // private final String userID; // // private final String iliasPortal; // // private AnalyticsLogger() { // this.sessionID = generateSessionID(); // this.iliasVersion = new VersionValidator().getVersion(); // this.userID = generateUserID(); // this.iliasPortal = IliasManager.getInstance().getShortName(); // } // // public static AnalyticsLogger getInstance() { // if (logger == null) { // logger = new AnalyticsLogger(); // } // return logger; // } // // private String generateUserID() { // String pluginShortName = IliasManager.getInstance().getShortName(); // User user = Settings.getInstance().getUser(); // // if (user.getName() == null) { // return hash("init"); // } else { // String name = hash(user.getName()); // return hash(name + hash(pluginShortName) + hash("G(xpt+OgoLltz5b#e(Bu-YcYF$cokfmp9349fdjd!-4sdvf2")); // } // } // // private String generateSessionID() { // return hash(UUID.randomUUID().toString()); // } // // public void log(Enum actionType) { // new Thread(() -> { // CloseableHttpClient client = HttpClients.createDefault(); // // HttpPost httpPost = new HttpPost(url); // // SessionLog sessionLog = new SessionLog(this.userID, this.sessionID, actionType, // this.iliasVersion, this.iliasPortal); // // StringEntity entity; // try { // entity = new StringEntity(sessionLog.toJson()); // httpPost.setEntity(entity); // httpPost.setHeader("Accept", "application/json"); // httpPost.setHeader("Content-type", "application/json"); // // client.execute(httpPost); // client.close(); // } catch (Exception e) { // e.printStackTrace(); // } // }).start(); // } // // private String hash(String s) { // SHA3.DigestSHA3 digestSHA3 = new SHA3.Digest256(); // byte[] digest = digestSHA3.digest(s.getBytes()); // // return Hex.toHexString(digest); // } // // } // Path: src/main/java/view/Dashboard.java import java.io.*; import java.security.*; import analytics.ActionType; import analytics.AnalyticsLogger; import javafx.animation.*; import javafx.application.*; import javafx.concurrent.*; import javafx.event.*; import javafx.geometry.*; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.image.*; import javafx.scene.layout.*; import javafx.scene.web.*; import javafx.stage.*; import javafx.util.*; import lombok.extern.slf4j.Slf4j; import model.*; import model.persistance.*; import org.bouncycastle.jce.provider.*; import org.controlsfx.control.textfield.*; import control.*; private Dashboard dashboard; private Stage stage; private Scene scene; private LoginFader loginFader; private SplitPane splitPane; private StackPane stackPane; private GridPane actualisationTimePane; private BorderPane background; private WebView webView; private static Label lastUpdateTime; private static ResultList resultList; private Button settingsButton; private Button refreshButton; private static Label statusFooterText; private static CoursesTreeView courses; private Button signIn; private GridPane actionBar; private LoginFader loginFader2; private boolean loaderRunning; private CustomTextField searchField; private Button showLocalNotThere; private Button showIgnored; private RotateTransition refreshTransition; static { Security.insertProviderAt(new BouncyCastleProvider(), 1); } public static void main(String[] args) { AnalyticsLogger analyticsLogger = AnalyticsLogger.getInstance();
analyticsLogger.log(ActionType.START);
DeOldSax/iliasDownloaderTool
src/main/java/control/IliasManager.java
// Path: src/main/java/plugin/IliasPlugin.java // public enum LoginStatus { // WRONG_PASSWORD, CONNECTION_FAILED, SUCCESS // };
import org.apache.http.impl.client.CloseableHttpClient; import plugin.*; import plugin.IliasPlugin.LoginStatus; import java.util.HashMap;
package control; public class IliasManager { private IliasPlugin ilias; private static IliasManager iliasManager; private IliasManager() { String magicVariable = "kn"; HashMap<String, IliasPlugin> map = new HashMap<>(); map.put("kn", new KNIlias()); map.put("kit", new KITIlias()); map.put("demo", new DemoIlias()); map.put("hsf", new HSFIlias()); map.put("tueb", new TuebIlias()); map.put("wbs", new WBSIlias()); map.put("ube", new UniBernIlias()); map.put("phtg", new PHTGIlias()); map.put("stugge", new StuggeIlias()); this.ilias = map.get(magicVariable); } public static IliasManager getInstance() { if (iliasManager == null) { iliasManager = new IliasManager(); } return iliasManager; }
// Path: src/main/java/plugin/IliasPlugin.java // public enum LoginStatus { // WRONG_PASSWORD, CONNECTION_FAILED, SUCCESS // }; // Path: src/main/java/control/IliasManager.java import org.apache.http.impl.client.CloseableHttpClient; import plugin.*; import plugin.IliasPlugin.LoginStatus; import java.util.HashMap; package control; public class IliasManager { private IliasPlugin ilias; private static IliasManager iliasManager; private IliasManager() { String magicVariable = "kn"; HashMap<String, IliasPlugin> map = new HashMap<>(); map.put("kn", new KNIlias()); map.put("kit", new KITIlias()); map.put("demo", new DemoIlias()); map.put("hsf", new HSFIlias()); map.put("tueb", new TuebIlias()); map.put("wbs", new WBSIlias()); map.put("ube", new UniBernIlias()); map.put("phtg", new PHTGIlias()); map.put("stugge", new StuggeIlias()); this.ilias = map.get(magicVariable); } public static IliasManager getInstance() { if (iliasManager == null) { iliasManager = new IliasManager(); } return iliasManager; }
public LoginStatus login(String username, String password) {
DeOldSax/iliasDownloaderTool
src/main/java/model/IliasFolder.java
// Path: src/main/java/control/LocalFileStorage.java // public class LocalFileStorage { // private static LocalFileStorage instance; // private final Map<Integer, String> localFileLocations; // // private LocalFileStorage() { // this.localFileLocations = new HashMap<Integer, String>(); // } // // public static LocalFileStorage getInstance() { // if (instance == null) { // instance = new LocalFileStorage(); // } // return instance; // } // // public void refresh() { // scanFolders(Settings.getInstance().getIliasFolderSettings().getLocalIliasFolderPath()); // } // // public Set<Integer> getAllLocalFileSizes() { // return localFileLocations.keySet(); // } // // private void scanFolders(String path) { // File dir = new File(path); // File[] files = dir.listFiles(); // // for (File file : files) { // if (file.isDirectory()) { // scanFolders(file.getAbsolutePath()); // //.zip is not detected as a "file" // } else if (file.isFile() || file.getPath().toLowerCase().endsWith(".zip")) { // localFileLocations.put((int) file.length(), file.getAbsolutePath()); // } // } // } // // public boolean contains(IliasFile iliasFile) { // return localFileLocations.containsKey(iliasFile.getSize()); // } // // public void addIliasFile(IliasFile iliasFile, String path) { // localFileLocations.put(iliasFile.getSize(), path); // } // // public boolean isFolderSynchronized(IliasFolder folder) { // for (IliasTreeNode node : folder.getChildNodes()) { // if (node instanceof IliasFile) { // IliasFile iliasFile = (IliasFile) node; // if (!contains(iliasFile) && !iliasFile.isIgnored()) { // return false; // } // } else if (node instanceof IliasFolder) { // if (!isFolderSynchronized((IliasFolder) node)) { // return false; // } // } // } // return true; // } // // public String suggestDownloadPath(IliasFile iliasFile) { // final List<IliasTreeNode> siblings = iliasFile.getParentFolder().getChildNodes(); // for (IliasTreeNode node : siblings) { // if (node instanceof IliasFile) { // final String result = getContainingFolder((IliasFile) node); // if (result != null) { // return result; // } // } // } // return Settings.getInstance().getIliasFolderSettings().getLocalIliasFolderPath(); // } // // private String getContainingFolder(IliasFile iliasFile) { // final int size = iliasFile.getSize(); // String path = localFileLocations.get(size); // if (path == null) { // return null; // } // path = path.substring(0, path.lastIndexOf(File.separator)); // return path; // } // // // public File getFile(IliasFile iliasFile) { // final String location = localFileLocations.get(iliasFile.getSize()); // if (location == null) { // return null; // } // return new File(location); // } // }
import java.util.ArrayList; import java.util.List; import control.LocalFileStorage; import javafx.scene.image.ImageView;
package model; public class IliasFolder extends IliasTreeNode { private static final long serialVersionUID = 6134132849917192741L; private final List<IliasTreeNode> childFolders; public IliasFolder(String name, String url, IliasFolder parentDirectory) { super(name, url, parentDirectory); this.childFolders = new ArrayList<IliasTreeNode>(); } public List<IliasTreeNode> getChildNodes() { return childFolders; } @Override public ImageView getGraphic() {
// Path: src/main/java/control/LocalFileStorage.java // public class LocalFileStorage { // private static LocalFileStorage instance; // private final Map<Integer, String> localFileLocations; // // private LocalFileStorage() { // this.localFileLocations = new HashMap<Integer, String>(); // } // // public static LocalFileStorage getInstance() { // if (instance == null) { // instance = new LocalFileStorage(); // } // return instance; // } // // public void refresh() { // scanFolders(Settings.getInstance().getIliasFolderSettings().getLocalIliasFolderPath()); // } // // public Set<Integer> getAllLocalFileSizes() { // return localFileLocations.keySet(); // } // // private void scanFolders(String path) { // File dir = new File(path); // File[] files = dir.listFiles(); // // for (File file : files) { // if (file.isDirectory()) { // scanFolders(file.getAbsolutePath()); // //.zip is not detected as a "file" // } else if (file.isFile() || file.getPath().toLowerCase().endsWith(".zip")) { // localFileLocations.put((int) file.length(), file.getAbsolutePath()); // } // } // } // // public boolean contains(IliasFile iliasFile) { // return localFileLocations.containsKey(iliasFile.getSize()); // } // // public void addIliasFile(IliasFile iliasFile, String path) { // localFileLocations.put(iliasFile.getSize(), path); // } // // public boolean isFolderSynchronized(IliasFolder folder) { // for (IliasTreeNode node : folder.getChildNodes()) { // if (node instanceof IliasFile) { // IliasFile iliasFile = (IliasFile) node; // if (!contains(iliasFile) && !iliasFile.isIgnored()) { // return false; // } // } else if (node instanceof IliasFolder) { // if (!isFolderSynchronized((IliasFolder) node)) { // return false; // } // } // } // return true; // } // // public String suggestDownloadPath(IliasFile iliasFile) { // final List<IliasTreeNode> siblings = iliasFile.getParentFolder().getChildNodes(); // for (IliasTreeNode node : siblings) { // if (node instanceof IliasFile) { // final String result = getContainingFolder((IliasFile) node); // if (result != null) { // return result; // } // } // } // return Settings.getInstance().getIliasFolderSettings().getLocalIliasFolderPath(); // } // // private String getContainingFolder(IliasFile iliasFile) { // final int size = iliasFile.getSize(); // String path = localFileLocations.get(size); // if (path == null) { // return null; // } // path = path.substring(0, path.lastIndexOf(File.separator)); // return path; // } // // // public File getFile(IliasFile iliasFile) { // final String location = localFileLocations.get(iliasFile.getSize()); // if (location == null) { // return null; // } // return new File(location); // } // } // Path: src/main/java/model/IliasFolder.java import java.util.ArrayList; import java.util.List; import control.LocalFileStorage; import javafx.scene.image.ImageView; package model; public class IliasFolder extends IliasTreeNode { private static final long serialVersionUID = 6134132849917192741L; private final List<IliasTreeNode> childFolders; public IliasFolder(String name, String url, IliasFolder parentDirectory) { super(name, url, parentDirectory); this.childFolders = new ArrayList<IliasTreeNode>(); } public List<IliasTreeNode> getChildNodes() { return childFolders; } @Override public ImageView getGraphic() {
if (LocalFileStorage.getInstance().isFolderSynchronized(this)) {
DeOldSax/iliasDownloaderTool
src/main/java/model/persistance/Settings.java
// Path: src/main/java/model/IliasFile.java // @Slf4j // public class IliasFile extends IliasTreeNode { // // private static final long serialVersionUID = -6286982393008142116L; // private final int size; // private final String extension; // private final String sizeLabel; // // public IliasFile(String name, String url, IliasFolder parentFolder, int size, String sizeLabel, // String extension) { // super(name, url, parentFolder); // this.size = size; // this.extension = extension; // this.sizeLabel = sizeLabel; // } // // public int getSize() { // return size; // } // // public boolean isIgnored() { // return Settings.getInstance().getFileStates().isIgnored(createStoreKey()) != -1; // } // // public void setIgnored(boolean b) { // if (b) { // Settings.getInstance().getFileStates() // .storeIgnoredFileSize(createStoreKey(), getSize()); // } else { // Settings.getInstance().getFileStates().removeIgnoredFileSize(createStoreKey()); // } // } // // private String createStoreKey() { // String url = super.getUrl(); // Matcher matcher = Pattern.compile("(.*?)(\\d{3,})(.*)").matcher(url); // String digits = ""; // // if (matcher.find()) { // digits = matcher.group(2); // } else { // log.warn("StoreKey digits not found!"); // } // // return digits; // } // // @Override // public final ImageView getGraphic() { // FileAppearanceManager appearanceManager = FileAppearanceManager.getInstance(); // if (isIgnored()) { // return appearanceManager.getIgnoredPicture(getExtension()); // } else if (!(LocalFileStorage.getInstance().contains(this))) { // return appearanceManager.getNotSynchronizedPicture(getExtension()); // } else { // return appearanceManager.getNormalPicture(getExtension()); // } // } // // /** // * Returns the files {@link #extension}. e. g. "pdf" or "txt" <br> // * <b>NOT</b> .pdf ! // * // * @return {@link #extension} // */ // public String getExtension() { // return extension; // } // // public String getSizeLabel() { // return sizeLabel; // } // }
import java.util.ArrayList; import java.util.List; import model.IliasFile;
flags = new Flags(); } storableObjects.add(flags); } return flags; } public FileStates getFileStates() { if (fileStates == null) { fileStates = (FileStates) load(new FileStates()); if (fileStates == null) { fileStates = new FileStates(); } storableObjects.add(fileStates); } return fileStates; } public IliasFolderSettings getIliasFolderSettings() { if (iliasFolderSettings == null) { iliasFolderSettings = (IliasFolderSettings) load(new IliasFolderSettings()); if (iliasFolderSettings == null) { iliasFolderSettings = new IliasFolderSettings(); } storableObjects.add(iliasFolderSettings); } return iliasFolderSettings; }
// Path: src/main/java/model/IliasFile.java // @Slf4j // public class IliasFile extends IliasTreeNode { // // private static final long serialVersionUID = -6286982393008142116L; // private final int size; // private final String extension; // private final String sizeLabel; // // public IliasFile(String name, String url, IliasFolder parentFolder, int size, String sizeLabel, // String extension) { // super(name, url, parentFolder); // this.size = size; // this.extension = extension; // this.sizeLabel = sizeLabel; // } // // public int getSize() { // return size; // } // // public boolean isIgnored() { // return Settings.getInstance().getFileStates().isIgnored(createStoreKey()) != -1; // } // // public void setIgnored(boolean b) { // if (b) { // Settings.getInstance().getFileStates() // .storeIgnoredFileSize(createStoreKey(), getSize()); // } else { // Settings.getInstance().getFileStates().removeIgnoredFileSize(createStoreKey()); // } // } // // private String createStoreKey() { // String url = super.getUrl(); // Matcher matcher = Pattern.compile("(.*?)(\\d{3,})(.*)").matcher(url); // String digits = ""; // // if (matcher.find()) { // digits = matcher.group(2); // } else { // log.warn("StoreKey digits not found!"); // } // // return digits; // } // // @Override // public final ImageView getGraphic() { // FileAppearanceManager appearanceManager = FileAppearanceManager.getInstance(); // if (isIgnored()) { // return appearanceManager.getIgnoredPicture(getExtension()); // } else if (!(LocalFileStorage.getInstance().contains(this))) { // return appearanceManager.getNotSynchronizedPicture(getExtension()); // } else { // return appearanceManager.getNormalPicture(getExtension()); // } // } // // /** // * Returns the files {@link #extension}. e. g. "pdf" or "txt" <br> // * <b>NOT</b> .pdf ! // * // * @return {@link #extension} // */ // public String getExtension() { // return extension; // } // // public String getSizeLabel() { // return sizeLabel; // } // } // Path: src/main/java/model/persistance/Settings.java import java.util.ArrayList; import java.util.List; import model.IliasFile; flags = new Flags(); } storableObjects.add(flags); } return flags; } public FileStates getFileStates() { if (fileStates == null) { fileStates = (FileStates) load(new FileStates()); if (fileStates == null) { fileStates = new FileStates(); } storableObjects.add(fileStates); } return fileStates; } public IliasFolderSettings getIliasFolderSettings() { if (iliasFolderSettings == null) { iliasFolderSettings = (IliasFolderSettings) load(new IliasFolderSettings()); if (iliasFolderSettings == null) { iliasFolderSettings = new IliasFolderSettings(); } storableObjects.add(iliasFolderSettings); } return iliasFolderSettings; }
public void toggleFileIgnored(IliasFile file) {
crate/crate-sample-apps
spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/PostsController.java
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/BlogPostDao.java // public interface BlogPostDao { // // List<BlogPost> getPosts(); // // Optional<BlogPost> getPost(String id); // // Optional<BlogPost> insertPost(BlogPost newPost); // // Optional<BlogPost> updatePostText(String id, String newText); // // Optional<BlogPost> incrementLikeCount(String id); // // boolean deletePost(String id); // // List<BlogPost> searchPostsWithQuery(String query); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/BlogPost.java // public class BlogPost { // // private String id; // // private User user; // // private String text; // // private Date created; // // @JsonProperty("image_ref") // private String imageRef; // // @JsonProperty("like_count") // private long likeCount; // // private String country; // // private Area area; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getImageRef() { // return imageRef; // } // // public void setImageRef(String imageRef) { // this.imageRef = imageRef; // } // // public long getLikeCount() { // return likeCount; // } // // public void setLikeCount(long likeCount) { // this.likeCount = likeCount; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public Area getArea() { // return area; // } // // public void setArea(Area area) { // this.area = area; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // BlogPost blogPost = (BlogPost) o; // return likeCount == blogPost.likeCount && // Objects.equals(id, blogPost.id) && // Objects.equals(user, blogPost.user) && // Objects.equals(text, blogPost.text) && // Objects.equals(created, blogPost.created) && // Objects.equals(imageRef, blogPost.imageRef) && // Objects.equals(country, blogPost.country) && // Objects.equals(area, blogPost.area); // } // // @Override // public int hashCode() { // return Objects.hash(id, user, text, created, imageRef, likeCount, country, area); // } // // @Override // public String toString() { // return "BlogPost{" + // "id='" + id + '\'' + // ", user=" + user + // ", text='" + text + '\'' + // ", created=" + created + // ", imageRef='" + imageRef + '\'' + // ", likeCount=" + likeCount + // ", country='" + country + '\'' + // ", area=" + area + // '}'; // } // }
import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import io.crate.spring.jdbc.samples.dao.BlogPostDao; import io.crate.spring.jdbc.samples.model.BlogPost;
package io.crate.spring.jdbc.samples; @RestController public class PostsController { private static final Log logger = LogFactory.getLog(PostsController.class); @Autowired
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/BlogPostDao.java // public interface BlogPostDao { // // List<BlogPost> getPosts(); // // Optional<BlogPost> getPost(String id); // // Optional<BlogPost> insertPost(BlogPost newPost); // // Optional<BlogPost> updatePostText(String id, String newText); // // Optional<BlogPost> incrementLikeCount(String id); // // boolean deletePost(String id); // // List<BlogPost> searchPostsWithQuery(String query); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/BlogPost.java // public class BlogPost { // // private String id; // // private User user; // // private String text; // // private Date created; // // @JsonProperty("image_ref") // private String imageRef; // // @JsonProperty("like_count") // private long likeCount; // // private String country; // // private Area area; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getImageRef() { // return imageRef; // } // // public void setImageRef(String imageRef) { // this.imageRef = imageRef; // } // // public long getLikeCount() { // return likeCount; // } // // public void setLikeCount(long likeCount) { // this.likeCount = likeCount; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public Area getArea() { // return area; // } // // public void setArea(Area area) { // this.area = area; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // BlogPost blogPost = (BlogPost) o; // return likeCount == blogPost.likeCount && // Objects.equals(id, blogPost.id) && // Objects.equals(user, blogPost.user) && // Objects.equals(text, blogPost.text) && // Objects.equals(created, blogPost.created) && // Objects.equals(imageRef, blogPost.imageRef) && // Objects.equals(country, blogPost.country) && // Objects.equals(area, blogPost.area); // } // // @Override // public int hashCode() { // return Objects.hash(id, user, text, created, imageRef, likeCount, country, area); // } // // @Override // public String toString() { // return "BlogPost{" + // "id='" + id + '\'' + // ", user=" + user + // ", text='" + text + '\'' + // ", created=" + created + // ", imageRef='" + imageRef + '\'' + // ", likeCount=" + likeCount + // ", country='" + country + '\'' + // ", area=" + area + // '}'; // } // } // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/PostsController.java import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import io.crate.spring.jdbc.samples.dao.BlogPostDao; import io.crate.spring.jdbc.samples.model.BlogPost; package io.crate.spring.jdbc.samples; @RestController public class PostsController { private static final Log logger = LogFactory.getLog(PostsController.class); @Autowired
private BlogPostDao dao;
crate/crate-sample-apps
spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/PostsController.java
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/BlogPostDao.java // public interface BlogPostDao { // // List<BlogPost> getPosts(); // // Optional<BlogPost> getPost(String id); // // Optional<BlogPost> insertPost(BlogPost newPost); // // Optional<BlogPost> updatePostText(String id, String newText); // // Optional<BlogPost> incrementLikeCount(String id); // // boolean deletePost(String id); // // List<BlogPost> searchPostsWithQuery(String query); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/BlogPost.java // public class BlogPost { // // private String id; // // private User user; // // private String text; // // private Date created; // // @JsonProperty("image_ref") // private String imageRef; // // @JsonProperty("like_count") // private long likeCount; // // private String country; // // private Area area; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getImageRef() { // return imageRef; // } // // public void setImageRef(String imageRef) { // this.imageRef = imageRef; // } // // public long getLikeCount() { // return likeCount; // } // // public void setLikeCount(long likeCount) { // this.likeCount = likeCount; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public Area getArea() { // return area; // } // // public void setArea(Area area) { // this.area = area; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // BlogPost blogPost = (BlogPost) o; // return likeCount == blogPost.likeCount && // Objects.equals(id, blogPost.id) && // Objects.equals(user, blogPost.user) && // Objects.equals(text, blogPost.text) && // Objects.equals(created, blogPost.created) && // Objects.equals(imageRef, blogPost.imageRef) && // Objects.equals(country, blogPost.country) && // Objects.equals(area, blogPost.area); // } // // @Override // public int hashCode() { // return Objects.hash(id, user, text, created, imageRef, likeCount, country, area); // } // // @Override // public String toString() { // return "BlogPost{" + // "id='" + id + '\'' + // ", user=" + user + // ", text='" + text + '\'' + // ", created=" + created + // ", imageRef='" + imageRef + '\'' + // ", likeCount=" + likeCount + // ", country='" + country + '\'' + // ", area=" + area + // '}'; // } // }
import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import io.crate.spring.jdbc.samples.dao.BlogPostDao; import io.crate.spring.jdbc.samples.model.BlogPost;
} var newPost = dao.insertPost(postsDeserializer.fromMap(postProps)).orElseThrow(() -> new PostNotFoundException("new from insert")); return List.of(postsSerializer.serialize(newPost)); } @GetMapping("/post/{id}") public Map<String, Object> getPost(@PathVariable String id) { logger.debug("Searching for post with id '" + id + "' in database"); return postsSerializer.serialize(dao.getPost(id).orElseThrow(() -> new PostNotFoundException(id))); } @PutMapping("/post/{id}") public Map<String, Object> updatePost(@PathVariable String id, @RequestBody Map<String, Object> postProps) { logger.debug("Updating post with id '" + id + "' in database"); if (postProps == null) { throw new ArgumentRequiredException("Request body is required"); } else if (!postProps.containsKey("text")) { throw new ArgumentRequiredException("Argument \"text\" is required"); } String text = postProps != null ? postProps.get("text").toString() : null; return postsSerializer.serialize(dao.updatePostText(id, text).orElseThrow(() -> new PostNotFoundException(id))); } @PutMapping("/post/{id}/like") public Map<String, Object> incrementLikeCount(@PathVariable String id) { logger.debug("Incrementing like count of post with id " + id);
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/BlogPostDao.java // public interface BlogPostDao { // // List<BlogPost> getPosts(); // // Optional<BlogPost> getPost(String id); // // Optional<BlogPost> insertPost(BlogPost newPost); // // Optional<BlogPost> updatePostText(String id, String newText); // // Optional<BlogPost> incrementLikeCount(String id); // // boolean deletePost(String id); // // List<BlogPost> searchPostsWithQuery(String query); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/BlogPost.java // public class BlogPost { // // private String id; // // private User user; // // private String text; // // private Date created; // // @JsonProperty("image_ref") // private String imageRef; // // @JsonProperty("like_count") // private long likeCount; // // private String country; // // private Area area; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getImageRef() { // return imageRef; // } // // public void setImageRef(String imageRef) { // this.imageRef = imageRef; // } // // public long getLikeCount() { // return likeCount; // } // // public void setLikeCount(long likeCount) { // this.likeCount = likeCount; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public Area getArea() { // return area; // } // // public void setArea(Area area) { // this.area = area; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // BlogPost blogPost = (BlogPost) o; // return likeCount == blogPost.likeCount && // Objects.equals(id, blogPost.id) && // Objects.equals(user, blogPost.user) && // Objects.equals(text, blogPost.text) && // Objects.equals(created, blogPost.created) && // Objects.equals(imageRef, blogPost.imageRef) && // Objects.equals(country, blogPost.country) && // Objects.equals(area, blogPost.area); // } // // @Override // public int hashCode() { // return Objects.hash(id, user, text, created, imageRef, likeCount, country, area); // } // // @Override // public String toString() { // return "BlogPost{" + // "id='" + id + '\'' + // ", user=" + user + // ", text='" + text + '\'' + // ", created=" + created + // ", imageRef='" + imageRef + '\'' + // ", likeCount=" + likeCount + // ", country='" + country + '\'' + // ", area=" + area + // '}'; // } // } // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/PostsController.java import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import io.crate.spring.jdbc.samples.dao.BlogPostDao; import io.crate.spring.jdbc.samples.model.BlogPost; } var newPost = dao.insertPost(postsDeserializer.fromMap(postProps)).orElseThrow(() -> new PostNotFoundException("new from insert")); return List.of(postsSerializer.serialize(newPost)); } @GetMapping("/post/{id}") public Map<String, Object> getPost(@PathVariable String id) { logger.debug("Searching for post with id '" + id + "' in database"); return postsSerializer.serialize(dao.getPost(id).orElseThrow(() -> new PostNotFoundException(id))); } @PutMapping("/post/{id}") public Map<String, Object> updatePost(@PathVariable String id, @RequestBody Map<String, Object> postProps) { logger.debug("Updating post with id '" + id + "' in database"); if (postProps == null) { throw new ArgumentRequiredException("Request body is required"); } else if (!postProps.containsKey("text")) { throw new ArgumentRequiredException("Argument \"text\" is required"); } String text = postProps != null ? postProps.get("text").toString() : null; return postsSerializer.serialize(dao.updatePostText(id, text).orElseThrow(() -> new PostNotFoundException(id))); } @PutMapping("/post/{id}/like") public Map<String, Object> incrementLikeCount(@PathVariable String id) { logger.debug("Incrementing like count of post with id " + id);
BlogPost post = dao.incrementLikeCount(id).orElseThrow(() -> new PostNotFoundException(id));
crate/crate-sample-apps
spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/ImagesController.java
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/ImagesDao.java // public interface ImagesDao { // // boolean imageExists(String digest); // // List<Image> getImages(); // // InputStream getImageAsInputStream(String digest); // // boolean deleteImage(String digest); // // Map<String, String> insertImage(String digest, byte[] decoded); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/Image.java // public class Image { // // private final String digest; // // @JsonProperty("last_modified") // private final Date lastModified; // // public Image(String digest, Date last_modified) { // this.digest = digest; // this.lastModified = last_modified; // } // // public String getDigest() { // return digest; // } // // public Date getLastModified() { // return lastModified; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Image image = (Image) o; // return Objects.equals(digest, image.digest) && // Objects.equals(lastModified, image.lastModified); // } // // @Override // public int hashCode() { // return Objects.hash(digest, lastModified); // } // }
import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import io.crate.spring.jdbc.samples.dao.ImagesDao; import io.crate.spring.jdbc.samples.model.Image;
package io.crate.spring.jdbc.samples; @RestController public class ImagesController { private static final Log logger = LogFactory.getLog(ImagesController.class); @Autowired
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/ImagesDao.java // public interface ImagesDao { // // boolean imageExists(String digest); // // List<Image> getImages(); // // InputStream getImageAsInputStream(String digest); // // boolean deleteImage(String digest); // // Map<String, String> insertImage(String digest, byte[] decoded); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/Image.java // public class Image { // // private final String digest; // // @JsonProperty("last_modified") // private final Date lastModified; // // public Image(String digest, Date last_modified) { // this.digest = digest; // this.lastModified = last_modified; // } // // public String getDigest() { // return digest; // } // // public Date getLastModified() { // return lastModified; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Image image = (Image) o; // return Objects.equals(digest, image.digest) && // Objects.equals(lastModified, image.lastModified); // } // // @Override // public int hashCode() { // return Objects.hash(digest, lastModified); // } // } // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/ImagesController.java import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import io.crate.spring.jdbc.samples.dao.ImagesDao; import io.crate.spring.jdbc.samples.model.Image; package io.crate.spring.jdbc.samples; @RestController public class ImagesController { private static final Log logger = LogFactory.getLog(ImagesController.class); @Autowired
private ImagesDao dao;
crate/crate-sample-apps
spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/ImagesController.java
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/ImagesDao.java // public interface ImagesDao { // // boolean imageExists(String digest); // // List<Image> getImages(); // // InputStream getImageAsInputStream(String digest); // // boolean deleteImage(String digest); // // Map<String, String> insertImage(String digest, byte[] decoded); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/Image.java // public class Image { // // private final String digest; // // @JsonProperty("last_modified") // private final Date lastModified; // // public Image(String digest, Date last_modified) { // this.digest = digest; // this.lastModified = last_modified; // } // // public String getDigest() { // return digest; // } // // public Date getLastModified() { // return lastModified; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Image image = (Image) o; // return Objects.equals(digest, image.digest) && // Objects.equals(lastModified, image.lastModified); // } // // @Override // public int hashCode() { // return Objects.hash(digest, lastModified); // } // }
import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import io.crate.spring.jdbc.samples.dao.ImagesDao; import io.crate.spring.jdbc.samples.model.Image;
} } @DeleteMapping("/image/{digest}") public void deleteImage(@PathVariable String digest) { logger.debug("Deleting image with digest " + digest); if (this.dao.imageExists(digest)) { this.dao.deleteImage(digest); } else { throw new ImageNotExistsException(digest); } } @PostMapping("/images") public Map<String, String> insertImage(@RequestBody Map<String, Object> imageProps, HttpServletResponse response) { logger.debug("Inserting image into database"); if (imageProps == null) { throw new ArgumentRequiredException("Request body is required"); } else if (!imageProps.containsKey("blob")) { throw new ArgumentRequiredException("Argument \"blob\" is required"); } var decodedBytes = Base64.getDecoder().decode((String) imageProps.get("blob")); var digest = DigestUtils.sha1Hex(decodedBytes); var responseMap = dao.insertImage(digest, decodedBytes); response.setStatus(Integer.parseInt(responseMap.get("status"))); return responseMap; }
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/ImagesDao.java // public interface ImagesDao { // // boolean imageExists(String digest); // // List<Image> getImages(); // // InputStream getImageAsInputStream(String digest); // // boolean deleteImage(String digest); // // Map<String, String> insertImage(String digest, byte[] decoded); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/Image.java // public class Image { // // private final String digest; // // @JsonProperty("last_modified") // private final Date lastModified; // // public Image(String digest, Date last_modified) { // this.digest = digest; // this.lastModified = last_modified; // } // // public String getDigest() { // return digest; // } // // public Date getLastModified() { // return lastModified; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Image image = (Image) o; // return Objects.equals(digest, image.digest) && // Objects.equals(lastModified, image.lastModified); // } // // @Override // public int hashCode() { // return Objects.hash(digest, lastModified); // } // } // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/ImagesController.java import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import io.crate.spring.jdbc.samples.dao.ImagesDao; import io.crate.spring.jdbc.samples.model.Image; } } @DeleteMapping("/image/{digest}") public void deleteImage(@PathVariable String digest) { logger.debug("Deleting image with digest " + digest); if (this.dao.imageExists(digest)) { this.dao.deleteImage(digest); } else { throw new ImageNotExistsException(digest); } } @PostMapping("/images") public Map<String, String> insertImage(@RequestBody Map<String, Object> imageProps, HttpServletResponse response) { logger.debug("Inserting image into database"); if (imageProps == null) { throw new ArgumentRequiredException("Request body is required"); } else if (!imageProps.containsKey("blob")) { throw new ArgumentRequiredException("Argument \"blob\" is required"); } var decodedBytes = Base64.getDecoder().decode((String) imageProps.get("blob")); var digest = DigestUtils.sha1Hex(decodedBytes); var responseMap = dao.insertImage(digest, decodedBytes); response.setStatus(Integer.parseInt(responseMap.get("status"))); return responseMap; }
private List<Map<String, Object>> convertToStdResult(final List<Image> images) {
crate/crate-sample-apps
spring-jdbc/src/test/java/io/crate/spring/jdbc/samples/da/BlogPostDaoTest.java
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/BlogPostDao.java // public interface BlogPostDao { // // List<BlogPost> getPosts(); // // Optional<BlogPost> getPost(String id); // // Optional<BlogPost> insertPost(BlogPost newPost); // // Optional<BlogPost> updatePostText(String id, String newText); // // Optional<BlogPost> incrementLikeCount(String id); // // boolean deletePost(String id); // // List<BlogPost> searchPostsWithQuery(String query); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/BlogPost.java // public class BlogPost { // // private String id; // // private User user; // // private String text; // // private Date created; // // @JsonProperty("image_ref") // private String imageRef; // // @JsonProperty("like_count") // private long likeCount; // // private String country; // // private Area area; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getImageRef() { // return imageRef; // } // // public void setImageRef(String imageRef) { // this.imageRef = imageRef; // } // // public long getLikeCount() { // return likeCount; // } // // public void setLikeCount(long likeCount) { // this.likeCount = likeCount; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public Area getArea() { // return area; // } // // public void setArea(Area area) { // this.area = area; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // BlogPost blogPost = (BlogPost) o; // return likeCount == blogPost.likeCount && // Objects.equals(id, blogPost.id) && // Objects.equals(user, blogPost.user) && // Objects.equals(text, blogPost.text) && // Objects.equals(created, blogPost.created) && // Objects.equals(imageRef, blogPost.imageRef) && // Objects.equals(country, blogPost.country) && // Objects.equals(area, blogPost.area); // } // // @Override // public int hashCode() { // return Objects.hash(id, user, text, created, imageRef, likeCount, country, area); // } // // @Override // public String toString() { // return "BlogPost{" + // "id='" + id + '\'' + // ", user=" + user + // ", text='" + text + '\'' + // ", created=" + created + // ", imageRef='" + imageRef + '\'' + // ", likeCount=" + likeCount + // ", country='" + country + '\'' + // ", area=" + area + // '}'; // } // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/User.java // public class User { // // private final String name; // private final double lon; // private final double lat; // // public User(String name, double lat, double lon) { // this.name = name; // this.lat = lat; // this.lon = lon; // } // // public String getName() { // return name; // } // // public double getLon() { // return lon; // } // // public double getLat() { // return lat; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // User user = (User) o; // return Double.compare(user.lon, lon) == 0 && // Double.compare(user.lat, lat) == 0 && // Objects.equals(name, user.name); // } // // @Override // public int hashCode() { // return Objects.hash(name, lon, lat); // } // // @Override // public String toString() { // return "User{" + // "name='" + name + '\'' + // ", lon=" + lon + // ", lat=" + lat + // '}'; // } // }
import java.util.Date; import java.util.UUID; import io.crate.spring.jdbc.samples.dao.BlogPostDao; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import io.crate.spring.jdbc.samples.model.BlogPost; import io.crate.spring.jdbc.samples.model.User; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertNotNull;
package io.crate.spring.jdbc.samples.da; @SpringBootTest public class BlogPostDaoTest { @Autowired
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/BlogPostDao.java // public interface BlogPostDao { // // List<BlogPost> getPosts(); // // Optional<BlogPost> getPost(String id); // // Optional<BlogPost> insertPost(BlogPost newPost); // // Optional<BlogPost> updatePostText(String id, String newText); // // Optional<BlogPost> incrementLikeCount(String id); // // boolean deletePost(String id); // // List<BlogPost> searchPostsWithQuery(String query); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/BlogPost.java // public class BlogPost { // // private String id; // // private User user; // // private String text; // // private Date created; // // @JsonProperty("image_ref") // private String imageRef; // // @JsonProperty("like_count") // private long likeCount; // // private String country; // // private Area area; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getImageRef() { // return imageRef; // } // // public void setImageRef(String imageRef) { // this.imageRef = imageRef; // } // // public long getLikeCount() { // return likeCount; // } // // public void setLikeCount(long likeCount) { // this.likeCount = likeCount; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public Area getArea() { // return area; // } // // public void setArea(Area area) { // this.area = area; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // BlogPost blogPost = (BlogPost) o; // return likeCount == blogPost.likeCount && // Objects.equals(id, blogPost.id) && // Objects.equals(user, blogPost.user) && // Objects.equals(text, blogPost.text) && // Objects.equals(created, blogPost.created) && // Objects.equals(imageRef, blogPost.imageRef) && // Objects.equals(country, blogPost.country) && // Objects.equals(area, blogPost.area); // } // // @Override // public int hashCode() { // return Objects.hash(id, user, text, created, imageRef, likeCount, country, area); // } // // @Override // public String toString() { // return "BlogPost{" + // "id='" + id + '\'' + // ", user=" + user + // ", text='" + text + '\'' + // ", created=" + created + // ", imageRef='" + imageRef + '\'' + // ", likeCount=" + likeCount + // ", country='" + country + '\'' + // ", area=" + area + // '}'; // } // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/User.java // public class User { // // private final String name; // private final double lon; // private final double lat; // // public User(String name, double lat, double lon) { // this.name = name; // this.lat = lat; // this.lon = lon; // } // // public String getName() { // return name; // } // // public double getLon() { // return lon; // } // // public double getLat() { // return lat; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // User user = (User) o; // return Double.compare(user.lon, lon) == 0 && // Double.compare(user.lat, lat) == 0 && // Objects.equals(name, user.name); // } // // @Override // public int hashCode() { // return Objects.hash(name, lon, lat); // } // // @Override // public String toString() { // return "User{" + // "name='" + name + '\'' + // ", lon=" + lon + // ", lat=" + lat + // '}'; // } // } // Path: spring-jdbc/src/test/java/io/crate/spring/jdbc/samples/da/BlogPostDaoTest.java import java.util.Date; import java.util.UUID; import io.crate.spring.jdbc.samples.dao.BlogPostDao; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import io.crate.spring.jdbc.samples.model.BlogPost; import io.crate.spring.jdbc.samples.model.User; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertNotNull; package io.crate.spring.jdbc.samples.da; @SpringBootTest public class BlogPostDaoTest { @Autowired
private BlogPostDao dao;
crate/crate-sample-apps
spring-jdbc/src/test/java/io/crate/spring/jdbc/samples/da/BlogPostDaoTest.java
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/BlogPostDao.java // public interface BlogPostDao { // // List<BlogPost> getPosts(); // // Optional<BlogPost> getPost(String id); // // Optional<BlogPost> insertPost(BlogPost newPost); // // Optional<BlogPost> updatePostText(String id, String newText); // // Optional<BlogPost> incrementLikeCount(String id); // // boolean deletePost(String id); // // List<BlogPost> searchPostsWithQuery(String query); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/BlogPost.java // public class BlogPost { // // private String id; // // private User user; // // private String text; // // private Date created; // // @JsonProperty("image_ref") // private String imageRef; // // @JsonProperty("like_count") // private long likeCount; // // private String country; // // private Area area; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getImageRef() { // return imageRef; // } // // public void setImageRef(String imageRef) { // this.imageRef = imageRef; // } // // public long getLikeCount() { // return likeCount; // } // // public void setLikeCount(long likeCount) { // this.likeCount = likeCount; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public Area getArea() { // return area; // } // // public void setArea(Area area) { // this.area = area; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // BlogPost blogPost = (BlogPost) o; // return likeCount == blogPost.likeCount && // Objects.equals(id, blogPost.id) && // Objects.equals(user, blogPost.user) && // Objects.equals(text, blogPost.text) && // Objects.equals(created, blogPost.created) && // Objects.equals(imageRef, blogPost.imageRef) && // Objects.equals(country, blogPost.country) && // Objects.equals(area, blogPost.area); // } // // @Override // public int hashCode() { // return Objects.hash(id, user, text, created, imageRef, likeCount, country, area); // } // // @Override // public String toString() { // return "BlogPost{" + // "id='" + id + '\'' + // ", user=" + user + // ", text='" + text + '\'' + // ", created=" + created + // ", imageRef='" + imageRef + '\'' + // ", likeCount=" + likeCount + // ", country='" + country + '\'' + // ", area=" + area + // '}'; // } // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/User.java // public class User { // // private final String name; // private final double lon; // private final double lat; // // public User(String name, double lat, double lon) { // this.name = name; // this.lat = lat; // this.lon = lon; // } // // public String getName() { // return name; // } // // public double getLon() { // return lon; // } // // public double getLat() { // return lat; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // User user = (User) o; // return Double.compare(user.lon, lon) == 0 && // Double.compare(user.lat, lat) == 0 && // Objects.equals(name, user.name); // } // // @Override // public int hashCode() { // return Objects.hash(name, lon, lat); // } // // @Override // public String toString() { // return "User{" + // "name='" + name + '\'' + // ", lon=" + lon + // ", lat=" + lat + // '}'; // } // }
import java.util.Date; import java.util.UUID; import io.crate.spring.jdbc.samples.dao.BlogPostDao; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import io.crate.spring.jdbc.samples.model.BlogPost; import io.crate.spring.jdbc.samples.model.User; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertNotNull;
package io.crate.spring.jdbc.samples.da; @SpringBootTest public class BlogPostDaoTest { @Autowired private BlogPostDao dao; @Test public void testPostCrudOperations() {
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/BlogPostDao.java // public interface BlogPostDao { // // List<BlogPost> getPosts(); // // Optional<BlogPost> getPost(String id); // // Optional<BlogPost> insertPost(BlogPost newPost); // // Optional<BlogPost> updatePostText(String id, String newText); // // Optional<BlogPost> incrementLikeCount(String id); // // boolean deletePost(String id); // // List<BlogPost> searchPostsWithQuery(String query); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/BlogPost.java // public class BlogPost { // // private String id; // // private User user; // // private String text; // // private Date created; // // @JsonProperty("image_ref") // private String imageRef; // // @JsonProperty("like_count") // private long likeCount; // // private String country; // // private Area area; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getImageRef() { // return imageRef; // } // // public void setImageRef(String imageRef) { // this.imageRef = imageRef; // } // // public long getLikeCount() { // return likeCount; // } // // public void setLikeCount(long likeCount) { // this.likeCount = likeCount; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public Area getArea() { // return area; // } // // public void setArea(Area area) { // this.area = area; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // BlogPost blogPost = (BlogPost) o; // return likeCount == blogPost.likeCount && // Objects.equals(id, blogPost.id) && // Objects.equals(user, blogPost.user) && // Objects.equals(text, blogPost.text) && // Objects.equals(created, blogPost.created) && // Objects.equals(imageRef, blogPost.imageRef) && // Objects.equals(country, blogPost.country) && // Objects.equals(area, blogPost.area); // } // // @Override // public int hashCode() { // return Objects.hash(id, user, text, created, imageRef, likeCount, country, area); // } // // @Override // public String toString() { // return "BlogPost{" + // "id='" + id + '\'' + // ", user=" + user + // ", text='" + text + '\'' + // ", created=" + created + // ", imageRef='" + imageRef + '\'' + // ", likeCount=" + likeCount + // ", country='" + country + '\'' + // ", area=" + area + // '}'; // } // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/User.java // public class User { // // private final String name; // private final double lon; // private final double lat; // // public User(String name, double lat, double lon) { // this.name = name; // this.lat = lat; // this.lon = lon; // } // // public String getName() { // return name; // } // // public double getLon() { // return lon; // } // // public double getLat() { // return lat; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // User user = (User) o; // return Double.compare(user.lon, lon) == 0 && // Double.compare(user.lat, lat) == 0 && // Objects.equals(name, user.name); // } // // @Override // public int hashCode() { // return Objects.hash(name, lon, lat); // } // // @Override // public String toString() { // return "User{" + // "name='" + name + '\'' + // ", lon=" + lon + // ", lat=" + lat + // '}'; // } // } // Path: spring-jdbc/src/test/java/io/crate/spring/jdbc/samples/da/BlogPostDaoTest.java import java.util.Date; import java.util.UUID; import io.crate.spring.jdbc.samples.dao.BlogPostDao; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import io.crate.spring.jdbc.samples.model.BlogPost; import io.crate.spring.jdbc.samples.model.User; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertNotNull; package io.crate.spring.jdbc.samples.da; @SpringBootTest public class BlogPostDaoTest { @Autowired private BlogPostDao dao; @Test public void testPostCrudOperations() {
BlogPost newPost = new BlogPost();
crate/crate-sample-apps
spring-jdbc/src/test/java/io/crate/spring/jdbc/samples/da/BlogPostDaoTest.java
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/BlogPostDao.java // public interface BlogPostDao { // // List<BlogPost> getPosts(); // // Optional<BlogPost> getPost(String id); // // Optional<BlogPost> insertPost(BlogPost newPost); // // Optional<BlogPost> updatePostText(String id, String newText); // // Optional<BlogPost> incrementLikeCount(String id); // // boolean deletePost(String id); // // List<BlogPost> searchPostsWithQuery(String query); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/BlogPost.java // public class BlogPost { // // private String id; // // private User user; // // private String text; // // private Date created; // // @JsonProperty("image_ref") // private String imageRef; // // @JsonProperty("like_count") // private long likeCount; // // private String country; // // private Area area; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getImageRef() { // return imageRef; // } // // public void setImageRef(String imageRef) { // this.imageRef = imageRef; // } // // public long getLikeCount() { // return likeCount; // } // // public void setLikeCount(long likeCount) { // this.likeCount = likeCount; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public Area getArea() { // return area; // } // // public void setArea(Area area) { // this.area = area; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // BlogPost blogPost = (BlogPost) o; // return likeCount == blogPost.likeCount && // Objects.equals(id, blogPost.id) && // Objects.equals(user, blogPost.user) && // Objects.equals(text, blogPost.text) && // Objects.equals(created, blogPost.created) && // Objects.equals(imageRef, blogPost.imageRef) && // Objects.equals(country, blogPost.country) && // Objects.equals(area, blogPost.area); // } // // @Override // public int hashCode() { // return Objects.hash(id, user, text, created, imageRef, likeCount, country, area); // } // // @Override // public String toString() { // return "BlogPost{" + // "id='" + id + '\'' + // ", user=" + user + // ", text='" + text + '\'' + // ", created=" + created + // ", imageRef='" + imageRef + '\'' + // ", likeCount=" + likeCount + // ", country='" + country + '\'' + // ", area=" + area + // '}'; // } // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/User.java // public class User { // // private final String name; // private final double lon; // private final double lat; // // public User(String name, double lat, double lon) { // this.name = name; // this.lat = lat; // this.lon = lon; // } // // public String getName() { // return name; // } // // public double getLon() { // return lon; // } // // public double getLat() { // return lat; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // User user = (User) o; // return Double.compare(user.lon, lon) == 0 && // Double.compare(user.lat, lat) == 0 && // Objects.equals(name, user.name); // } // // @Override // public int hashCode() { // return Objects.hash(name, lon, lat); // } // // @Override // public String toString() { // return "User{" + // "name='" + name + '\'' + // ", lon=" + lon + // ", lat=" + lat + // '}'; // } // }
import java.util.Date; import java.util.UUID; import io.crate.spring.jdbc.samples.dao.BlogPostDao; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import io.crate.spring.jdbc.samples.model.BlogPost; import io.crate.spring.jdbc.samples.model.User; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertNotNull;
package io.crate.spring.jdbc.samples.da; @SpringBootTest public class BlogPostDaoTest { @Autowired private BlogPostDao dao; @Test public void testPostCrudOperations() { BlogPost newPost = new BlogPost(); String id = UUID.randomUUID().toString(); newPost.setId(id); newPost.setText("The force will be with you");
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/BlogPostDao.java // public interface BlogPostDao { // // List<BlogPost> getPosts(); // // Optional<BlogPost> getPost(String id); // // Optional<BlogPost> insertPost(BlogPost newPost); // // Optional<BlogPost> updatePostText(String id, String newText); // // Optional<BlogPost> incrementLikeCount(String id); // // boolean deletePost(String id); // // List<BlogPost> searchPostsWithQuery(String query); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/BlogPost.java // public class BlogPost { // // private String id; // // private User user; // // private String text; // // private Date created; // // @JsonProperty("image_ref") // private String imageRef; // // @JsonProperty("like_count") // private long likeCount; // // private String country; // // private Area area; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getImageRef() { // return imageRef; // } // // public void setImageRef(String imageRef) { // this.imageRef = imageRef; // } // // public long getLikeCount() { // return likeCount; // } // // public void setLikeCount(long likeCount) { // this.likeCount = likeCount; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public Area getArea() { // return area; // } // // public void setArea(Area area) { // this.area = area; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // BlogPost blogPost = (BlogPost) o; // return likeCount == blogPost.likeCount && // Objects.equals(id, blogPost.id) && // Objects.equals(user, blogPost.user) && // Objects.equals(text, blogPost.text) && // Objects.equals(created, blogPost.created) && // Objects.equals(imageRef, blogPost.imageRef) && // Objects.equals(country, blogPost.country) && // Objects.equals(area, blogPost.area); // } // // @Override // public int hashCode() { // return Objects.hash(id, user, text, created, imageRef, likeCount, country, area); // } // // @Override // public String toString() { // return "BlogPost{" + // "id='" + id + '\'' + // ", user=" + user + // ", text='" + text + '\'' + // ", created=" + created + // ", imageRef='" + imageRef + '\'' + // ", likeCount=" + likeCount + // ", country='" + country + '\'' + // ", area=" + area + // '}'; // } // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/User.java // public class User { // // private final String name; // private final double lon; // private final double lat; // // public User(String name, double lat, double lon) { // this.name = name; // this.lat = lat; // this.lon = lon; // } // // public String getName() { // return name; // } // // public double getLon() { // return lon; // } // // public double getLat() { // return lat; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // User user = (User) o; // return Double.compare(user.lon, lon) == 0 && // Double.compare(user.lat, lat) == 0 && // Objects.equals(name, user.name); // } // // @Override // public int hashCode() { // return Objects.hash(name, lon, lat); // } // // @Override // public String toString() { // return "User{" + // "name='" + name + '\'' + // ", lon=" + lon + // ", lat=" + lat + // '}'; // } // } // Path: spring-jdbc/src/test/java/io/crate/spring/jdbc/samples/da/BlogPostDaoTest.java import java.util.Date; import java.util.UUID; import io.crate.spring.jdbc.samples.dao.BlogPostDao; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import io.crate.spring.jdbc.samples.model.BlogPost; import io.crate.spring.jdbc.samples.model.User; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertNotNull; package io.crate.spring.jdbc.samples.da; @SpringBootTest public class BlogPostDaoTest { @Autowired private BlogPostDao dao; @Test public void testPostCrudOperations() { BlogPost newPost = new BlogPost(); String id = UUID.randomUUID().toString(); newPost.setId(id); newPost.setText("The force will be with you");
User anUser = new User("Darth Vader", 16.3552942, 48.32648349999999);
crate/crate-sample-apps
spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/BlogPostSerializer.java
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/BlogPost.java // public class BlogPost { // // private String id; // // private User user; // // private String text; // // private Date created; // // @JsonProperty("image_ref") // private String imageRef; // // @JsonProperty("like_count") // private long likeCount; // // private String country; // // private Area area; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getImageRef() { // return imageRef; // } // // public void setImageRef(String imageRef) { // this.imageRef = imageRef; // } // // public long getLikeCount() { // return likeCount; // } // // public void setLikeCount(long likeCount) { // this.likeCount = likeCount; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public Area getArea() { // return area; // } // // public void setArea(Area area) { // this.area = area; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // BlogPost blogPost = (BlogPost) o; // return likeCount == blogPost.likeCount && // Objects.equals(id, blogPost.id) && // Objects.equals(user, blogPost.user) && // Objects.equals(text, blogPost.text) && // Objects.equals(created, blogPost.created) && // Objects.equals(imageRef, blogPost.imageRef) && // Objects.equals(country, blogPost.country) && // Objects.equals(area, blogPost.area); // } // // @Override // public int hashCode() { // return Objects.hash(id, user, text, created, imageRef, likeCount, country, area); // } // // @Override // public String toString() { // return "BlogPost{" + // "id='" + id + '\'' + // ", user=" + user + // ", text='" + text + '\'' + // ", created=" + created + // ", imageRef='" + imageRef + '\'' + // ", likeCount=" + likeCount + // ", country='" + country + '\'' + // ", area=" + area + // '}'; // } // }
import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.springframework.lang.NonNull; import io.crate.spring.jdbc.samples.model.BlogPost;
package io.crate.spring.jdbc.samples; public class BlogPostSerializer { private final static SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("MMM d, yyyy hh:mm:ss a", Locale.US);
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/BlogPost.java // public class BlogPost { // // private String id; // // private User user; // // private String text; // // private Date created; // // @JsonProperty("image_ref") // private String imageRef; // // @JsonProperty("like_count") // private long likeCount; // // private String country; // // private Area area; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getImageRef() { // return imageRef; // } // // public void setImageRef(String imageRef) { // this.imageRef = imageRef; // } // // public long getLikeCount() { // return likeCount; // } // // public void setLikeCount(long likeCount) { // this.likeCount = likeCount; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public Area getArea() { // return area; // } // // public void setArea(Area area) { // this.area = area; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // BlogPost blogPost = (BlogPost) o; // return likeCount == blogPost.likeCount && // Objects.equals(id, blogPost.id) && // Objects.equals(user, blogPost.user) && // Objects.equals(text, blogPost.text) && // Objects.equals(created, blogPost.created) && // Objects.equals(imageRef, blogPost.imageRef) && // Objects.equals(country, blogPost.country) && // Objects.equals(area, blogPost.area); // } // // @Override // public int hashCode() { // return Objects.hash(id, user, text, created, imageRef, likeCount, country, area); // } // // @Override // public String toString() { // return "BlogPost{" + // "id='" + id + '\'' + // ", user=" + user + // ", text='" + text + '\'' + // ", created=" + created + // ", imageRef='" + imageRef + '\'' + // ", likeCount=" + likeCount + // ", country='" + country + '\'' + // ", area=" + area + // '}'; // } // } // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/BlogPostSerializer.java import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.springframework.lang.NonNull; import io.crate.spring.jdbc.samples.model.BlogPost; package io.crate.spring.jdbc.samples; public class BlogPostSerializer { private final static SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("MMM d, yyyy hh:mm:ss a", Locale.US);
public Map<String, Object> serialize(@NonNull final BlogPost post) {
crate/crate-sample-apps
spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/PostgresJDBCDBObjectsFactory.java
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/BlogPost.java // public class BlogPost { // // private String id; // // private User user; // // private String text; // // private Date created; // // @JsonProperty("image_ref") // private String imageRef; // // @JsonProperty("like_count") // private long likeCount; // // private String country; // // private Area area; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getImageRef() { // return imageRef; // } // // public void setImageRef(String imageRef) { // this.imageRef = imageRef; // } // // public long getLikeCount() { // return likeCount; // } // // public void setLikeCount(long likeCount) { // this.likeCount = likeCount; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public Area getArea() { // return area; // } // // public void setArea(Area area) { // this.area = area; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // BlogPost blogPost = (BlogPost) o; // return likeCount == blogPost.likeCount && // Objects.equals(id, blogPost.id) && // Objects.equals(user, blogPost.user) && // Objects.equals(text, blogPost.text) && // Objects.equals(created, blogPost.created) && // Objects.equals(imageRef, blogPost.imageRef) && // Objects.equals(country, blogPost.country) && // Objects.equals(area, blogPost.area); // } // // @Override // public int hashCode() { // return Objects.hash(id, user, text, created, imageRef, likeCount, country, area); // } // // @Override // public String toString() { // return "BlogPost{" + // "id='" + id + '\'' + // ", user=" + user + // ", text='" + text + '\'' + // ", created=" + created + // ", imageRef='" + imageRef + '\'' + // ", likeCount=" + likeCount + // ", country='" + country + '\'' + // ", area=" + area + // '}'; // } // }
import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.dao.DataIntegrityViolationException; import io.crate.shade.org.postgresql.util.PGobject; import io.crate.spring.jdbc.samples.model.BlogPost;
package io.crate.spring.jdbc.samples.dao; public class PostgresJDBCDBObjectsFactory implements JDBCDBObjectsFactory { private ObjectMapper mapper = new ObjectMapper(); @Override
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/BlogPost.java // public class BlogPost { // // private String id; // // private User user; // // private String text; // // private Date created; // // @JsonProperty("image_ref") // private String imageRef; // // @JsonProperty("like_count") // private long likeCount; // // private String country; // // private Area area; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getImageRef() { // return imageRef; // } // // public void setImageRef(String imageRef) { // this.imageRef = imageRef; // } // // public long getLikeCount() { // return likeCount; // } // // public void setLikeCount(long likeCount) { // this.likeCount = likeCount; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public Area getArea() { // return area; // } // // public void setArea(Area area) { // this.area = area; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // BlogPost blogPost = (BlogPost) o; // return likeCount == blogPost.likeCount && // Objects.equals(id, blogPost.id) && // Objects.equals(user, blogPost.user) && // Objects.equals(text, blogPost.text) && // Objects.equals(created, blogPost.created) && // Objects.equals(imageRef, blogPost.imageRef) && // Objects.equals(country, blogPost.country) && // Objects.equals(area, blogPost.area); // } // // @Override // public int hashCode() { // return Objects.hash(id, user, text, created, imageRef, likeCount, country, area); // } // // @Override // public String toString() { // return "BlogPost{" + // "id='" + id + '\'' + // ", user=" + user + // ", text='" + text + '\'' + // ", created=" + created + // ", imageRef='" + imageRef + '\'' + // ", likeCount=" + likeCount + // ", country='" + country + '\'' + // ", area=" + area + // '}'; // } // } // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/PostgresJDBCDBObjectsFactory.java import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.dao.DataIntegrityViolationException; import io.crate.shade.org.postgresql.util.PGobject; import io.crate.spring.jdbc.samples.model.BlogPost; package io.crate.spring.jdbc.samples.dao; public class PostgresJDBCDBObjectsFactory implements JDBCDBObjectsFactory { private ObjectMapper mapper = new ObjectMapper(); @Override
public Object createUserObject(BlogPost post) {
crate/crate-sample-apps
spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/ImagesJDBCTemplateDao.java
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/Image.java // public class Image { // // private final String digest; // // @JsonProperty("last_modified") // private final Date lastModified; // // public Image(String digest, Date last_modified) { // this.digest = digest; // this.lastModified = last_modified; // } // // public String getDigest() { // return digest; // } // // public Date getLastModified() { // return lastModified; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Image image = (Image) o; // return Objects.equals(digest, image.digest) && // Objects.equals(lastModified, image.lastModified); // } // // @Override // public int hashCode() { // return Objects.hash(digest, lastModified); // } // }
import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.http.HttpRequest.BodyPublishers; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpStatus; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.lang.NonNull; import org.springframework.stereotype.Component; import io.crate.spring.jdbc.samples.model.Image;
package io.crate.spring.jdbc.samples.dao; @Component public class ImagesJDBCTemplateDao implements ImagesDao { @Value("${cratesample.cratedb.blobEndpointURL:http://localhost:4200/_blobs/}") private String blobEndpointURL; @Autowired private JdbcTemplate jdbcTemplate; private HttpClient client = HttpClient.newHttpClient(); @Override public boolean imageExists(@NonNull final String digest) { var request = HttpRequest .newBuilder(this.createBlobUri(digest)) .method("HEAD", HttpRequest.BodyPublishers.noBody()) .build(); try { var response = client.send(request, HttpResponse.BodyHandlers.discarding()); return response.statusCode() == HttpStatus.OK.value(); } catch (IOException | InterruptedException e) { throw new DataIntegrityViolationException("Failed to call blob endpoint", e); } } @Override
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/Image.java // public class Image { // // private final String digest; // // @JsonProperty("last_modified") // private final Date lastModified; // // public Image(String digest, Date last_modified) { // this.digest = digest; // this.lastModified = last_modified; // } // // public String getDigest() { // return digest; // } // // public Date getLastModified() { // return lastModified; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Image image = (Image) o; // return Objects.equals(digest, image.digest) && // Objects.equals(lastModified, image.lastModified); // } // // @Override // public int hashCode() { // return Objects.hash(digest, lastModified); // } // } // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/ImagesJDBCTemplateDao.java import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.http.HttpRequest.BodyPublishers; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpStatus; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.lang.NonNull; import org.springframework.stereotype.Component; import io.crate.spring.jdbc.samples.model.Image; package io.crate.spring.jdbc.samples.dao; @Component public class ImagesJDBCTemplateDao implements ImagesDao { @Value("${cratesample.cratedb.blobEndpointURL:http://localhost:4200/_blobs/}") private String blobEndpointURL; @Autowired private JdbcTemplate jdbcTemplate; private HttpClient client = HttpClient.newHttpClient(); @Override public boolean imageExists(@NonNull final String digest) { var request = HttpRequest .newBuilder(this.createBlobUri(digest)) .method("HEAD", HttpRequest.BodyPublishers.noBody()) .build(); try { var response = client.send(request, HttpResponse.BodyHandlers.discarding()); return response.statusCode() == HttpStatus.OK.value(); } catch (IOException | InterruptedException e) { throw new DataIntegrityViolationException("Failed to call blob endpoint", e); } } @Override
public List<Image> getImages() {
crate/crate-sample-apps
spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/BackEndApplication.java
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/JDBCDBObjectsFactory.java // public interface JDBCDBObjectsFactory { // // Object createUserObject(final BlogPost post); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/PostgresJDBCDBObjectsFactory.java // public class PostgresJDBCDBObjectsFactory implements JDBCDBObjectsFactory { // // private ObjectMapper mapper = new ObjectMapper(); // // @Override // public Object createUserObject(BlogPost post) { // if (post != null && post.getUser() != null) { // // objects can be streamed as json strings, // // https://crate.io/docs/reference/en/latest/protocols/postgres.html#jdbc // var userObject = new PGobject(); // userObject.setType("json"); // var userValue = new HashMap<String, Object>(); // userValue.put("name", post.getUser().getName()); // var locValues = new ArrayList<Double>(); // locValues.add(post.getUser().getLat()); // locValues.add(post.getUser().getLon()); // userValue.put("location", locValues); // try { // userObject.setValue(mapper.writeValueAsString(userValue)); // } catch (JsonProcessingException | SQLException e) { // throw new DataIntegrityViolationException("Can not create Postgres object for user", e); // } // return userObject; // } else // return null; // } // }
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import io.crate.spring.jdbc.samples.dao.JDBCDBObjectsFactory; import io.crate.spring.jdbc.samples.dao.PostgresJDBCDBObjectsFactory;
package io.crate.spring.jdbc.samples; @SpringBootApplication public class BackEndApplication { public static void main(String[] args) { SpringApplication.run(BackEndApplication.class, args); } @Bean public BlogPostSerializer createPostsSerializer() { return new BlogPostSerializer(); } @Bean public BlogPostDeserializer createPostsDeserializer() { return new BlogPostDeserializer(); } @Bean
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/JDBCDBObjectsFactory.java // public interface JDBCDBObjectsFactory { // // Object createUserObject(final BlogPost post); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/PostgresJDBCDBObjectsFactory.java // public class PostgresJDBCDBObjectsFactory implements JDBCDBObjectsFactory { // // private ObjectMapper mapper = new ObjectMapper(); // // @Override // public Object createUserObject(BlogPost post) { // if (post != null && post.getUser() != null) { // // objects can be streamed as json strings, // // https://crate.io/docs/reference/en/latest/protocols/postgres.html#jdbc // var userObject = new PGobject(); // userObject.setType("json"); // var userValue = new HashMap<String, Object>(); // userValue.put("name", post.getUser().getName()); // var locValues = new ArrayList<Double>(); // locValues.add(post.getUser().getLat()); // locValues.add(post.getUser().getLon()); // userValue.put("location", locValues); // try { // userObject.setValue(mapper.writeValueAsString(userValue)); // } catch (JsonProcessingException | SQLException e) { // throw new DataIntegrityViolationException("Can not create Postgres object for user", e); // } // return userObject; // } else // return null; // } // } // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/BackEndApplication.java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import io.crate.spring.jdbc.samples.dao.JDBCDBObjectsFactory; import io.crate.spring.jdbc.samples.dao.PostgresJDBCDBObjectsFactory; package io.crate.spring.jdbc.samples; @SpringBootApplication public class BackEndApplication { public static void main(String[] args) { SpringApplication.run(BackEndApplication.class, args); } @Bean public BlogPostSerializer createPostsSerializer() { return new BlogPostSerializer(); } @Bean public BlogPostDeserializer createPostsDeserializer() { return new BlogPostDeserializer(); } @Bean
public JDBCDBObjectsFactory createObjectsFactory() {
crate/crate-sample-apps
spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/BackEndApplication.java
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/JDBCDBObjectsFactory.java // public interface JDBCDBObjectsFactory { // // Object createUserObject(final BlogPost post); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/PostgresJDBCDBObjectsFactory.java // public class PostgresJDBCDBObjectsFactory implements JDBCDBObjectsFactory { // // private ObjectMapper mapper = new ObjectMapper(); // // @Override // public Object createUserObject(BlogPost post) { // if (post != null && post.getUser() != null) { // // objects can be streamed as json strings, // // https://crate.io/docs/reference/en/latest/protocols/postgres.html#jdbc // var userObject = new PGobject(); // userObject.setType("json"); // var userValue = new HashMap<String, Object>(); // userValue.put("name", post.getUser().getName()); // var locValues = new ArrayList<Double>(); // locValues.add(post.getUser().getLat()); // locValues.add(post.getUser().getLon()); // userValue.put("location", locValues); // try { // userObject.setValue(mapper.writeValueAsString(userValue)); // } catch (JsonProcessingException | SQLException e) { // throw new DataIntegrityViolationException("Can not create Postgres object for user", e); // } // return userObject; // } else // return null; // } // }
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import io.crate.spring.jdbc.samples.dao.JDBCDBObjectsFactory; import io.crate.spring.jdbc.samples.dao.PostgresJDBCDBObjectsFactory;
package io.crate.spring.jdbc.samples; @SpringBootApplication public class BackEndApplication { public static void main(String[] args) { SpringApplication.run(BackEndApplication.class, args); } @Bean public BlogPostSerializer createPostsSerializer() { return new BlogPostSerializer(); } @Bean public BlogPostDeserializer createPostsDeserializer() { return new BlogPostDeserializer(); } @Bean public JDBCDBObjectsFactory createObjectsFactory() {
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/JDBCDBObjectsFactory.java // public interface JDBCDBObjectsFactory { // // Object createUserObject(final BlogPost post); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/PostgresJDBCDBObjectsFactory.java // public class PostgresJDBCDBObjectsFactory implements JDBCDBObjectsFactory { // // private ObjectMapper mapper = new ObjectMapper(); // // @Override // public Object createUserObject(BlogPost post) { // if (post != null && post.getUser() != null) { // // objects can be streamed as json strings, // // https://crate.io/docs/reference/en/latest/protocols/postgres.html#jdbc // var userObject = new PGobject(); // userObject.setType("json"); // var userValue = new HashMap<String, Object>(); // userValue.put("name", post.getUser().getName()); // var locValues = new ArrayList<Double>(); // locValues.add(post.getUser().getLat()); // locValues.add(post.getUser().getLon()); // userValue.put("location", locValues); // try { // userObject.setValue(mapper.writeValueAsString(userValue)); // } catch (JsonProcessingException | SQLException e) { // throw new DataIntegrityViolationException("Can not create Postgres object for user", e); // } // return userObject; // } else // return null; // } // } // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/BackEndApplication.java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import io.crate.spring.jdbc.samples.dao.JDBCDBObjectsFactory; import io.crate.spring.jdbc.samples.dao.PostgresJDBCDBObjectsFactory; package io.crate.spring.jdbc.samples; @SpringBootApplication public class BackEndApplication { public static void main(String[] args) { SpringApplication.run(BackEndApplication.class, args); } @Bean public BlogPostSerializer createPostsSerializer() { return new BlogPostSerializer(); } @Bean public BlogPostDeserializer createPostsDeserializer() { return new BlogPostDeserializer(); } @Bean public JDBCDBObjectsFactory createObjectsFactory() {
return new PostgresJDBCDBObjectsFactory();
crate/crate-sample-apps
spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/BlogPostDeserializer.java
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/BlogPost.java // public class BlogPost { // // private String id; // // private User user; // // private String text; // // private Date created; // // @JsonProperty("image_ref") // private String imageRef; // // @JsonProperty("like_count") // private long likeCount; // // private String country; // // private Area area; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getImageRef() { // return imageRef; // } // // public void setImageRef(String imageRef) { // this.imageRef = imageRef; // } // // public long getLikeCount() { // return likeCount; // } // // public void setLikeCount(long likeCount) { // this.likeCount = likeCount; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public Area getArea() { // return area; // } // // public void setArea(Area area) { // this.area = area; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // BlogPost blogPost = (BlogPost) o; // return likeCount == blogPost.likeCount && // Objects.equals(id, blogPost.id) && // Objects.equals(user, blogPost.user) && // Objects.equals(text, blogPost.text) && // Objects.equals(created, blogPost.created) && // Objects.equals(imageRef, blogPost.imageRef) && // Objects.equals(country, blogPost.country) && // Objects.equals(area, blogPost.area); // } // // @Override // public int hashCode() { // return Objects.hash(id, user, text, created, imageRef, likeCount, country, area); // } // // @Override // public String toString() { // return "BlogPost{" + // "id='" + id + '\'' + // ", user=" + user + // ", text='" + text + '\'' + // ", created=" + created + // ", imageRef='" + imageRef + '\'' + // ", likeCount=" + likeCount + // ", country='" + country + '\'' + // ", area=" + area + // '}'; // } // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/User.java // public class User { // // private final String name; // private final double lon; // private final double lat; // // public User(String name, double lat, double lon) { // this.name = name; // this.lat = lat; // this.lon = lon; // } // // public String getName() { // return name; // } // // public double getLon() { // return lon; // } // // public double getLat() { // return lat; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // User user = (User) o; // return Double.compare(user.lon, lon) == 0 && // Double.compare(user.lat, lat) == 0 && // Objects.equals(name, user.name); // } // // @Override // public int hashCode() { // return Objects.hash(name, lon, lat); // } // // @Override // public String toString() { // return "User{" + // "name='" + name + '\'' + // ", lon=" + lon + // ", lat=" + lat + // '}'; // } // }
import java.util.Date; import java.util.List; import java.util.Map; import org.springframework.lang.NonNull; import io.crate.spring.jdbc.samples.model.BlogPost; import io.crate.spring.jdbc.samples.model.User;
package io.crate.spring.jdbc.samples; public class BlogPostDeserializer { @SuppressWarnings("unchecked")
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/BlogPost.java // public class BlogPost { // // private String id; // // private User user; // // private String text; // // private Date created; // // @JsonProperty("image_ref") // private String imageRef; // // @JsonProperty("like_count") // private long likeCount; // // private String country; // // private Area area; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getImageRef() { // return imageRef; // } // // public void setImageRef(String imageRef) { // this.imageRef = imageRef; // } // // public long getLikeCount() { // return likeCount; // } // // public void setLikeCount(long likeCount) { // this.likeCount = likeCount; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public Area getArea() { // return area; // } // // public void setArea(Area area) { // this.area = area; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // BlogPost blogPost = (BlogPost) o; // return likeCount == blogPost.likeCount && // Objects.equals(id, blogPost.id) && // Objects.equals(user, blogPost.user) && // Objects.equals(text, blogPost.text) && // Objects.equals(created, blogPost.created) && // Objects.equals(imageRef, blogPost.imageRef) && // Objects.equals(country, blogPost.country) && // Objects.equals(area, blogPost.area); // } // // @Override // public int hashCode() { // return Objects.hash(id, user, text, created, imageRef, likeCount, country, area); // } // // @Override // public String toString() { // return "BlogPost{" + // "id='" + id + '\'' + // ", user=" + user + // ", text='" + text + '\'' + // ", created=" + created + // ", imageRef='" + imageRef + '\'' + // ", likeCount=" + likeCount + // ", country='" + country + '\'' + // ", area=" + area + // '}'; // } // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/User.java // public class User { // // private final String name; // private final double lon; // private final double lat; // // public User(String name, double lat, double lon) { // this.name = name; // this.lat = lat; // this.lon = lon; // } // // public String getName() { // return name; // } // // public double getLon() { // return lon; // } // // public double getLat() { // return lat; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // User user = (User) o; // return Double.compare(user.lon, lon) == 0 && // Double.compare(user.lat, lat) == 0 && // Objects.equals(name, user.name); // } // // @Override // public int hashCode() { // return Objects.hash(name, lon, lat); // } // // @Override // public String toString() { // return "User{" + // "name='" + name + '\'' + // ", lon=" + lon + // ", lat=" + lat + // '}'; // } // } // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/BlogPostDeserializer.java import java.util.Date; import java.util.List; import java.util.Map; import org.springframework.lang.NonNull; import io.crate.spring.jdbc.samples.model.BlogPost; import io.crate.spring.jdbc.samples.model.User; package io.crate.spring.jdbc.samples; public class BlogPostDeserializer { @SuppressWarnings("unchecked")
public BlogPost fromMap(@NonNull final Map<String, Object> postProps) {
crate/crate-sample-apps
spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/BlogPostDeserializer.java
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/BlogPost.java // public class BlogPost { // // private String id; // // private User user; // // private String text; // // private Date created; // // @JsonProperty("image_ref") // private String imageRef; // // @JsonProperty("like_count") // private long likeCount; // // private String country; // // private Area area; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getImageRef() { // return imageRef; // } // // public void setImageRef(String imageRef) { // this.imageRef = imageRef; // } // // public long getLikeCount() { // return likeCount; // } // // public void setLikeCount(long likeCount) { // this.likeCount = likeCount; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public Area getArea() { // return area; // } // // public void setArea(Area area) { // this.area = area; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // BlogPost blogPost = (BlogPost) o; // return likeCount == blogPost.likeCount && // Objects.equals(id, blogPost.id) && // Objects.equals(user, blogPost.user) && // Objects.equals(text, blogPost.text) && // Objects.equals(created, blogPost.created) && // Objects.equals(imageRef, blogPost.imageRef) && // Objects.equals(country, blogPost.country) && // Objects.equals(area, blogPost.area); // } // // @Override // public int hashCode() { // return Objects.hash(id, user, text, created, imageRef, likeCount, country, area); // } // // @Override // public String toString() { // return "BlogPost{" + // "id='" + id + '\'' + // ", user=" + user + // ", text='" + text + '\'' + // ", created=" + created + // ", imageRef='" + imageRef + '\'' + // ", likeCount=" + likeCount + // ", country='" + country + '\'' + // ", area=" + area + // '}'; // } // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/User.java // public class User { // // private final String name; // private final double lon; // private final double lat; // // public User(String name, double lat, double lon) { // this.name = name; // this.lat = lat; // this.lon = lon; // } // // public String getName() { // return name; // } // // public double getLon() { // return lon; // } // // public double getLat() { // return lat; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // User user = (User) o; // return Double.compare(user.lon, lon) == 0 && // Double.compare(user.lat, lat) == 0 && // Objects.equals(name, user.name); // } // // @Override // public int hashCode() { // return Objects.hash(name, lon, lat); // } // // @Override // public String toString() { // return "User{" + // "name='" + name + '\'' + // ", lon=" + lon + // ", lat=" + lat + // '}'; // } // }
import java.util.Date; import java.util.List; import java.util.Map; import org.springframework.lang.NonNull; import io.crate.spring.jdbc.samples.model.BlogPost; import io.crate.spring.jdbc.samples.model.User;
package io.crate.spring.jdbc.samples; public class BlogPostDeserializer { @SuppressWarnings("unchecked") public BlogPost fromMap(@NonNull final Map<String, Object> postProps) { var post = new BlogPost(); var id = postProps.get("id"); if (id != null) { post.setId(id.toString()); } var userData = (Map<String, Object>) postProps.get("user"); if (userData != null) { String name = (String) userData.get("name"); var location = (List<Double>) userData.get("location"); if (name != null && location != null && location.size() == 2) {
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/BlogPost.java // public class BlogPost { // // private String id; // // private User user; // // private String text; // // private Date created; // // @JsonProperty("image_ref") // private String imageRef; // // @JsonProperty("like_count") // private long likeCount; // // private String country; // // private Area area; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public Date getCreated() { // return created; // } // // public void setCreated(Date created) { // this.created = created; // } // // public String getImageRef() { // return imageRef; // } // // public void setImageRef(String imageRef) { // this.imageRef = imageRef; // } // // public long getLikeCount() { // return likeCount; // } // // public void setLikeCount(long likeCount) { // this.likeCount = likeCount; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public Area getArea() { // return area; // } // // public void setArea(Area area) { // this.area = area; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // BlogPost blogPost = (BlogPost) o; // return likeCount == blogPost.likeCount && // Objects.equals(id, blogPost.id) && // Objects.equals(user, blogPost.user) && // Objects.equals(text, blogPost.text) && // Objects.equals(created, blogPost.created) && // Objects.equals(imageRef, blogPost.imageRef) && // Objects.equals(country, blogPost.country) && // Objects.equals(area, blogPost.area); // } // // @Override // public int hashCode() { // return Objects.hash(id, user, text, created, imageRef, likeCount, country, area); // } // // @Override // public String toString() { // return "BlogPost{" + // "id='" + id + '\'' + // ", user=" + user + // ", text='" + text + '\'' + // ", created=" + created + // ", imageRef='" + imageRef + '\'' + // ", likeCount=" + likeCount + // ", country='" + country + '\'' + // ", area=" + area + // '}'; // } // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/User.java // public class User { // // private final String name; // private final double lon; // private final double lat; // // public User(String name, double lat, double lon) { // this.name = name; // this.lat = lat; // this.lon = lon; // } // // public String getName() { // return name; // } // // public double getLon() { // return lon; // } // // public double getLat() { // return lat; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // User user = (User) o; // return Double.compare(user.lon, lon) == 0 && // Double.compare(user.lat, lat) == 0 && // Objects.equals(name, user.name); // } // // @Override // public int hashCode() { // return Objects.hash(name, lon, lat); // } // // @Override // public String toString() { // return "User{" + // "name='" + name + '\'' + // ", lon=" + lon + // ", lat=" + lat + // '}'; // } // } // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/BlogPostDeserializer.java import java.util.Date; import java.util.List; import java.util.Map; import org.springframework.lang.NonNull; import io.crate.spring.jdbc.samples.model.BlogPost; import io.crate.spring.jdbc.samples.model.User; package io.crate.spring.jdbc.samples; public class BlogPostDeserializer { @SuppressWarnings("unchecked") public BlogPost fromMap(@NonNull final Map<String, Object> postProps) { var post = new BlogPost(); var id = postProps.get("id"); if (id != null) { post.setId(id.toString()); } var userData = (Map<String, Object>) postProps.get("user"); if (userData != null) { String name = (String) userData.get("name"); var location = (List<Double>) userData.get("location"); if (name != null && location != null && location.size() == 2) {
post.setUser(new User(name, location.get(0), location.get(1)));
crate/crate-sample-apps
spring-jdbc/src/test/java/io/crate/spring/jdbc/samples/da/ImagesDaoTest.java
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/ImagesDao.java // public interface ImagesDao { // // boolean imageExists(String digest); // // List<Image> getImages(); // // InputStream getImageAsInputStream(String digest); // // boolean deleteImage(String digest); // // Map<String, String> insertImage(String digest, byte[] decoded); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/Image.java // public class Image { // // private final String digest; // // @JsonProperty("last_modified") // private final Date lastModified; // // public Image(String digest, Date last_modified) { // this.digest = digest; // this.lastModified = last_modified; // } // // public String getDigest() { // return digest; // } // // public Date getLastModified() { // return lastModified; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Image image = (Image) o; // return Objects.equals(digest, image.digest) && // Objects.equals(lastModified, image.lastModified); // } // // @Override // public int hashCode() { // return Objects.hash(digest, lastModified); // } // }
import com.google.common.hash.Hashing; import io.crate.spring.jdbc.samples.dao.ImagesDao; import io.crate.spring.jdbc.samples.model.Image; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; import java.util.Random;
package io.crate.spring.jdbc.samples.da; @SpringBootTest public class ImagesDaoTest { @Autowired
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/ImagesDao.java // public interface ImagesDao { // // boolean imageExists(String digest); // // List<Image> getImages(); // // InputStream getImageAsInputStream(String digest); // // boolean deleteImage(String digest); // // Map<String, String> insertImage(String digest, byte[] decoded); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/Image.java // public class Image { // // private final String digest; // // @JsonProperty("last_modified") // private final Date lastModified; // // public Image(String digest, Date last_modified) { // this.digest = digest; // this.lastModified = last_modified; // } // // public String getDigest() { // return digest; // } // // public Date getLastModified() { // return lastModified; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Image image = (Image) o; // return Objects.equals(digest, image.digest) && // Objects.equals(lastModified, image.lastModified); // } // // @Override // public int hashCode() { // return Objects.hash(digest, lastModified); // } // } // Path: spring-jdbc/src/test/java/io/crate/spring/jdbc/samples/da/ImagesDaoTest.java import com.google.common.hash.Hashing; import io.crate.spring.jdbc.samples.dao.ImagesDao; import io.crate.spring.jdbc.samples.model.Image; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; import java.util.Random; package io.crate.spring.jdbc.samples.da; @SpringBootTest public class ImagesDaoTest { @Autowired
private ImagesDao dao;
crate/crate-sample-apps
spring-jdbc/src/test/java/io/crate/spring/jdbc/samples/da/ImagesDaoTest.java
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/ImagesDao.java // public interface ImagesDao { // // boolean imageExists(String digest); // // List<Image> getImages(); // // InputStream getImageAsInputStream(String digest); // // boolean deleteImage(String digest); // // Map<String, String> insertImage(String digest, byte[] decoded); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/Image.java // public class Image { // // private final String digest; // // @JsonProperty("last_modified") // private final Date lastModified; // // public Image(String digest, Date last_modified) { // this.digest = digest; // this.lastModified = last_modified; // } // // public String getDigest() { // return digest; // } // // public Date getLastModified() { // return lastModified; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Image image = (Image) o; // return Objects.equals(digest, image.digest) && // Objects.equals(lastModified, image.lastModified); // } // // @Override // public int hashCode() { // return Objects.hash(digest, lastModified); // } // }
import com.google.common.hash.Hashing; import io.crate.spring.jdbc.samples.dao.ImagesDao; import io.crate.spring.jdbc.samples.model.Image; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; import java.util.Random;
package io.crate.spring.jdbc.samples.da; @SpringBootTest public class ImagesDaoTest { @Autowired private ImagesDao dao; @Test public void testImageCrud() throws Exception { var data = new byte[10]; new Random().nextBytes(data); var hash = Hashing.sha1().hashBytes(data).toString(); dao.insertImage(hash, data); Assertions.assertTrue(dao.imageExists(hash)); var result = dao.getImageAsInputStream(hash).readAllBytes();; Assertions.assertArrayEquals(data, result);
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/ImagesDao.java // public interface ImagesDao { // // boolean imageExists(String digest); // // List<Image> getImages(); // // InputStream getImageAsInputStream(String digest); // // boolean deleteImage(String digest); // // Map<String, String> insertImage(String digest, byte[] decoded); // } // // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/Image.java // public class Image { // // private final String digest; // // @JsonProperty("last_modified") // private final Date lastModified; // // public Image(String digest, Date last_modified) { // this.digest = digest; // this.lastModified = last_modified; // } // // public String getDigest() { // return digest; // } // // public Date getLastModified() { // return lastModified; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Image image = (Image) o; // return Objects.equals(digest, image.digest) && // Objects.equals(lastModified, image.lastModified); // } // // @Override // public int hashCode() { // return Objects.hash(digest, lastModified); // } // } // Path: spring-jdbc/src/test/java/io/crate/spring/jdbc/samples/da/ImagesDaoTest.java import com.google.common.hash.Hashing; import io.crate.spring.jdbc.samples.dao.ImagesDao; import io.crate.spring.jdbc.samples.model.Image; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; import java.util.Random; package io.crate.spring.jdbc.samples.da; @SpringBootTest public class ImagesDaoTest { @Autowired private ImagesDao dao; @Test public void testImageCrud() throws Exception { var data = new byte[10]; new Random().nextBytes(data); var hash = Hashing.sha1().hashBytes(data).toString(); dao.insertImage(hash, data); Assertions.assertTrue(dao.imageExists(hash)); var result = dao.getImageAsInputStream(hash).readAllBytes();; Assertions.assertArrayEquals(data, result);
List<Image> images = dao.getImages();
crate/crate-sample-apps
spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/ImagesDao.java
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/Image.java // public class Image { // // private final String digest; // // @JsonProperty("last_modified") // private final Date lastModified; // // public Image(String digest, Date last_modified) { // this.digest = digest; // this.lastModified = last_modified; // } // // public String getDigest() { // return digest; // } // // public Date getLastModified() { // return lastModified; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Image image = (Image) o; // return Objects.equals(digest, image.digest) && // Objects.equals(lastModified, image.lastModified); // } // // @Override // public int hashCode() { // return Objects.hash(digest, lastModified); // } // }
import java.io.InputStream; import java.util.List; import java.util.Map; import io.crate.spring.jdbc.samples.model.Image;
package io.crate.spring.jdbc.samples.dao; public interface ImagesDao { boolean imageExists(String digest);
// Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/model/Image.java // public class Image { // // private final String digest; // // @JsonProperty("last_modified") // private final Date lastModified; // // public Image(String digest, Date last_modified) { // this.digest = digest; // this.lastModified = last_modified; // } // // public String getDigest() { // return digest; // } // // public Date getLastModified() { // return lastModified; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Image image = (Image) o; // return Objects.equals(digest, image.digest) && // Objects.equals(lastModified, image.lastModified); // } // // @Override // public int hashCode() { // return Objects.hash(digest, lastModified); // } // } // Path: spring-jdbc/src/main/java/io/crate/spring/jdbc/samples/dao/ImagesDao.java import java.io.InputStream; import java.util.List; import java.util.Map; import io.crate.spring.jdbc.samples.model.Image; package io.crate.spring.jdbc.samples.dao; public interface ImagesDao { boolean imageExists(String digest);
List<Image> getImages();
spirylics/x-gwt
x-gwt-hello/src/main/java/com/github/spirylics/xgwt/hello/Hello.java
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Promise.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public class Promise<S, E> extends Thenable<S, E> { // // @JsConstructor // public Promise(Fn.Resolver<S, E> resolver) { // } // // public static native <A, B> Promise<A, B> all(Promise<?, ?>[] promises); // // public static native <S> Promise<S, Error> resolve(S success); // // private Fn.Arg<S> resolve; // private Fn.Arg<E> reject; // // @JsOverlay // public final Promise<S, E> openResolve(S success) { // if (resolve == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // resolve.e(success); // return this; // } // // @JsOverlay // public final Promise<S, E> openReject(E error) { // if (reject == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // reject.e(error); // return this; // } // // @JsOverlay // public static <S, E> Promise<S, E> buildOpenPromise() { // final Map<String, Fn.Arg<?>> containers = new HashMap<>(2); // Fn.Resolver<S, E> resolver = new Fn.Resolver<S, E>() { // @Override // public void e(Fn.Arg<S> resolve, Fn.Arg<E> reject) { // containers.put("resolve", resolve); // containers.put("reject", reject); // } // }; // Promise<S, E> openPromise = new Promise<S, E>(resolver); // openPromise.resolve = (Fn.Arg<S>) containers.get("resolve"); // openPromise.reject = (Fn.Arg<E>) containers.get("reject"); // return openPromise; // } // }
import com.github.spirylics.xgwt.essential.Promise; import com.google.gwt.core.client.JavaScriptObject; import jsinterop.annotations.JsMethod; import jsinterop.annotations.JsPackage; import jsinterop.annotations.JsType;
package com.github.spirylics.xgwt.hello; @SuppressWarnings("ALL") @JsType(isNative = true, name = "hello") public class Hello { @JsMethod(namespace = JsPackage.GLOBAL) public native static Hello hello(); @JsMethod(namespace = JsPackage.GLOBAL) public native static Hello hello(String network); public native Hello init(Credentials credentials); public native Hello init(Credentials credentials, Options options);
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Promise.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public class Promise<S, E> extends Thenable<S, E> { // // @JsConstructor // public Promise(Fn.Resolver<S, E> resolver) { // } // // public static native <A, B> Promise<A, B> all(Promise<?, ?>[] promises); // // public static native <S> Promise<S, Error> resolve(S success); // // private Fn.Arg<S> resolve; // private Fn.Arg<E> reject; // // @JsOverlay // public final Promise<S, E> openResolve(S success) { // if (resolve == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // resolve.e(success); // return this; // } // // @JsOverlay // public final Promise<S, E> openReject(E error) { // if (reject == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // reject.e(error); // return this; // } // // @JsOverlay // public static <S, E> Promise<S, E> buildOpenPromise() { // final Map<String, Fn.Arg<?>> containers = new HashMap<>(2); // Fn.Resolver<S, E> resolver = new Fn.Resolver<S, E>() { // @Override // public void e(Fn.Arg<S> resolve, Fn.Arg<E> reject) { // containers.put("resolve", resolve); // containers.put("reject", reject); // } // }; // Promise<S, E> openPromise = new Promise<S, E>(resolver); // openPromise.resolve = (Fn.Arg<S>) containers.get("resolve"); // openPromise.reject = (Fn.Arg<E>) containers.get("reject"); // return openPromise; // } // } // Path: x-gwt-hello/src/main/java/com/github/spirylics/xgwt/hello/Hello.java import com.github.spirylics.xgwt.essential.Promise; import com.google.gwt.core.client.JavaScriptObject; import jsinterop.annotations.JsMethod; import jsinterop.annotations.JsPackage; import jsinterop.annotations.JsType; package com.github.spirylics.xgwt.hello; @SuppressWarnings("ALL") @JsType(isNative = true, name = "hello") public class Hello { @JsMethod(namespace = JsPackage.GLOBAL) public native static Hello hello(); @JsMethod(namespace = JsPackage.GLOBAL) public native static Hello hello(String network); public native Hello init(Credentials credentials); public native Hello init(Credentials credentials, Options options);
public native Promise<Auth, Error> login();
spirylics/x-gwt
x-gwt-polymer/src/main/java/com/github/spirylics/xgwt/polymer/PolymerElement.java
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Error.java // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public interface Error { // @JsProperty // String getCode(); // // @JsProperty // String getMessage(); // }
import com.github.spirylics.xgwt.essential.*; import com.github.spirylics.xgwt.essential.Error; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.query.client.js.JsUtils; import jsinterop.annotations.JsOverlay; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import java.util.Arrays; import java.util.function.Predicate; import java.util.stream.Stream;
package com.github.spirylics.xgwt.polymer; @JsType(isNative = true) public interface PolymerElement extends GQueryElement, Base { @JsProperty Lifecycle getLifecycle(); @SuppressWarnings("unusable-by-js") @JsProperty void setLifecycle(Lifecycle lifecycle); @JsOverlay default Lifecycle lifecycle() { if (getLifecycle() == null) { setLifecycle(new Lifecycle(this)); } return getLifecycle(); } @JsOverlay default <T> T call(final String method, final Object... args) { return JsUtils.jsni(this.el(), method, args); } @JsOverlay default <S, E, T> Promise<T, E> callWhen(Promise<S, E> promise, final String method, final Object... args) { return promise.then(new Fn.ArgRet<S, T>() { @Override public T e(S arg) { return call(method, args); } }); } @JsOverlay
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Error.java // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public interface Error { // @JsProperty // String getCode(); // // @JsProperty // String getMessage(); // } // Path: x-gwt-polymer/src/main/java/com/github/spirylics/xgwt/polymer/PolymerElement.java import com.github.spirylics.xgwt.essential.*; import com.github.spirylics.xgwt.essential.Error; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.query.client.js.JsUtils; import jsinterop.annotations.JsOverlay; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import java.util.Arrays; import java.util.function.Predicate; import java.util.stream.Stream; package com.github.spirylics.xgwt.polymer; @JsType(isNative = true) public interface PolymerElement extends GQueryElement, Base { @JsProperty Lifecycle getLifecycle(); @SuppressWarnings("unusable-by-js") @JsProperty void setLifecycle(Lifecycle lifecycle); @JsOverlay default Lifecycle lifecycle() { if (getLifecycle() == null) { setLifecycle(new Lifecycle(this)); } return getLifecycle(); } @JsOverlay default <T> T call(final String method, final Object... args) { return JsUtils.jsni(this.el(), method, args); } @JsOverlay default <S, E, T> Promise<T, E> callWhen(Promise<S, E> promise, final String method, final Object... args) { return promise.then(new Fn.ArgRet<S, T>() { @Override public T e(S arg) { return call(method, args); } }); } @JsOverlay
default <T> Promise<T, Error> callWhen(Lifecycle.State state, final String method, final Object... args) {
spirylics/x-gwt
x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/auth/Auth.java
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Fn.java // public abstract class Fn { // private Fn() { // } // // @JsFunction // public interface NoArg { // void e(); // } // // @JsFunction // public interface Arg<A> { // void e(A arg); // } // // @JsFunction // public interface ArgRet<A, R> { // R e(A arg); // } // // @JsFunction // public interface Args { // void e(Object... args); // } // // @JsFunction // public interface Resolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // // @JsFunction // public interface OpenResolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // } // // Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Promise.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public class Promise<S, E> extends Thenable<S, E> { // // @JsConstructor // public Promise(Fn.Resolver<S, E> resolver) { // } // // public static native <A, B> Promise<A, B> all(Promise<?, ?>[] promises); // // public static native <S> Promise<S, Error> resolve(S success); // // private Fn.Arg<S> resolve; // private Fn.Arg<E> reject; // // @JsOverlay // public final Promise<S, E> openResolve(S success) { // if (resolve == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // resolve.e(success); // return this; // } // // @JsOverlay // public final Promise<S, E> openReject(E error) { // if (reject == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // reject.e(error); // return this; // } // // @JsOverlay // public static <S, E> Promise<S, E> buildOpenPromise() { // final Map<String, Fn.Arg<?>> containers = new HashMap<>(2); // Fn.Resolver<S, E> resolver = new Fn.Resolver<S, E>() { // @Override // public void e(Fn.Arg<S> resolve, Fn.Arg<E> reject) { // containers.put("resolve", resolve); // containers.put("reject", reject); // } // }; // Promise<S, E> openPromise = new Promise<S, E>(resolver); // openPromise.resolve = (Fn.Arg<S>) containers.get("resolve"); // openPromise.reject = (Fn.Arg<E>) containers.get("reject"); // return openPromise; // } // }
import com.github.spirylics.xgwt.essential.Fn; import com.github.spirylics.xgwt.essential.Promise; import jsinterop.annotations.JsOverlay; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType;
package com.github.spirylics.xgwt.firebase.auth; @SuppressWarnings("ALL") @JsType(isNative = true, namespace = "firebase.auth", name = "Auth") public class Auth {
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Fn.java // public abstract class Fn { // private Fn() { // } // // @JsFunction // public interface NoArg { // void e(); // } // // @JsFunction // public interface Arg<A> { // void e(A arg); // } // // @JsFunction // public interface ArgRet<A, R> { // R e(A arg); // } // // @JsFunction // public interface Args { // void e(Object... args); // } // // @JsFunction // public interface Resolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // // @JsFunction // public interface OpenResolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // } // // Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Promise.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public class Promise<S, E> extends Thenable<S, E> { // // @JsConstructor // public Promise(Fn.Resolver<S, E> resolver) { // } // // public static native <A, B> Promise<A, B> all(Promise<?, ?>[] promises); // // public static native <S> Promise<S, Error> resolve(S success); // // private Fn.Arg<S> resolve; // private Fn.Arg<E> reject; // // @JsOverlay // public final Promise<S, E> openResolve(S success) { // if (resolve == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // resolve.e(success); // return this; // } // // @JsOverlay // public final Promise<S, E> openReject(E error) { // if (reject == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // reject.e(error); // return this; // } // // @JsOverlay // public static <S, E> Promise<S, E> buildOpenPromise() { // final Map<String, Fn.Arg<?>> containers = new HashMap<>(2); // Fn.Resolver<S, E> resolver = new Fn.Resolver<S, E>() { // @Override // public void e(Fn.Arg<S> resolve, Fn.Arg<E> reject) { // containers.put("resolve", resolve); // containers.put("reject", reject); // } // }; // Promise<S, E> openPromise = new Promise<S, E>(resolver); // openPromise.resolve = (Fn.Arg<S>) containers.get("resolve"); // openPromise.reject = (Fn.Arg<E>) containers.get("reject"); // return openPromise; // } // } // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/auth/Auth.java import com.github.spirylics.xgwt.essential.Fn; import com.github.spirylics.xgwt.essential.Promise; import jsinterop.annotations.JsOverlay; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; package com.github.spirylics.xgwt.firebase.auth; @SuppressWarnings("ALL") @JsType(isNative = true, namespace = "firebase.auth", name = "Auth") public class Auth {
public native Promise<Void, Error> applyActionCode(String code);
spirylics/x-gwt
x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/auth/Auth.java
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Fn.java // public abstract class Fn { // private Fn() { // } // // @JsFunction // public interface NoArg { // void e(); // } // // @JsFunction // public interface Arg<A> { // void e(A arg); // } // // @JsFunction // public interface ArgRet<A, R> { // R e(A arg); // } // // @JsFunction // public interface Args { // void e(Object... args); // } // // @JsFunction // public interface Resolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // // @JsFunction // public interface OpenResolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // } // // Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Promise.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public class Promise<S, E> extends Thenable<S, E> { // // @JsConstructor // public Promise(Fn.Resolver<S, E> resolver) { // } // // public static native <A, B> Promise<A, B> all(Promise<?, ?>[] promises); // // public static native <S> Promise<S, Error> resolve(S success); // // private Fn.Arg<S> resolve; // private Fn.Arg<E> reject; // // @JsOverlay // public final Promise<S, E> openResolve(S success) { // if (resolve == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // resolve.e(success); // return this; // } // // @JsOverlay // public final Promise<S, E> openReject(E error) { // if (reject == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // reject.e(error); // return this; // } // // @JsOverlay // public static <S, E> Promise<S, E> buildOpenPromise() { // final Map<String, Fn.Arg<?>> containers = new HashMap<>(2); // Fn.Resolver<S, E> resolver = new Fn.Resolver<S, E>() { // @Override // public void e(Fn.Arg<S> resolve, Fn.Arg<E> reject) { // containers.put("resolve", resolve); // containers.put("reject", reject); // } // }; // Promise<S, E> openPromise = new Promise<S, E>(resolver); // openPromise.resolve = (Fn.Arg<S>) containers.get("resolve"); // openPromise.reject = (Fn.Arg<E>) containers.get("reject"); // return openPromise; // } // }
import com.github.spirylics.xgwt.essential.Fn; import com.github.spirylics.xgwt.essential.Promise; import jsinterop.annotations.JsOverlay; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType;
package com.github.spirylics.xgwt.firebase.auth; @SuppressWarnings("ALL") @JsType(isNative = true, namespace = "firebase.auth", name = "Auth") public class Auth { public native Promise<Void, Error> applyActionCode(String code); public native Promise<ActionCodeInfo, Error> checkActionCode(String code); public native Promise<Void, Error> confirmPasswordReset(String code, String newPassword); public native Promise<UserCredential, Error> signInWithPopup(AuthProvider authProvider); public native Promise<User, Error> signInWithEmailAndPassword(String email, String password); public native Promise<User, Error> signInAnonymously(); public native Promise<Void, Error> signOut(); public native Promise<User, Error> createUserWithEmailAndPassword(String email, String password); public native Promise<String[], Error> fetchProvidersForEmail(String email); public native Promise<Void, Error> sendPasswordResetEmail(String email); public native Promise<User, Error> signInWithCredential(AuthCredential authCredential); public native Promise<User, Error> signInWithCustomToken(String token); public native Promise<Void, Error> signInWithRedirect(AuthProvider authProvider); public native Promise<String, Error> verifyPasswordResetCode(String code); @JsProperty public native User getCurrentUser();
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Fn.java // public abstract class Fn { // private Fn() { // } // // @JsFunction // public interface NoArg { // void e(); // } // // @JsFunction // public interface Arg<A> { // void e(A arg); // } // // @JsFunction // public interface ArgRet<A, R> { // R e(A arg); // } // // @JsFunction // public interface Args { // void e(Object... args); // } // // @JsFunction // public interface Resolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // // @JsFunction // public interface OpenResolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // } // // Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Promise.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public class Promise<S, E> extends Thenable<S, E> { // // @JsConstructor // public Promise(Fn.Resolver<S, E> resolver) { // } // // public static native <A, B> Promise<A, B> all(Promise<?, ?>[] promises); // // public static native <S> Promise<S, Error> resolve(S success); // // private Fn.Arg<S> resolve; // private Fn.Arg<E> reject; // // @JsOverlay // public final Promise<S, E> openResolve(S success) { // if (resolve == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // resolve.e(success); // return this; // } // // @JsOverlay // public final Promise<S, E> openReject(E error) { // if (reject == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // reject.e(error); // return this; // } // // @JsOverlay // public static <S, E> Promise<S, E> buildOpenPromise() { // final Map<String, Fn.Arg<?>> containers = new HashMap<>(2); // Fn.Resolver<S, E> resolver = new Fn.Resolver<S, E>() { // @Override // public void e(Fn.Arg<S> resolve, Fn.Arg<E> reject) { // containers.put("resolve", resolve); // containers.put("reject", reject); // } // }; // Promise<S, E> openPromise = new Promise<S, E>(resolver); // openPromise.resolve = (Fn.Arg<S>) containers.get("resolve"); // openPromise.reject = (Fn.Arg<E>) containers.get("reject"); // return openPromise; // } // } // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/auth/Auth.java import com.github.spirylics.xgwt.essential.Fn; import com.github.spirylics.xgwt.essential.Promise; import jsinterop.annotations.JsOverlay; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; package com.github.spirylics.xgwt.firebase.auth; @SuppressWarnings("ALL") @JsType(isNative = true, namespace = "firebase.auth", name = "Auth") public class Auth { public native Promise<Void, Error> applyActionCode(String code); public native Promise<ActionCodeInfo, Error> checkActionCode(String code); public native Promise<Void, Error> confirmPasswordReset(String code, String newPassword); public native Promise<UserCredential, Error> signInWithPopup(AuthProvider authProvider); public native Promise<User, Error> signInWithEmailAndPassword(String email, String password); public native Promise<User, Error> signInAnonymously(); public native Promise<Void, Error> signOut(); public native Promise<User, Error> createUserWithEmailAndPassword(String email, String password); public native Promise<String[], Error> fetchProvidersForEmail(String email); public native Promise<Void, Error> sendPasswordResetEmail(String email); public native Promise<User, Error> signInWithCredential(AuthCredential authCredential); public native Promise<User, Error> signInWithCustomToken(String token); public native Promise<Void, Error> signInWithRedirect(AuthProvider authProvider); public native Promise<String, Error> verifyPasswordResetCode(String code); @JsProperty public native User getCurrentUser();
public native Fn.NoArg onAuthStateChanged(Fn.Arg<User> fn);
spirylics/x-gwt
x-gwt-polymer/src/main/java/com/github/spirylics/xgwt/polymer/Polymer.java
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Element.java // @JsType(isNative = true) // public interface Element { // // @JsOverlay // static <E extends Element> E create(String tag) { // return (E) DOM.createElement(tag); // } // // @JsOverlay // static <E extends Element> E create(String tag, Map<String, Object> attributes) { // return (E) GQuery.$("<" + tag + " " // + attributes.entrySet().stream() // .map(e -> e.getKey() + "=\"" + XMapper.get().write(e.getValue()) + "\"") // .collect(Collectors.joining(" ")) // + "></" + tag + ">").get(0); // } // // void addEventListener(String event, Fn.Arg<Event> function, boolean useCapture); // // void addEventListener(String event, Fn.Arg<Event> function); // // void removeEventListener(String event, Fn.Arg<Event> function, boolean useCapture); // // void removeEventListener(String event, Fn.Arg<Event> function); // // String getAttribute(String attribute); // // void setAttribute(String attribute, Object value); // // void removeAttribute(String attribute); // // <E extends Element> E querySelector(String selector); // // <E extends Element> E[] querySelectorAll(String selector); // // void focus(); // // void blur(); // // void appendChild(Element element); // // @JsOverlay // default <E extends Element> Stream<E> querySelectorStream(String selector) { // return Arrays.stream(querySelectorAll(selector)); // } // // @JsOverlay // default void appendChild(Widget widget) { // appendChild((Element) widget.getElement()); // } // // // @JsOverlay // default <E extends Element> E focus(boolean focused) { // if (focused) { // focus(); // } else { // blur(); // } // return (E) this; // } // // @JsOverlay // default <E extends Element> E hidden(boolean hidden) { // return attribute("hidden", hidden); // } // // @JsOverlay // default <E extends Element> E attribute(String attribute, Object value) { // if (value == null || Boolean.FALSE.equals(value)) { // removeAttribute(attribute); // } else { // setAttribute(attribute, XMapper.get().write(value)); // } // return (E) this; // } // // @JsOverlay // default <V> V attribute(String attribute, Class<V> clazz) { // return XMapper.get().read(getAttribute(attribute), clazz); // } // // }
import com.github.spirylics.xgwt.essential.Element; import com.google.gwt.query.client.Function; import com.google.gwt.query.client.GQuery; import com.google.gwt.query.client.Promise; import com.google.gwt.query.client.plugins.deferred.PromiseFunction; import jsinterop.annotations.*; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.google.gwt.query.client.GQuery.$; import static com.google.gwt.query.client.GQuery.body;
package com.github.spirylics.xgwt.polymer; @JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Polymer") public abstract class Polymer { @JsProperty(name = "Base") public static native Base Base(); @JsProperty(name = "dom") public static native Dom dom(); @JsMethod public static native DomApi dom(Base base); @JsMethod
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Element.java // @JsType(isNative = true) // public interface Element { // // @JsOverlay // static <E extends Element> E create(String tag) { // return (E) DOM.createElement(tag); // } // // @JsOverlay // static <E extends Element> E create(String tag, Map<String, Object> attributes) { // return (E) GQuery.$("<" + tag + " " // + attributes.entrySet().stream() // .map(e -> e.getKey() + "=\"" + XMapper.get().write(e.getValue()) + "\"") // .collect(Collectors.joining(" ")) // + "></" + tag + ">").get(0); // } // // void addEventListener(String event, Fn.Arg<Event> function, boolean useCapture); // // void addEventListener(String event, Fn.Arg<Event> function); // // void removeEventListener(String event, Fn.Arg<Event> function, boolean useCapture); // // void removeEventListener(String event, Fn.Arg<Event> function); // // String getAttribute(String attribute); // // void setAttribute(String attribute, Object value); // // void removeAttribute(String attribute); // // <E extends Element> E querySelector(String selector); // // <E extends Element> E[] querySelectorAll(String selector); // // void focus(); // // void blur(); // // void appendChild(Element element); // // @JsOverlay // default <E extends Element> Stream<E> querySelectorStream(String selector) { // return Arrays.stream(querySelectorAll(selector)); // } // // @JsOverlay // default void appendChild(Widget widget) { // appendChild((Element) widget.getElement()); // } // // // @JsOverlay // default <E extends Element> E focus(boolean focused) { // if (focused) { // focus(); // } else { // blur(); // } // return (E) this; // } // // @JsOverlay // default <E extends Element> E hidden(boolean hidden) { // return attribute("hidden", hidden); // } // // @JsOverlay // default <E extends Element> E attribute(String attribute, Object value) { // if (value == null || Boolean.FALSE.equals(value)) { // removeAttribute(attribute); // } else { // setAttribute(attribute, XMapper.get().write(value)); // } // return (E) this; // } // // @JsOverlay // default <V> V attribute(String attribute, Class<V> clazz) { // return XMapper.get().read(getAttribute(attribute), clazz); // } // // } // Path: x-gwt-polymer/src/main/java/com/github/spirylics/xgwt/polymer/Polymer.java import com.github.spirylics.xgwt.essential.Element; import com.google.gwt.query.client.Function; import com.google.gwt.query.client.GQuery; import com.google.gwt.query.client.Promise; import com.google.gwt.query.client.plugins.deferred.PromiseFunction; import jsinterop.annotations.*; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.google.gwt.query.client.GQuery.$; import static com.google.gwt.query.client.GQuery.body; package com.github.spirylics.xgwt.polymer; @JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Polymer") public abstract class Polymer { @JsProperty(name = "Base") public static native Base Base(); @JsProperty(name = "dom") public static native Dom dom(); @JsMethod public static native DomApi dom(Base base); @JsMethod
public static native DomApi dom(Element element);
spirylics/x-gwt
x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/auth/AuthRegistration.java
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Fn.java // public abstract class Fn { // private Fn() { // } // // @JsFunction // public interface NoArg { // void e(); // } // // @JsFunction // public interface Arg<A> { // void e(A arg); // } // // @JsFunction // public interface ArgRet<A, R> { // R e(A arg); // } // // @JsFunction // public interface Args { // void e(Object... args); // } // // @JsFunction // public interface Resolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // // @JsFunction // public interface OpenResolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // } // // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/HandlerRegistration.java // public interface HandlerRegistration { // <R extends HandlerRegistration> R on(); // // <R extends HandlerRegistration> R off(); // }
import com.github.spirylics.xgwt.essential.Fn; import com.github.spirylics.xgwt.firebase.HandlerRegistration;
package com.github.spirylics.xgwt.firebase.auth; public class AuthRegistration implements HandlerRegistration { final Auth auth;
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Fn.java // public abstract class Fn { // private Fn() { // } // // @JsFunction // public interface NoArg { // void e(); // } // // @JsFunction // public interface Arg<A> { // void e(A arg); // } // // @JsFunction // public interface ArgRet<A, R> { // R e(A arg); // } // // @JsFunction // public interface Args { // void e(Object... args); // } // // @JsFunction // public interface Resolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // // @JsFunction // public interface OpenResolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // } // // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/HandlerRegistration.java // public interface HandlerRegistration { // <R extends HandlerRegistration> R on(); // // <R extends HandlerRegistration> R off(); // } // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/auth/AuthRegistration.java import com.github.spirylics.xgwt.essential.Fn; import com.github.spirylics.xgwt.firebase.HandlerRegistration; package com.github.spirylics.xgwt.firebase.auth; public class AuthRegistration implements HandlerRegistration { final Auth auth;
final Fn.Arg<User> fn;
spirylics/x-gwt
x-gwt-analytics/src/main/java/com/github/spirylics/xgwt/analytics/XAnalytics.java
// Path: x-gwt-cordova/src/main/java/com/github/spirylics/xgwt/cordova/XCordova.java // public class XCordova { // final PhoneGap phoneGap; // final GeolocationOptions geolocationOptions; // GeolocationCancelableCallback singleGeolocationCallback; // boolean networkIndicationShow; // // public XCordova() { // this(GWT.create(PhoneGap.class)); // } // // public XCordova(PhoneGap phoneGap) { // this.phoneGap = phoneGap; // this.geolocationOptions = new GeolocationOptions(); // this.geolocationOptions.setTimeout(5000); // this.geolocationOptions.setEnableHighAccuracy(true); // this.geolocationOptions.setMaximumAge(60000); // } // // public XCordova initialize(final Promise<Void, Object> promise) { // phoneGap.addHandler(new PhoneGapAvailableHandler() { // @Override // public void onPhoneGapAvailable(PhoneGapAvailableEvent phoneGapAvailableEvent) { // promise.openResolve(null); // } // }); // phoneGap.addHandler(new PhoneGapTimeoutHandler() { // @Override // public void onPhoneGapTimeout(PhoneGapTimeoutEvent phoneGapTimeoutEvent) { // promise.openReject(phoneGapTimeoutEvent); // } // }); // phoneGap.initializePhoneGap(); // return this; // } // // public Promise<Void, Object> initialize() { // Promise<Void, Object> promise = Promise.buildOpenPromise(); // initialize(promise); // return promise; // } // // public Device getDevice() { // return phoneGap.getDevice(); // } // // public Promise<Device, Object> getDevicePromise() { // return initialize().then(() -> phoneGap.getDevice()); // } // // public XCordova hideSplashScreen() { // phoneGap.getSplashScreen().hide(); // return this; // } // // public XCordova openKeyboard() { // JsUtils.jsni("cordova.plugins.Keyboard.show"); // return this; // } // // public XCordova dismissKeyboard() { // JsUtils.jsni("cordova.plugins.Keyboard.close"); // return this; // } // // public XCordova showNetworkIndicator(boolean show) { // if (this.networkIndicationShow != show) { // JsUtils.jsni(show ? "NetworkActivityIndicator.show" : "NetworkActivityIndicator.hide"); // this.networkIndicationShow = show; // } // return this; // } // // public void cancelSingleGeolocation() { // if (singleGeolocationCallback != null) { // singleGeolocationCallback.cancel(); // singleGeolocationCallback = null; // } // } // // public XCordova getSingleCurrentPosition(GeolocationCancelableCallback callback) { // cancelSingleGeolocation(); // this.singleGeolocationCallback = callback; // getCurrentPosition(callback); // return this; // } // // public XCordova getCurrentPosition(GeolocationCallback callback) { // phoneGap.getGeolocation().getCurrentPosition(callback, geolocationOptions); // return this; // } // // public boolean isNative() { // return phoneGap.isPhoneGapDevice(); // } // // public boolean isDesktop() { // return !Window.Navigator.getUserAgent().matches(".*(iPhone|iPod|iPad|Android|BlackBerry|IEMobile).*"); // } // // public native boolean isTactile() /*-{ // return !!('ontouchstart' in $wnd) || !!('ongesturechange' in $wnd); // }-*/; // }
import com.arcbees.analytics.shared.Analytics; import com.arcbees.analytics.shared.AnalyticsPlugin; import com.arcbees.analytics.shared.Storage; import com.arcbees.analytics.shared.Task; import com.arcbees.analytics.shared.options.EventsOptions; import com.arcbees.analytics.shared.options.TimingOptions; import com.github.spirylics.xgwt.cordova.XCordova; import com.google.common.base.Joiner; import com.google.common.base.Strings; import com.google.gwt.query.client.Function; import com.google.gwt.query.client.GQuery; import com.google.gwt.query.client.Promise; import com.google.gwt.query.client.plugins.deferred.Deferred; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import com.gwtplatform.mvp.shared.proxy.TokenFormatter;
package com.github.spirylics.xgwt.analytics; public class XAnalytics { final Analytics analytics; final TokenFormatter tokenFormatter; final Joiner labelJoiner = Joiner.on("-").skipNulls(); final String appName; final String appVersion; final protected Promise.Deferred readyDeferred = new Deferred(); com.google.common.base.Function<PlaceRequest, Void> sendRequestFn; public XAnalytics(final Analytics analytics,
// Path: x-gwt-cordova/src/main/java/com/github/spirylics/xgwt/cordova/XCordova.java // public class XCordova { // final PhoneGap phoneGap; // final GeolocationOptions geolocationOptions; // GeolocationCancelableCallback singleGeolocationCallback; // boolean networkIndicationShow; // // public XCordova() { // this(GWT.create(PhoneGap.class)); // } // // public XCordova(PhoneGap phoneGap) { // this.phoneGap = phoneGap; // this.geolocationOptions = new GeolocationOptions(); // this.geolocationOptions.setTimeout(5000); // this.geolocationOptions.setEnableHighAccuracy(true); // this.geolocationOptions.setMaximumAge(60000); // } // // public XCordova initialize(final Promise<Void, Object> promise) { // phoneGap.addHandler(new PhoneGapAvailableHandler() { // @Override // public void onPhoneGapAvailable(PhoneGapAvailableEvent phoneGapAvailableEvent) { // promise.openResolve(null); // } // }); // phoneGap.addHandler(new PhoneGapTimeoutHandler() { // @Override // public void onPhoneGapTimeout(PhoneGapTimeoutEvent phoneGapTimeoutEvent) { // promise.openReject(phoneGapTimeoutEvent); // } // }); // phoneGap.initializePhoneGap(); // return this; // } // // public Promise<Void, Object> initialize() { // Promise<Void, Object> promise = Promise.buildOpenPromise(); // initialize(promise); // return promise; // } // // public Device getDevice() { // return phoneGap.getDevice(); // } // // public Promise<Device, Object> getDevicePromise() { // return initialize().then(() -> phoneGap.getDevice()); // } // // public XCordova hideSplashScreen() { // phoneGap.getSplashScreen().hide(); // return this; // } // // public XCordova openKeyboard() { // JsUtils.jsni("cordova.plugins.Keyboard.show"); // return this; // } // // public XCordova dismissKeyboard() { // JsUtils.jsni("cordova.plugins.Keyboard.close"); // return this; // } // // public XCordova showNetworkIndicator(boolean show) { // if (this.networkIndicationShow != show) { // JsUtils.jsni(show ? "NetworkActivityIndicator.show" : "NetworkActivityIndicator.hide"); // this.networkIndicationShow = show; // } // return this; // } // // public void cancelSingleGeolocation() { // if (singleGeolocationCallback != null) { // singleGeolocationCallback.cancel(); // singleGeolocationCallback = null; // } // } // // public XCordova getSingleCurrentPosition(GeolocationCancelableCallback callback) { // cancelSingleGeolocation(); // this.singleGeolocationCallback = callback; // getCurrentPosition(callback); // return this; // } // // public XCordova getCurrentPosition(GeolocationCallback callback) { // phoneGap.getGeolocation().getCurrentPosition(callback, geolocationOptions); // return this; // } // // public boolean isNative() { // return phoneGap.isPhoneGapDevice(); // } // // public boolean isDesktop() { // return !Window.Navigator.getUserAgent().matches(".*(iPhone|iPod|iPad|Android|BlackBerry|IEMobile).*"); // } // // public native boolean isTactile() /*-{ // return !!('ontouchstart' in $wnd) || !!('ongesturechange' in $wnd); // }-*/; // } // Path: x-gwt-analytics/src/main/java/com/github/spirylics/xgwt/analytics/XAnalytics.java import com.arcbees.analytics.shared.Analytics; import com.arcbees.analytics.shared.AnalyticsPlugin; import com.arcbees.analytics.shared.Storage; import com.arcbees.analytics.shared.Task; import com.arcbees.analytics.shared.options.EventsOptions; import com.arcbees.analytics.shared.options.TimingOptions; import com.github.spirylics.xgwt.cordova.XCordova; import com.google.common.base.Joiner; import com.google.common.base.Strings; import com.google.gwt.query.client.Function; import com.google.gwt.query.client.GQuery; import com.google.gwt.query.client.Promise; import com.google.gwt.query.client.plugins.deferred.Deferred; import com.gwtplatform.mvp.shared.proxy.PlaceRequest; import com.gwtplatform.mvp.shared.proxy.TokenFormatter; package com.github.spirylics.xgwt.analytics; public class XAnalytics { final Analytics analytics; final TokenFormatter tokenFormatter; final Joiner labelJoiner = Joiner.on("-").skipNulls(); final String appName; final String appVersion; final protected Promise.Deferred readyDeferred = new Deferred(); com.google.common.base.Function<PlaceRequest, Void> sendRequestFn; public XAnalytics(final Analytics analytics,
final XCordova cordova,
spirylics/x-gwt
x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/database/EventRegistration.java
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Fn.java // public abstract class Fn { // private Fn() { // } // // @JsFunction // public interface NoArg { // void e(); // } // // @JsFunction // public interface Arg<A> { // void e(A arg); // } // // @JsFunction // public interface ArgRet<A, R> { // R e(A arg); // } // // @JsFunction // public interface Args { // void e(Object... args); // } // // @JsFunction // public interface Resolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // // @JsFunction // public interface OpenResolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // } // // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/Event.java // public enum Event { // value, child_added, child_removed, child_changed, child_moved; // } // // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/HandlerRegistration.java // public interface HandlerRegistration { // <R extends HandlerRegistration> R on(); // // <R extends HandlerRegistration> R off(); // }
import com.github.spirylics.xgwt.essential.Fn; import com.github.spirylics.xgwt.firebase.Event; import com.github.spirylics.xgwt.firebase.HandlerRegistration;
package com.github.spirylics.xgwt.firebase.database; public class EventRegistration implements HandlerRegistration { final Reference reference;
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Fn.java // public abstract class Fn { // private Fn() { // } // // @JsFunction // public interface NoArg { // void e(); // } // // @JsFunction // public interface Arg<A> { // void e(A arg); // } // // @JsFunction // public interface ArgRet<A, R> { // R e(A arg); // } // // @JsFunction // public interface Args { // void e(Object... args); // } // // @JsFunction // public interface Resolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // // @JsFunction // public interface OpenResolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // } // // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/Event.java // public enum Event { // value, child_added, child_removed, child_changed, child_moved; // } // // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/HandlerRegistration.java // public interface HandlerRegistration { // <R extends HandlerRegistration> R on(); // // <R extends HandlerRegistration> R off(); // } // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/database/EventRegistration.java import com.github.spirylics.xgwt.essential.Fn; import com.github.spirylics.xgwt.firebase.Event; import com.github.spirylics.xgwt.firebase.HandlerRegistration; package com.github.spirylics.xgwt.firebase.database; public class EventRegistration implements HandlerRegistration { final Reference reference;
final Event event;
spirylics/x-gwt
x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/database/EventRegistration.java
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Fn.java // public abstract class Fn { // private Fn() { // } // // @JsFunction // public interface NoArg { // void e(); // } // // @JsFunction // public interface Arg<A> { // void e(A arg); // } // // @JsFunction // public interface ArgRet<A, R> { // R e(A arg); // } // // @JsFunction // public interface Args { // void e(Object... args); // } // // @JsFunction // public interface Resolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // // @JsFunction // public interface OpenResolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // } // // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/Event.java // public enum Event { // value, child_added, child_removed, child_changed, child_moved; // } // // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/HandlerRegistration.java // public interface HandlerRegistration { // <R extends HandlerRegistration> R on(); // // <R extends HandlerRegistration> R off(); // }
import com.github.spirylics.xgwt.essential.Fn; import com.github.spirylics.xgwt.firebase.Event; import com.github.spirylics.xgwt.firebase.HandlerRegistration;
package com.github.spirylics.xgwt.firebase.database; public class EventRegistration implements HandlerRegistration { final Reference reference; final Event event;
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Fn.java // public abstract class Fn { // private Fn() { // } // // @JsFunction // public interface NoArg { // void e(); // } // // @JsFunction // public interface Arg<A> { // void e(A arg); // } // // @JsFunction // public interface ArgRet<A, R> { // R e(A arg); // } // // @JsFunction // public interface Args { // void e(Object... args); // } // // @JsFunction // public interface Resolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // // @JsFunction // public interface OpenResolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // } // // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/Event.java // public enum Event { // value, child_added, child_removed, child_changed, child_moved; // } // // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/HandlerRegistration.java // public interface HandlerRegistration { // <R extends HandlerRegistration> R on(); // // <R extends HandlerRegistration> R off(); // } // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/database/EventRegistration.java import com.github.spirylics.xgwt.essential.Fn; import com.github.spirylics.xgwt.firebase.Event; import com.github.spirylics.xgwt.firebase.HandlerRegistration; package com.github.spirylics.xgwt.firebase.database; public class EventRegistration implements HandlerRegistration { final Reference reference; final Event event;
final Fn.Arg<XDataSnapshot> fn;
spirylics/x-gwt
x-gwt-polymer/src/main/java/com/github/spirylics/xgwt/polymer/Dialog.java
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Error.java // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public interface Error { // @JsProperty // String getCode(); // // @JsProperty // String getMessage(); // } // // Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Fn.java // public abstract class Fn { // private Fn() { // } // // @JsFunction // public interface NoArg { // void e(); // } // // @JsFunction // public interface Arg<A> { // void e(A arg); // } // // @JsFunction // public interface ArgRet<A, R> { // R e(A arg); // } // // @JsFunction // public interface Args { // void e(Object... args); // } // // @JsFunction // public interface Resolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // // @JsFunction // public interface OpenResolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // } // // Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Promise.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public class Promise<S, E> extends Thenable<S, E> { // // @JsConstructor // public Promise(Fn.Resolver<S, E> resolver) { // } // // public static native <A, B> Promise<A, B> all(Promise<?, ?>[] promises); // // public static native <S> Promise<S, Error> resolve(S success); // // private Fn.Arg<S> resolve; // private Fn.Arg<E> reject; // // @JsOverlay // public final Promise<S, E> openResolve(S success) { // if (resolve == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // resolve.e(success); // return this; // } // // @JsOverlay // public final Promise<S, E> openReject(E error) { // if (reject == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // reject.e(error); // return this; // } // // @JsOverlay // public static <S, E> Promise<S, E> buildOpenPromise() { // final Map<String, Fn.Arg<?>> containers = new HashMap<>(2); // Fn.Resolver<S, E> resolver = new Fn.Resolver<S, E>() { // @Override // public void e(Fn.Arg<S> resolve, Fn.Arg<E> reject) { // containers.put("resolve", resolve); // containers.put("reject", reject); // } // }; // Promise<S, E> openPromise = new Promise<S, E>(resolver); // openPromise.resolve = (Fn.Arg<S>) containers.get("resolve"); // openPromise.reject = (Fn.Arg<E>) containers.get("reject"); // return openPromise; // } // }
import com.github.spirylics.xgwt.essential.Error; import com.github.spirylics.xgwt.essential.Fn; import com.github.spirylics.xgwt.essential.Promise; import com.google.common.base.Strings; import com.google.gwt.core.client.Scheduler; import com.google.gwt.event.logical.shared.*; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.History; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import java.util.function.Predicate;
@JsProperty boolean isConfirmed(); } String dialogParameter; HandlerRegistration historyHandlerRegistration; HandlerRegistration openedHandlerRegistration; public Dialog(String html) { super("paper-dialog", html); p().attribute("entry-animation", "scale-up-animation") .attribute("exit-animation", "fade-out-animation") .attribute("with-backdrop", ""); } void enableHistory() { if (this.historyHandlerRegistration == null) { this.historyHandlerRegistration = History.addValueChangeHandler(event -> overlay(hasHistoryDialogParameter(event.getValue())) .then(opened -> { if (opened) { OpenEvent.fire(Dialog.this, Dialog.this); } else { disableHistory(); CloseEvent.fire(Dialog.this, Dialog.this); } })); } if (this.openedHandlerRegistration == null) {
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Error.java // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public interface Error { // @JsProperty // String getCode(); // // @JsProperty // String getMessage(); // } // // Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Fn.java // public abstract class Fn { // private Fn() { // } // // @JsFunction // public interface NoArg { // void e(); // } // // @JsFunction // public interface Arg<A> { // void e(A arg); // } // // @JsFunction // public interface ArgRet<A, R> { // R e(A arg); // } // // @JsFunction // public interface Args { // void e(Object... args); // } // // @JsFunction // public interface Resolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // // @JsFunction // public interface OpenResolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // } // // Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Promise.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public class Promise<S, E> extends Thenable<S, E> { // // @JsConstructor // public Promise(Fn.Resolver<S, E> resolver) { // } // // public static native <A, B> Promise<A, B> all(Promise<?, ?>[] promises); // // public static native <S> Promise<S, Error> resolve(S success); // // private Fn.Arg<S> resolve; // private Fn.Arg<E> reject; // // @JsOverlay // public final Promise<S, E> openResolve(S success) { // if (resolve == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // resolve.e(success); // return this; // } // // @JsOverlay // public final Promise<S, E> openReject(E error) { // if (reject == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // reject.e(error); // return this; // } // // @JsOverlay // public static <S, E> Promise<S, E> buildOpenPromise() { // final Map<String, Fn.Arg<?>> containers = new HashMap<>(2); // Fn.Resolver<S, E> resolver = new Fn.Resolver<S, E>() { // @Override // public void e(Fn.Arg<S> resolve, Fn.Arg<E> reject) { // containers.put("resolve", resolve); // containers.put("reject", reject); // } // }; // Promise<S, E> openPromise = new Promise<S, E>(resolver); // openPromise.resolve = (Fn.Arg<S>) containers.get("resolve"); // openPromise.reject = (Fn.Arg<E>) containers.get("reject"); // return openPromise; // } // } // Path: x-gwt-polymer/src/main/java/com/github/spirylics/xgwt/polymer/Dialog.java import com.github.spirylics.xgwt.essential.Error; import com.github.spirylics.xgwt.essential.Fn; import com.github.spirylics.xgwt.essential.Promise; import com.google.common.base.Strings; import com.google.gwt.core.client.Scheduler; import com.google.gwt.event.logical.shared.*; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.History; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import java.util.function.Predicate; @JsProperty boolean isConfirmed(); } String dialogParameter; HandlerRegistration historyHandlerRegistration; HandlerRegistration openedHandlerRegistration; public Dialog(String html) { super("paper-dialog", html); p().attribute("entry-animation", "scale-up-animation") .attribute("exit-animation", "fade-out-animation") .attribute("with-backdrop", ""); } void enableHistory() { if (this.historyHandlerRegistration == null) { this.historyHandlerRegistration = History.addValueChangeHandler(event -> overlay(hasHistoryDialogParameter(event.getValue())) .then(opened -> { if (opened) { OpenEvent.fire(Dialog.this, Dialog.this); } else { disableHistory(); CloseEvent.fire(Dialog.this, Dialog.this); } })); } if (this.openedHandlerRegistration == null) {
openedHandlerRegistration = p().onPropertyChange("opened", (Fn.Arg<Boolean>) opened -> {
spirylics/x-gwt
x-gwt-polymer/src/main/java/com/github/spirylics/xgwt/polymer/Dialog.java
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Error.java // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public interface Error { // @JsProperty // String getCode(); // // @JsProperty // String getMessage(); // } // // Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Fn.java // public abstract class Fn { // private Fn() { // } // // @JsFunction // public interface NoArg { // void e(); // } // // @JsFunction // public interface Arg<A> { // void e(A arg); // } // // @JsFunction // public interface ArgRet<A, R> { // R e(A arg); // } // // @JsFunction // public interface Args { // void e(Object... args); // } // // @JsFunction // public interface Resolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // // @JsFunction // public interface OpenResolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // } // // Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Promise.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public class Promise<S, E> extends Thenable<S, E> { // // @JsConstructor // public Promise(Fn.Resolver<S, E> resolver) { // } // // public static native <A, B> Promise<A, B> all(Promise<?, ?>[] promises); // // public static native <S> Promise<S, Error> resolve(S success); // // private Fn.Arg<S> resolve; // private Fn.Arg<E> reject; // // @JsOverlay // public final Promise<S, E> openResolve(S success) { // if (resolve == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // resolve.e(success); // return this; // } // // @JsOverlay // public final Promise<S, E> openReject(E error) { // if (reject == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // reject.e(error); // return this; // } // // @JsOverlay // public static <S, E> Promise<S, E> buildOpenPromise() { // final Map<String, Fn.Arg<?>> containers = new HashMap<>(2); // Fn.Resolver<S, E> resolver = new Fn.Resolver<S, E>() { // @Override // public void e(Fn.Arg<S> resolve, Fn.Arg<E> reject) { // containers.put("resolve", resolve); // containers.put("reject", reject); // } // }; // Promise<S, E> openPromise = new Promise<S, E>(resolver); // openPromise.resolve = (Fn.Arg<S>) containers.get("resolve"); // openPromise.reject = (Fn.Arg<E>) containers.get("reject"); // return openPromise; // } // }
import com.github.spirylics.xgwt.essential.Error; import com.github.spirylics.xgwt.essential.Fn; import com.github.spirylics.xgwt.essential.Promise; import com.google.common.base.Strings; import com.google.gwt.core.client.Scheduler; import com.google.gwt.event.logical.shared.*; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.History; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import java.util.function.Predicate;
String getDialogParameter() { if (Strings.isNullOrEmpty(dialogParameter)) { throw new IllegalStateException("no history token defined!"); } return dialogParameter; } boolean hasHistoryDialogParameter(String historyToken) { return Strings.nullToEmpty(historyToken).contains(getDialogParameter()); } Dialog addDialogParameter() { Scheduler.get().scheduleDeferred(() -> { if (!hasHistoryDialogParameter(History.getToken())) { History.newItem(History.getToken() + (Strings.isNullOrEmpty(History.getToken()) ? "#" : ";") + getDialogParameter(), true); } }); return this; } void removeDialogParameter() { Scheduler.get().scheduleDeferred(() -> { if (hasHistoryDialogParameter(History.getToken())) { History.back(); } }); }
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Error.java // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public interface Error { // @JsProperty // String getCode(); // // @JsProperty // String getMessage(); // } // // Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Fn.java // public abstract class Fn { // private Fn() { // } // // @JsFunction // public interface NoArg { // void e(); // } // // @JsFunction // public interface Arg<A> { // void e(A arg); // } // // @JsFunction // public interface ArgRet<A, R> { // R e(A arg); // } // // @JsFunction // public interface Args { // void e(Object... args); // } // // @JsFunction // public interface Resolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // // @JsFunction // public interface OpenResolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // } // // Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Promise.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public class Promise<S, E> extends Thenable<S, E> { // // @JsConstructor // public Promise(Fn.Resolver<S, E> resolver) { // } // // public static native <A, B> Promise<A, B> all(Promise<?, ?>[] promises); // // public static native <S> Promise<S, Error> resolve(S success); // // private Fn.Arg<S> resolve; // private Fn.Arg<E> reject; // // @JsOverlay // public final Promise<S, E> openResolve(S success) { // if (resolve == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // resolve.e(success); // return this; // } // // @JsOverlay // public final Promise<S, E> openReject(E error) { // if (reject == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // reject.e(error); // return this; // } // // @JsOverlay // public static <S, E> Promise<S, E> buildOpenPromise() { // final Map<String, Fn.Arg<?>> containers = new HashMap<>(2); // Fn.Resolver<S, E> resolver = new Fn.Resolver<S, E>() { // @Override // public void e(Fn.Arg<S> resolve, Fn.Arg<E> reject) { // containers.put("resolve", resolve); // containers.put("reject", reject); // } // }; // Promise<S, E> openPromise = new Promise<S, E>(resolver); // openPromise.resolve = (Fn.Arg<S>) containers.get("resolve"); // openPromise.reject = (Fn.Arg<E>) containers.get("reject"); // return openPromise; // } // } // Path: x-gwt-polymer/src/main/java/com/github/spirylics/xgwt/polymer/Dialog.java import com.github.spirylics.xgwt.essential.Error; import com.github.spirylics.xgwt.essential.Fn; import com.github.spirylics.xgwt.essential.Promise; import com.google.common.base.Strings; import com.google.gwt.core.client.Scheduler; import com.google.gwt.event.logical.shared.*; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.History; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import java.util.function.Predicate; String getDialogParameter() { if (Strings.isNullOrEmpty(dialogParameter)) { throw new IllegalStateException("no history token defined!"); } return dialogParameter; } boolean hasHistoryDialogParameter(String historyToken) { return Strings.nullToEmpty(historyToken).contains(getDialogParameter()); } Dialog addDialogParameter() { Scheduler.get().scheduleDeferred(() -> { if (!hasHistoryDialogParameter(History.getToken())) { History.newItem(History.getToken() + (Strings.isNullOrEmpty(History.getToken()) ? "#" : ";") + getDialogParameter(), true); } }); return this; } void removeDialogParameter() { Scheduler.get().scheduleDeferred(() -> { if (hasHistoryDialogParameter(History.getToken())) { History.back(); } }); }
Promise<Boolean, Error> overlay(final boolean opened) {
spirylics/x-gwt
x-gwt-polymer/src/main/java/com/github/spirylics/xgwt/polymer/Dialog.java
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Error.java // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public interface Error { // @JsProperty // String getCode(); // // @JsProperty // String getMessage(); // } // // Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Fn.java // public abstract class Fn { // private Fn() { // } // // @JsFunction // public interface NoArg { // void e(); // } // // @JsFunction // public interface Arg<A> { // void e(A arg); // } // // @JsFunction // public interface ArgRet<A, R> { // R e(A arg); // } // // @JsFunction // public interface Args { // void e(Object... args); // } // // @JsFunction // public interface Resolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // // @JsFunction // public interface OpenResolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // } // // Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Promise.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public class Promise<S, E> extends Thenable<S, E> { // // @JsConstructor // public Promise(Fn.Resolver<S, E> resolver) { // } // // public static native <A, B> Promise<A, B> all(Promise<?, ?>[] promises); // // public static native <S> Promise<S, Error> resolve(S success); // // private Fn.Arg<S> resolve; // private Fn.Arg<E> reject; // // @JsOverlay // public final Promise<S, E> openResolve(S success) { // if (resolve == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // resolve.e(success); // return this; // } // // @JsOverlay // public final Promise<S, E> openReject(E error) { // if (reject == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // reject.e(error); // return this; // } // // @JsOverlay // public static <S, E> Promise<S, E> buildOpenPromise() { // final Map<String, Fn.Arg<?>> containers = new HashMap<>(2); // Fn.Resolver<S, E> resolver = new Fn.Resolver<S, E>() { // @Override // public void e(Fn.Arg<S> resolve, Fn.Arg<E> reject) { // containers.put("resolve", resolve); // containers.put("reject", reject); // } // }; // Promise<S, E> openPromise = new Promise<S, E>(resolver); // openPromise.resolve = (Fn.Arg<S>) containers.get("resolve"); // openPromise.reject = (Fn.Arg<E>) containers.get("reject"); // return openPromise; // } // }
import com.github.spirylics.xgwt.essential.Error; import com.github.spirylics.xgwt.essential.Fn; import com.github.spirylics.xgwt.essential.Promise; import com.google.common.base.Strings; import com.google.gwt.core.client.Scheduler; import com.google.gwt.event.logical.shared.*; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.History; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import java.util.function.Predicate;
String getDialogParameter() { if (Strings.isNullOrEmpty(dialogParameter)) { throw new IllegalStateException("no history token defined!"); } return dialogParameter; } boolean hasHistoryDialogParameter(String historyToken) { return Strings.nullToEmpty(historyToken).contains(getDialogParameter()); } Dialog addDialogParameter() { Scheduler.get().scheduleDeferred(() -> { if (!hasHistoryDialogParameter(History.getToken())) { History.newItem(History.getToken() + (Strings.isNullOrEmpty(History.getToken()) ? "#" : ";") + getDialogParameter(), true); } }); return this; } void removeDialogParameter() { Scheduler.get().scheduleDeferred(() -> { if (hasHistoryDialogParameter(History.getToken())) { History.back(); } }); }
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Error.java // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public interface Error { // @JsProperty // String getCode(); // // @JsProperty // String getMessage(); // } // // Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Fn.java // public abstract class Fn { // private Fn() { // } // // @JsFunction // public interface NoArg { // void e(); // } // // @JsFunction // public interface Arg<A> { // void e(A arg); // } // // @JsFunction // public interface ArgRet<A, R> { // R e(A arg); // } // // @JsFunction // public interface Args { // void e(Object... args); // } // // @JsFunction // public interface Resolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // // @JsFunction // public interface OpenResolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // } // // Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Promise.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public class Promise<S, E> extends Thenable<S, E> { // // @JsConstructor // public Promise(Fn.Resolver<S, E> resolver) { // } // // public static native <A, B> Promise<A, B> all(Promise<?, ?>[] promises); // // public static native <S> Promise<S, Error> resolve(S success); // // private Fn.Arg<S> resolve; // private Fn.Arg<E> reject; // // @JsOverlay // public final Promise<S, E> openResolve(S success) { // if (resolve == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // resolve.e(success); // return this; // } // // @JsOverlay // public final Promise<S, E> openReject(E error) { // if (reject == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // reject.e(error); // return this; // } // // @JsOverlay // public static <S, E> Promise<S, E> buildOpenPromise() { // final Map<String, Fn.Arg<?>> containers = new HashMap<>(2); // Fn.Resolver<S, E> resolver = new Fn.Resolver<S, E>() { // @Override // public void e(Fn.Arg<S> resolve, Fn.Arg<E> reject) { // containers.put("resolve", resolve); // containers.put("reject", reject); // } // }; // Promise<S, E> openPromise = new Promise<S, E>(resolver); // openPromise.resolve = (Fn.Arg<S>) containers.get("resolve"); // openPromise.reject = (Fn.Arg<E>) containers.get("reject"); // return openPromise; // } // } // Path: x-gwt-polymer/src/main/java/com/github/spirylics/xgwt/polymer/Dialog.java import com.github.spirylics.xgwt.essential.Error; import com.github.spirylics.xgwt.essential.Fn; import com.github.spirylics.xgwt.essential.Promise; import com.google.common.base.Strings; import com.google.gwt.core.client.Scheduler; import com.google.gwt.event.logical.shared.*; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.History; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import java.util.function.Predicate; String getDialogParameter() { if (Strings.isNullOrEmpty(dialogParameter)) { throw new IllegalStateException("no history token defined!"); } return dialogParameter; } boolean hasHistoryDialogParameter(String historyToken) { return Strings.nullToEmpty(historyToken).contains(getDialogParameter()); } Dialog addDialogParameter() { Scheduler.get().scheduleDeferred(() -> { if (!hasHistoryDialogParameter(History.getToken())) { History.newItem(History.getToken() + (Strings.isNullOrEmpty(History.getToken()) ? "#" : ";") + getDialogParameter(), true); } }); return this; } void removeDialogParameter() { Scheduler.get().scheduleDeferred(() -> { if (hasHistoryDialogParameter(History.getToken())) { History.back(); } }); }
Promise<Boolean, Error> overlay(final boolean opened) {
spirylics/x-gwt
x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/database/DataSnapshot.java
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Fn.java // public abstract class Fn { // private Fn() { // } // // @JsFunction // public interface NoArg { // void e(); // } // // @JsFunction // public interface Arg<A> { // void e(A arg); // } // // @JsFunction // public interface ArgRet<A, R> { // R e(A arg); // } // // @JsFunction // public interface Args { // void e(Object... args); // } // // @JsFunction // public interface Resolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // // @JsFunction // public interface OpenResolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // }
import com.github.spirylics.xgwt.essential.Fn; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType;
package com.github.spirylics.xgwt.firebase.database; @SuppressWarnings("ALL") @JsType(isNative = true, namespace = "firebase.database", name = "DataSnapshot") public interface DataSnapshot<V> { <C> DataSnapshot<C> child(String path); boolean exists(); @JsProperty String getKey(); V val();
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Fn.java // public abstract class Fn { // private Fn() { // } // // @JsFunction // public interface NoArg { // void e(); // } // // @JsFunction // public interface Arg<A> { // void e(A arg); // } // // @JsFunction // public interface ArgRet<A, R> { // R e(A arg); // } // // @JsFunction // public interface Args { // void e(Object... args); // } // // @JsFunction // public interface Resolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // // @JsFunction // public interface OpenResolver<S, E> { // void e(Fn.Arg<S> resolve, Fn.Arg<E> reject); // } // } // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/database/DataSnapshot.java import com.github.spirylics.xgwt.essential.Fn; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; package com.github.spirylics.xgwt.firebase.database; @SuppressWarnings("ALL") @JsType(isNative = true, namespace = "firebase.database", name = "DataSnapshot") public interface DataSnapshot<V> { <C> DataSnapshot<C> child(String path); boolean exists(); @JsProperty String getKey(); V val();
<X> boolean forEach(Fn.Arg<DataSnapshot<X>> fn);
spirylics/x-gwt
x-gwt-polymer/src/main/java/com/github/spirylics/xgwt/polymer/DomApi.java
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Element.java // @JsType(isNative = true) // public interface Element { // // @JsOverlay // static <E extends Element> E create(String tag) { // return (E) DOM.createElement(tag); // } // // @JsOverlay // static <E extends Element> E create(String tag, Map<String, Object> attributes) { // return (E) GQuery.$("<" + tag + " " // + attributes.entrySet().stream() // .map(e -> e.getKey() + "=\"" + XMapper.get().write(e.getValue()) + "\"") // .collect(Collectors.joining(" ")) // + "></" + tag + ">").get(0); // } // // void addEventListener(String event, Fn.Arg<Event> function, boolean useCapture); // // void addEventListener(String event, Fn.Arg<Event> function); // // void removeEventListener(String event, Fn.Arg<Event> function, boolean useCapture); // // void removeEventListener(String event, Fn.Arg<Event> function); // // String getAttribute(String attribute); // // void setAttribute(String attribute, Object value); // // void removeAttribute(String attribute); // // <E extends Element> E querySelector(String selector); // // <E extends Element> E[] querySelectorAll(String selector); // // void focus(); // // void blur(); // // void appendChild(Element element); // // @JsOverlay // default <E extends Element> Stream<E> querySelectorStream(String selector) { // return Arrays.stream(querySelectorAll(selector)); // } // // @JsOverlay // default void appendChild(Widget widget) { // appendChild((Element) widget.getElement()); // } // // // @JsOverlay // default <E extends Element> E focus(boolean focused) { // if (focused) { // focus(); // } else { // blur(); // } // return (E) this; // } // // @JsOverlay // default <E extends Element> E hidden(boolean hidden) { // return attribute("hidden", hidden); // } // // @JsOverlay // default <E extends Element> E attribute(String attribute, Object value) { // if (value == null || Boolean.FALSE.equals(value)) { // removeAttribute(attribute); // } else { // setAttribute(attribute, XMapper.get().write(value)); // } // return (E) this; // } // // @JsOverlay // default <V> V attribute(String attribute, Class<V> clazz) { // return XMapper.get().read(getAttribute(attribute), clazz); // } // // }
import com.github.spirylics.xgwt.essential.Element; import com.google.gwt.user.client.ui.Widget; import jsinterop.annotations.JsOverlay; import jsinterop.annotations.JsType;
package com.github.spirylics.xgwt.polymer; @JsType(isNative = true) public interface DomApi extends Dom {
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Element.java // @JsType(isNative = true) // public interface Element { // // @JsOverlay // static <E extends Element> E create(String tag) { // return (E) DOM.createElement(tag); // } // // @JsOverlay // static <E extends Element> E create(String tag, Map<String, Object> attributes) { // return (E) GQuery.$("<" + tag + " " // + attributes.entrySet().stream() // .map(e -> e.getKey() + "=\"" + XMapper.get().write(e.getValue()) + "\"") // .collect(Collectors.joining(" ")) // + "></" + tag + ">").get(0); // } // // void addEventListener(String event, Fn.Arg<Event> function, boolean useCapture); // // void addEventListener(String event, Fn.Arg<Event> function); // // void removeEventListener(String event, Fn.Arg<Event> function, boolean useCapture); // // void removeEventListener(String event, Fn.Arg<Event> function); // // String getAttribute(String attribute); // // void setAttribute(String attribute, Object value); // // void removeAttribute(String attribute); // // <E extends Element> E querySelector(String selector); // // <E extends Element> E[] querySelectorAll(String selector); // // void focus(); // // void blur(); // // void appendChild(Element element); // // @JsOverlay // default <E extends Element> Stream<E> querySelectorStream(String selector) { // return Arrays.stream(querySelectorAll(selector)); // } // // @JsOverlay // default void appendChild(Widget widget) { // appendChild((Element) widget.getElement()); // } // // // @JsOverlay // default <E extends Element> E focus(boolean focused) { // if (focused) { // focus(); // } else { // blur(); // } // return (E) this; // } // // @JsOverlay // default <E extends Element> E hidden(boolean hidden) { // return attribute("hidden", hidden); // } // // @JsOverlay // default <E extends Element> E attribute(String attribute, Object value) { // if (value == null || Boolean.FALSE.equals(value)) { // removeAttribute(attribute); // } else { // setAttribute(attribute, XMapper.get().write(value)); // } // return (E) this; // } // // @JsOverlay // default <V> V attribute(String attribute, Class<V> clazz) { // return XMapper.get().read(getAttribute(attribute), clazz); // } // // } // Path: x-gwt-polymer/src/main/java/com/github/spirylics/xgwt/polymer/DomApi.java import com.github.spirylics.xgwt.essential.Element; import com.google.gwt.user.client.ui.Widget; import jsinterop.annotations.JsOverlay; import jsinterop.annotations.JsType; package com.github.spirylics.xgwt.polymer; @JsType(isNative = true) public interface DomApi extends Dom {
<E extends Element> E[] getEffectiveChildNodes();
spirylics/x-gwt
x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/Firebase.java
// Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/auth/Auth.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = "firebase.auth", name = "Auth") // public class Auth { // // public native Promise<Void, Error> applyActionCode(String code); // // public native Promise<ActionCodeInfo, Error> checkActionCode(String code); // // public native Promise<Void, Error> confirmPasswordReset(String code, String newPassword); // // public native Promise<UserCredential, Error> signInWithPopup(AuthProvider authProvider); // // public native Promise<User, Error> signInWithEmailAndPassword(String email, String password); // // public native Promise<User, Error> signInAnonymously(); // // public native Promise<Void, Error> signOut(); // // public native Promise<User, Error> createUserWithEmailAndPassword(String email, String password); // // public native Promise<String[], Error> fetchProvidersForEmail(String email); // // public native Promise<Void, Error> sendPasswordResetEmail(String email); // // public native Promise<User, Error> signInWithCredential(AuthCredential authCredential); // // public native Promise<User, Error> signInWithCustomToken(String token); // // public native Promise<Void, Error> signInWithRedirect(AuthProvider authProvider); // // public native Promise<String, Error> verifyPasswordResetCode(String code); // // // @JsProperty // public native User getCurrentUser(); // // public native Fn.NoArg onAuthStateChanged(Fn.Arg<User> fn); // // @JsOverlay // public final boolean isAuth() { // return getCurrentUser() != null; // } // // @JsOverlay // public final AuthRegistration handleAuth(final Fn.Arg<User> fn) { // return new AuthRegistration(this, fn); // } // } // // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/database/Database.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = "firebase.database", name = "Database") // public interface Database { // // Reference ref(); // // Reference ref(String path); // // }
import com.github.spirylics.xgwt.firebase.auth.Auth; import com.github.spirylics.xgwt.firebase.database.Database; import jsinterop.annotations.JsMethod; import jsinterop.annotations.JsType; import static jsinterop.annotations.JsPackage.GLOBAL;
package com.github.spirylics.xgwt.firebase; @SuppressWarnings("ALL") @JsType(isNative = true, namespace = "firebase.app", name = "App") public class Firebase { @JsMethod(namespace = "firebase") public static native Firebase initializeApp(Config config);
// Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/auth/Auth.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = "firebase.auth", name = "Auth") // public class Auth { // // public native Promise<Void, Error> applyActionCode(String code); // // public native Promise<ActionCodeInfo, Error> checkActionCode(String code); // // public native Promise<Void, Error> confirmPasswordReset(String code, String newPassword); // // public native Promise<UserCredential, Error> signInWithPopup(AuthProvider authProvider); // // public native Promise<User, Error> signInWithEmailAndPassword(String email, String password); // // public native Promise<User, Error> signInAnonymously(); // // public native Promise<Void, Error> signOut(); // // public native Promise<User, Error> createUserWithEmailAndPassword(String email, String password); // // public native Promise<String[], Error> fetchProvidersForEmail(String email); // // public native Promise<Void, Error> sendPasswordResetEmail(String email); // // public native Promise<User, Error> signInWithCredential(AuthCredential authCredential); // // public native Promise<User, Error> signInWithCustomToken(String token); // // public native Promise<Void, Error> signInWithRedirect(AuthProvider authProvider); // // public native Promise<String, Error> verifyPasswordResetCode(String code); // // // @JsProperty // public native User getCurrentUser(); // // public native Fn.NoArg onAuthStateChanged(Fn.Arg<User> fn); // // @JsOverlay // public final boolean isAuth() { // return getCurrentUser() != null; // } // // @JsOverlay // public final AuthRegistration handleAuth(final Fn.Arg<User> fn) { // return new AuthRegistration(this, fn); // } // } // // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/database/Database.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = "firebase.database", name = "Database") // public interface Database { // // Reference ref(); // // Reference ref(String path); // // } // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/Firebase.java import com.github.spirylics.xgwt.firebase.auth.Auth; import com.github.spirylics.xgwt.firebase.database.Database; import jsinterop.annotations.JsMethod; import jsinterop.annotations.JsType; import static jsinterop.annotations.JsPackage.GLOBAL; package com.github.spirylics.xgwt.firebase; @SuppressWarnings("ALL") @JsType(isNative = true, namespace = "firebase.app", name = "App") public class Firebase { @JsMethod(namespace = "firebase") public static native Firebase initializeApp(Config config);
public native Auth auth();
spirylics/x-gwt
x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/Firebase.java
// Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/auth/Auth.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = "firebase.auth", name = "Auth") // public class Auth { // // public native Promise<Void, Error> applyActionCode(String code); // // public native Promise<ActionCodeInfo, Error> checkActionCode(String code); // // public native Promise<Void, Error> confirmPasswordReset(String code, String newPassword); // // public native Promise<UserCredential, Error> signInWithPopup(AuthProvider authProvider); // // public native Promise<User, Error> signInWithEmailAndPassword(String email, String password); // // public native Promise<User, Error> signInAnonymously(); // // public native Promise<Void, Error> signOut(); // // public native Promise<User, Error> createUserWithEmailAndPassword(String email, String password); // // public native Promise<String[], Error> fetchProvidersForEmail(String email); // // public native Promise<Void, Error> sendPasswordResetEmail(String email); // // public native Promise<User, Error> signInWithCredential(AuthCredential authCredential); // // public native Promise<User, Error> signInWithCustomToken(String token); // // public native Promise<Void, Error> signInWithRedirect(AuthProvider authProvider); // // public native Promise<String, Error> verifyPasswordResetCode(String code); // // // @JsProperty // public native User getCurrentUser(); // // public native Fn.NoArg onAuthStateChanged(Fn.Arg<User> fn); // // @JsOverlay // public final boolean isAuth() { // return getCurrentUser() != null; // } // // @JsOverlay // public final AuthRegistration handleAuth(final Fn.Arg<User> fn) { // return new AuthRegistration(this, fn); // } // } // // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/database/Database.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = "firebase.database", name = "Database") // public interface Database { // // Reference ref(); // // Reference ref(String path); // // }
import com.github.spirylics.xgwt.firebase.auth.Auth; import com.github.spirylics.xgwt.firebase.database.Database; import jsinterop.annotations.JsMethod; import jsinterop.annotations.JsType; import static jsinterop.annotations.JsPackage.GLOBAL;
package com.github.spirylics.xgwt.firebase; @SuppressWarnings("ALL") @JsType(isNative = true, namespace = "firebase.app", name = "App") public class Firebase { @JsMethod(namespace = "firebase") public static native Firebase initializeApp(Config config); public native Auth auth();
// Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/auth/Auth.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = "firebase.auth", name = "Auth") // public class Auth { // // public native Promise<Void, Error> applyActionCode(String code); // // public native Promise<ActionCodeInfo, Error> checkActionCode(String code); // // public native Promise<Void, Error> confirmPasswordReset(String code, String newPassword); // // public native Promise<UserCredential, Error> signInWithPopup(AuthProvider authProvider); // // public native Promise<User, Error> signInWithEmailAndPassword(String email, String password); // // public native Promise<User, Error> signInAnonymously(); // // public native Promise<Void, Error> signOut(); // // public native Promise<User, Error> createUserWithEmailAndPassword(String email, String password); // // public native Promise<String[], Error> fetchProvidersForEmail(String email); // // public native Promise<Void, Error> sendPasswordResetEmail(String email); // // public native Promise<User, Error> signInWithCredential(AuthCredential authCredential); // // public native Promise<User, Error> signInWithCustomToken(String token); // // public native Promise<Void, Error> signInWithRedirect(AuthProvider authProvider); // // public native Promise<String, Error> verifyPasswordResetCode(String code); // // // @JsProperty // public native User getCurrentUser(); // // public native Fn.NoArg onAuthStateChanged(Fn.Arg<User> fn); // // @JsOverlay // public final boolean isAuth() { // return getCurrentUser() != null; // } // // @JsOverlay // public final AuthRegistration handleAuth(final Fn.Arg<User> fn) { // return new AuthRegistration(this, fn); // } // } // // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/database/Database.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = "firebase.database", name = "Database") // public interface Database { // // Reference ref(); // // Reference ref(String path); // // } // Path: x-gwt-firebase/src/main/java/com/github/spirylics/xgwt/firebase/Firebase.java import com.github.spirylics.xgwt.firebase.auth.Auth; import com.github.spirylics.xgwt.firebase.database.Database; import jsinterop.annotations.JsMethod; import jsinterop.annotations.JsType; import static jsinterop.annotations.JsPackage.GLOBAL; package com.github.spirylics.xgwt.firebase; @SuppressWarnings("ALL") @JsType(isNative = true, namespace = "firebase.app", name = "App") public class Firebase { @JsMethod(namespace = "firebase") public static native Firebase initializeApp(Config config); public native Auth auth();
public native Database database();
spirylics/x-gwt
x-gwt-cordova/src/main/java/com/github/spirylics/xgwt/cordova/XCordova.java
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Promise.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public class Promise<S, E> extends Thenable<S, E> { // // @JsConstructor // public Promise(Fn.Resolver<S, E> resolver) { // } // // public static native <A, B> Promise<A, B> all(Promise<?, ?>[] promises); // // public static native <S> Promise<S, Error> resolve(S success); // // private Fn.Arg<S> resolve; // private Fn.Arg<E> reject; // // @JsOverlay // public final Promise<S, E> openResolve(S success) { // if (resolve == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // resolve.e(success); // return this; // } // // @JsOverlay // public final Promise<S, E> openReject(E error) { // if (reject == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // reject.e(error); // return this; // } // // @JsOverlay // public static <S, E> Promise<S, E> buildOpenPromise() { // final Map<String, Fn.Arg<?>> containers = new HashMap<>(2); // Fn.Resolver<S, E> resolver = new Fn.Resolver<S, E>() { // @Override // public void e(Fn.Arg<S> resolve, Fn.Arg<E> reject) { // containers.put("resolve", resolve); // containers.put("reject", reject); // } // }; // Promise<S, E> openPromise = new Promise<S, E>(resolver); // openPromise.resolve = (Fn.Arg<S>) containers.get("resolve"); // openPromise.reject = (Fn.Arg<E>) containers.get("reject"); // return openPromise; // } // }
import com.github.spirylics.xgwt.essential.Promise; import com.google.gwt.core.client.GWT; import com.google.gwt.query.client.js.JsUtils; import com.google.gwt.user.client.Window; import com.googlecode.gwtphonegap.client.*; import com.googlecode.gwtphonegap.client.device.Device; import com.googlecode.gwtphonegap.client.geolocation.GeolocationCallback; import com.googlecode.gwtphonegap.client.geolocation.GeolocationOptions;
package com.github.spirylics.xgwt.cordova; public class XCordova { final PhoneGap phoneGap; final GeolocationOptions geolocationOptions; GeolocationCancelableCallback singleGeolocationCallback; boolean networkIndicationShow; public XCordova() { this(GWT.create(PhoneGap.class)); } public XCordova(PhoneGap phoneGap) { this.phoneGap = phoneGap; this.geolocationOptions = new GeolocationOptions(); this.geolocationOptions.setTimeout(5000); this.geolocationOptions.setEnableHighAccuracy(true); this.geolocationOptions.setMaximumAge(60000); }
// Path: x-gwt-essential/src/main/java/com/github/spirylics/xgwt/essential/Promise.java // @SuppressWarnings("ALL") // @JsType(isNative = true, namespace = JsPackage.GLOBAL) // public class Promise<S, E> extends Thenable<S, E> { // // @JsConstructor // public Promise(Fn.Resolver<S, E> resolver) { // } // // public static native <A, B> Promise<A, B> all(Promise<?, ?>[] promises); // // public static native <S> Promise<S, Error> resolve(S success); // // private Fn.Arg<S> resolve; // private Fn.Arg<E> reject; // // @JsOverlay // public final Promise<S, E> openResolve(S success) { // if (resolve == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // resolve.e(success); // return this; // } // // @JsOverlay // public final Promise<S, E> openReject(E error) { // if (reject == null) { // throw new UnsupportedOperationException("promise is not open, use buildOpenPromise"); // } // reject.e(error); // return this; // } // // @JsOverlay // public static <S, E> Promise<S, E> buildOpenPromise() { // final Map<String, Fn.Arg<?>> containers = new HashMap<>(2); // Fn.Resolver<S, E> resolver = new Fn.Resolver<S, E>() { // @Override // public void e(Fn.Arg<S> resolve, Fn.Arg<E> reject) { // containers.put("resolve", resolve); // containers.put("reject", reject); // } // }; // Promise<S, E> openPromise = new Promise<S, E>(resolver); // openPromise.resolve = (Fn.Arg<S>) containers.get("resolve"); // openPromise.reject = (Fn.Arg<E>) containers.get("reject"); // return openPromise; // } // } // Path: x-gwt-cordova/src/main/java/com/github/spirylics/xgwt/cordova/XCordova.java import com.github.spirylics.xgwt.essential.Promise; import com.google.gwt.core.client.GWT; import com.google.gwt.query.client.js.JsUtils; import com.google.gwt.user.client.Window; import com.googlecode.gwtphonegap.client.*; import com.googlecode.gwtphonegap.client.device.Device; import com.googlecode.gwtphonegap.client.geolocation.GeolocationCallback; import com.googlecode.gwtphonegap.client.geolocation.GeolocationOptions; package com.github.spirylics.xgwt.cordova; public class XCordova { final PhoneGap phoneGap; final GeolocationOptions geolocationOptions; GeolocationCancelableCallback singleGeolocationCallback; boolean networkIndicationShow; public XCordova() { this(GWT.create(PhoneGap.class)); } public XCordova(PhoneGap phoneGap) { this.phoneGap = phoneGap; this.geolocationOptions = new GeolocationOptions(); this.geolocationOptions.setTimeout(5000); this.geolocationOptions.setEnableHighAccuracy(true); this.geolocationOptions.setMaximumAge(60000); }
public XCordova initialize(final Promise<Void, Object> promise) {
OpenTreeMap/otm-android
OpenTreeMap/src/main/java/org/azavea/otm/ui/TreeDisplay.java
// Path: OpenTreeMap/src/main/java/org/azavea/helpers/GoogleMapsListeners.java // public class GoogleMapsListeners { // // We need to set a listener for marker drag, or markers will not give the correct position // // when we later call marker.getPosition() // // Note that we do not have to actually *do* anything in our listener // public static class NoopDragListener implements GoogleMap.OnMarkerDragListener { // // @Override // public void onMarkerDragStart(Marker marker) { // // } // // @Override // public void onMarkerDrag(Marker marker) { // // } // // @Override // public void onMarkerDragEnd(Marker marker) { // // } // } // }
import android.app.Activity; import android.app.FragmentManager; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.UiSettings; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import org.azavea.helpers.GoogleMapsListeners; import org.azavea.helpers.Logger; import org.azavea.otm.R; import org.azavea.otm.data.Geometry; import org.azavea.otm.data.Plot; import org.json.JSONException; import org.json.JSONObject;
if (map != null) { mMap = map; setUpMap(); } else { Log.e("VIN", "map was null."); } }); } } protected void onMapLoad(OnMapReadyCallback cb) { if (mMap != null) { cb.onMapReady(mMap); } // Try to obtain the map from the MapFragment. // we have to try for 2 different fragment id's, using the reasonable // assumption that the base classes are going to be instantiated one // at a time. FragmentManager fragmentManager = getFragmentManager(); MapFragment fragment = (MapFragment) fragmentManager.findFragmentById(mapFragmentId); fragment.getMapAsync(cb); } private void setUpMap() { UiSettings mUiSettings = mMap.getUiSettings(); mUiSettings.setZoomControlsEnabled(false); mUiSettings.setScrollGesturesEnabled(false); mUiSettings.setZoomGesturesEnabled(false); mUiSettings.setTiltGesturesEnabled(false); mUiSettings.setRotateGesturesEnabled(false);
// Path: OpenTreeMap/src/main/java/org/azavea/helpers/GoogleMapsListeners.java // public class GoogleMapsListeners { // // We need to set a listener for marker drag, or markers will not give the correct position // // when we later call marker.getPosition() // // Note that we do not have to actually *do* anything in our listener // public static class NoopDragListener implements GoogleMap.OnMarkerDragListener { // // @Override // public void onMarkerDragStart(Marker marker) { // // } // // @Override // public void onMarkerDrag(Marker marker) { // // } // // @Override // public void onMarkerDragEnd(Marker marker) { // // } // } // } // Path: OpenTreeMap/src/main/java/org/azavea/otm/ui/TreeDisplay.java import android.app.Activity; import android.app.FragmentManager; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.UiSettings; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import org.azavea.helpers.GoogleMapsListeners; import org.azavea.helpers.Logger; import org.azavea.otm.R; import org.azavea.otm.data.Geometry; import org.azavea.otm.data.Plot; import org.json.JSONException; import org.json.JSONObject; if (map != null) { mMap = map; setUpMap(); } else { Log.e("VIN", "map was null."); } }); } } protected void onMapLoad(OnMapReadyCallback cb) { if (mMap != null) { cb.onMapReady(mMap); } // Try to obtain the map from the MapFragment. // we have to try for 2 different fragment id's, using the reasonable // assumption that the base classes are going to be instantiated one // at a time. FragmentManager fragmentManager = getFragmentManager(); MapFragment fragment = (MapFragment) fragmentManager.findFragmentById(mapFragmentId); fragment.getMapAsync(cb); } private void setUpMap() { UiSettings mUiSettings = mMap.getUiSettings(); mUiSettings.setZoomControlsEnabled(false); mUiSettings.setScrollGesturesEnabled(false); mUiSettings.setZoomGesturesEnabled(false); mUiSettings.setTiltGesturesEnabled(false); mUiSettings.setRotateGesturesEnabled(false);
mMap.setOnMarkerDragListener(new GoogleMapsListeners.NoopDragListener());
Bombe/jFCPlib
src/main/java/net/pterodactylus/fcp/ClientPutComplexDir.java
// Path: src/main/java/net/pterodactylus/fcp/FileEntry.java // static class DirectFileEntry extends FileEntry { // // /** The content type of the data. */ // private final String contentType; // // /** The length of the data. */ // private final long length; // // /** The input stream of the data. */ // private final InputStream inputStream; // // /** // * Creates a new direct file entry with content type auto-detection. // * // * @param name // * The name of the file // * @param length // * The length of the file // * @param inputStream // * The input stream of the file // */ // public DirectFileEntry(String name, long length, InputStream inputStream) { // this(name, null, length, inputStream); // } // // /** // * Creates a new direct file entry. // * // * @param name // * The name of the file // * @param contentType // * The content type of the file, or <code>null</code> to let // * the node auto-detect it // * @param length // * The length of the file // * @param inputStream // * The input stream of the file // */ // public DirectFileEntry(String name, String contentType, long length, InputStream inputStream) { // super(name, UploadFrom.direct); // this.contentType = contentType; // this.length = length; // this.inputStream = inputStream; // } // // /** // * {@inheritDoc} // */ // @Override // Map<String, String> getFields() { // Map<String, String> fields = new HashMap<String, String>(); // fields.put("Name", name); // fields.put("UploadFrom", String.valueOf(uploadFrom)); // fields.put("DataLength", String.valueOf(length)); // if (contentType != null) { // fields.put("Metadata.ContentType", contentType); // } // return fields; // } // // /** // * Returns the input stream of the file. // * // * @return The input stream of the file // */ // InputStream getInputStream() { // return inputStream; // } // // }
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.SequenceInputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.pterodactylus.fcp.FileEntry.DirectFileEntry;
* <code>true</code> to encode the complete data early, * <code>false</code> otherwise */ public void setEarlyEncode(boolean earlyEncode) { setField("EarlyEncode", String.valueOf(earlyEncode)); } /** * Sets the default name. This is the name of the file that should be shown * if no file was specified. * * @param defaultName * The default name */ public void setDefaultName(String defaultName) { setField("DefaultName", defaultName); } /** * Adds an entry for a file. * * @param fileEntry * The file entry to add */ public void addFileEntry(FileEntry fileEntry) { Map<String, String> fields = fileEntry.getFields(); for (Entry<String, String> fieldEntry : fields.entrySet()) { setField("Files." + fileIndex + "." + fieldEntry.getKey(), fieldEntry.getValue()); } fileIndex++;
// Path: src/main/java/net/pterodactylus/fcp/FileEntry.java // static class DirectFileEntry extends FileEntry { // // /** The content type of the data. */ // private final String contentType; // // /** The length of the data. */ // private final long length; // // /** The input stream of the data. */ // private final InputStream inputStream; // // /** // * Creates a new direct file entry with content type auto-detection. // * // * @param name // * The name of the file // * @param length // * The length of the file // * @param inputStream // * The input stream of the file // */ // public DirectFileEntry(String name, long length, InputStream inputStream) { // this(name, null, length, inputStream); // } // // /** // * Creates a new direct file entry. // * // * @param name // * The name of the file // * @param contentType // * The content type of the file, or <code>null</code> to let // * the node auto-detect it // * @param length // * The length of the file // * @param inputStream // * The input stream of the file // */ // public DirectFileEntry(String name, String contentType, long length, InputStream inputStream) { // super(name, UploadFrom.direct); // this.contentType = contentType; // this.length = length; // this.inputStream = inputStream; // } // // /** // * {@inheritDoc} // */ // @Override // Map<String, String> getFields() { // Map<String, String> fields = new HashMap<String, String>(); // fields.put("Name", name); // fields.put("UploadFrom", String.valueOf(uploadFrom)); // fields.put("DataLength", String.valueOf(length)); // if (contentType != null) { // fields.put("Metadata.ContentType", contentType); // } // return fields; // } // // /** // * Returns the input stream of the file. // * // * @return The input stream of the file // */ // InputStream getInputStream() { // return inputStream; // } // // } // Path: src/main/java/net/pterodactylus/fcp/ClientPutComplexDir.java import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.SequenceInputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.pterodactylus.fcp.FileEntry.DirectFileEntry; * <code>true</code> to encode the complete data early, * <code>false</code> otherwise */ public void setEarlyEncode(boolean earlyEncode) { setField("EarlyEncode", String.valueOf(earlyEncode)); } /** * Sets the default name. This is the name of the file that should be shown * if no file was specified. * * @param defaultName * The default name */ public void setDefaultName(String defaultName) { setField("DefaultName", defaultName); } /** * Adds an entry for a file. * * @param fileEntry * The file entry to add */ public void addFileEntry(FileEntry fileEntry) { Map<String, String> fields = fileEntry.getFields(); for (Entry<String, String> fieldEntry : fields.entrySet()) { setField("Files." + fileIndex + "." + fieldEntry.getKey(), fieldEntry.getValue()); } fileIndex++;
if (fileEntry instanceof FileEntry.DirectFileEntry) {
actions-on-google/smart-home-dashboard
src/main/java/com/google/homegraph/dashboard/controller/UploadController.java
// Path: src/main/java/com/google/homegraph/dashboard/service/StorageService.java // @Service // @Scope(value="session") // public class StorageService implements Serializable{ // // private static final long serialVersionUID = 1L; // private static Logger log = LoggerFactory.getLogger("StorageService"); // private static StorageService instance; // // private Map<String, byte[]> inMemoryStore = new HashMap<>(); // // private StorageService() {} // // public static StorageService getInstance() { // if (instance == null) { // instance = new StorageService(); // } // return instance; // } // // public void storeInMemory(MultipartFile file) { // try { // inMemoryStore.put(file.getOriginalFilename(), convert(file)); // } catch (IOException e) { // log.error(e.getMessage() + ", Failed to convert the file and store in memory, will try disk instead"); // } // } // // public InputStream loadFile(String filename) { // // check if it is in memory // log.debug("Storing file: " + filename); // if (inMemoryStore.containsKey(filename)) { // log.debug("Found file in memory"); // return new ByteArrayInputStream(inMemoryStore.get(filename)); // } else { // log.debug("File is not in memory"); // return null; // } // } // // private byte[] convert(MultipartFile file) throws IOException { // InputStream is = file.getInputStream(); // ByteArrayOutputStream buffer = new ByteArrayOutputStream(); // // int nRead; // byte[] data = new byte[16384]; // while ((nRead = is.read(data, 0, data.length)) != -1) { // buffer.write(data, 0, nRead); // } // // buffer.flush(); // return buffer.toByteArray(); // } // }
import com.google.homegraph.dashboard.service.StorageService; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile;
/** * Copyright 2018 Google Inc. 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 com.google.homegraph.dashboard.controller; @Controller @Scope(value="session") public class UploadController implements Serializable { private static final long serialVersionUID = 5546148932202075489L; private static Logger log = LoggerFactory.getLogger("UploadController"); @PostMapping("/upload") @CrossOrigin public ResponseEntity<String> handleFileUpload(@RequestParam("file") final MultipartFile file) {
// Path: src/main/java/com/google/homegraph/dashboard/service/StorageService.java // @Service // @Scope(value="session") // public class StorageService implements Serializable{ // // private static final long serialVersionUID = 1L; // private static Logger log = LoggerFactory.getLogger("StorageService"); // private static StorageService instance; // // private Map<String, byte[]> inMemoryStore = new HashMap<>(); // // private StorageService() {} // // public static StorageService getInstance() { // if (instance == null) { // instance = new StorageService(); // } // return instance; // } // // public void storeInMemory(MultipartFile file) { // try { // inMemoryStore.put(file.getOriginalFilename(), convert(file)); // } catch (IOException e) { // log.error(e.getMessage() + ", Failed to convert the file and store in memory, will try disk instead"); // } // } // // public InputStream loadFile(String filename) { // // check if it is in memory // log.debug("Storing file: " + filename); // if (inMemoryStore.containsKey(filename)) { // log.debug("Found file in memory"); // return new ByteArrayInputStream(inMemoryStore.get(filename)); // } else { // log.debug("File is not in memory"); // return null; // } // } // // private byte[] convert(MultipartFile file) throws IOException { // InputStream is = file.getInputStream(); // ByteArrayOutputStream buffer = new ByteArrayOutputStream(); // // int nRead; // byte[] data = new byte[16384]; // while ((nRead = is.read(data, 0, data.length)) != -1) { // buffer.write(data, 0, nRead); // } // // buffer.flush(); // return buffer.toByteArray(); // } // } // Path: src/main/java/com/google/homegraph/dashboard/controller/UploadController.java import com.google.homegraph.dashboard.service.StorageService; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; /** * Copyright 2018 Google Inc. 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 com.google.homegraph.dashboard.controller; @Controller @Scope(value="session") public class UploadController implements Serializable { private static final long serialVersionUID = 5546148932202075489L; private static Logger log = LoggerFactory.getLogger("UploadController"); @PostMapping("/upload") @CrossOrigin public ResponseEntity<String> handleFileUpload(@RequestParam("file") final MultipartFile file) {
StorageService storageService = StorageService.getInstance();
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/AdapterTaskIT.java
// Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher initialPollRequest(String messageId, String collection) { // return new PollRequestMatcher(messageId, collection, null); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher nextPollRequest(String messageId, String collection, String begin) { // return new PollRequestMatcher(messageId, collection, begin); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HasHeaderMatcher.java // public static Matcher<HttpHeaders> hasAllTaxiiHeaders() { // return allOf( // hasHeader("Content-Type", is("application/xml")), // hasHeader("Accept", is("application/xml")), // hasHeader("X-Taxii-Accept", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-TAXII-Content-Type", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-Taxii-Protocol", is("urn:taxii.mitre.org:protocol:https:1.0")), // hasHeader("X-TAXII-Services", is("urn:taxii.mitre.org:services:1.1")) // ); // }
import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpResponse; import org.springframework.oxm.Unmarshaller; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.xml.datatype.DatatypeFactory; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.initialPollRequest; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.nextPollRequest; import static com.cisco.cta.taxii.adapter.httpclient.HasHeaderMatcher.hasAllTaxiiHeaders; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*;
@Test public void runFromEpochBegin() throws Exception { initialRequestResponse(); nextRequestResponse(2); assertThat(statistics.getPolls(), is(2L)); assertThat(statistics.getLogs(), is(2L)); assertThat(statistics.getErrors(), is(0L)); assertThat(OUTPUT_FILE + " content expected same as " + EXPECTED_OUTPUT_FILE, FileUtils.readFileToString(OUTPUT_FILE), is(FileUtils.readFileToString(EXPECTED_OUTPUT_FILE))); } @Test public void handleStatusMessage() throws Exception { initialRequestResponse(); requestStatusMessage(2); nextRequestResponse(3); assertThat(statistics.getPolls(), is(3L)); assertThat(statistics.getLogs(), is(2L)); assertThat(statistics.getErrors(), is(1L)); assertTrue( OUTPUT_FILE + " content expected same as " + EXPECTED_OUTPUT_FILE, FileUtils.contentEquals(OUTPUT_FILE, EXPECTED_OUTPUT_FILE)); } private void initialRequestResponse() throws IOException { when(httpResp.getRawStatusCode()).thenReturn(200); when(httpResp.getBody()).thenReturn(taxiiPollRespBodyInitial); task.run(); verify(httpRequestFactory).createRequest(pollServiceUri, HttpMethod.POST); verify(httpReq).execute();
// Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher initialPollRequest(String messageId, String collection) { // return new PollRequestMatcher(messageId, collection, null); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher nextPollRequest(String messageId, String collection, String begin) { // return new PollRequestMatcher(messageId, collection, begin); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HasHeaderMatcher.java // public static Matcher<HttpHeaders> hasAllTaxiiHeaders() { // return allOf( // hasHeader("Content-Type", is("application/xml")), // hasHeader("Accept", is("application/xml")), // hasHeader("X-Taxii-Accept", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-TAXII-Content-Type", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-Taxii-Protocol", is("urn:taxii.mitre.org:protocol:https:1.0")), // hasHeader("X-TAXII-Services", is("urn:taxii.mitre.org:services:1.1")) // ); // } // Path: src/test/java/com/cisco/cta/taxii/adapter/AdapterTaskIT.java import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpResponse; import org.springframework.oxm.Unmarshaller; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.xml.datatype.DatatypeFactory; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.initialPollRequest; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.nextPollRequest; import static com.cisco.cta.taxii.adapter.httpclient.HasHeaderMatcher.hasAllTaxiiHeaders; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; @Test public void runFromEpochBegin() throws Exception { initialRequestResponse(); nextRequestResponse(2); assertThat(statistics.getPolls(), is(2L)); assertThat(statistics.getLogs(), is(2L)); assertThat(statistics.getErrors(), is(0L)); assertThat(OUTPUT_FILE + " content expected same as " + EXPECTED_OUTPUT_FILE, FileUtils.readFileToString(OUTPUT_FILE), is(FileUtils.readFileToString(EXPECTED_OUTPUT_FILE))); } @Test public void handleStatusMessage() throws Exception { initialRequestResponse(); requestStatusMessage(2); nextRequestResponse(3); assertThat(statistics.getPolls(), is(3L)); assertThat(statistics.getLogs(), is(2L)); assertThat(statistics.getErrors(), is(1L)); assertTrue( OUTPUT_FILE + " content expected same as " + EXPECTED_OUTPUT_FILE, FileUtils.contentEquals(OUTPUT_FILE, EXPECTED_OUTPUT_FILE)); } private void initialRequestResponse() throws IOException { when(httpResp.getRawStatusCode()).thenReturn(200); when(httpResp.getBody()).thenReturn(taxiiPollRespBodyInitial); task.run(); verify(httpRequestFactory).createRequest(pollServiceUri, HttpMethod.POST); verify(httpReq).execute();
assertThat(httpReqHeaders, hasAllTaxiiHeaders());
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/AdapterTaskIT.java
// Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher initialPollRequest(String messageId, String collection) { // return new PollRequestMatcher(messageId, collection, null); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher nextPollRequest(String messageId, String collection, String begin) { // return new PollRequestMatcher(messageId, collection, begin); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HasHeaderMatcher.java // public static Matcher<HttpHeaders> hasAllTaxiiHeaders() { // return allOf( // hasHeader("Content-Type", is("application/xml")), // hasHeader("Accept", is("application/xml")), // hasHeader("X-Taxii-Accept", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-TAXII-Content-Type", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-Taxii-Protocol", is("urn:taxii.mitre.org:protocol:https:1.0")), // hasHeader("X-TAXII-Services", is("urn:taxii.mitre.org:services:1.1")) // ); // }
import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpResponse; import org.springframework.oxm.Unmarshaller; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.xml.datatype.DatatypeFactory; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.initialPollRequest; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.nextPollRequest; import static com.cisco.cta.taxii.adapter.httpclient.HasHeaderMatcher.hasAllTaxiiHeaders; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*;
public void runFromEpochBegin() throws Exception { initialRequestResponse(); nextRequestResponse(2); assertThat(statistics.getPolls(), is(2L)); assertThat(statistics.getLogs(), is(2L)); assertThat(statistics.getErrors(), is(0L)); assertThat(OUTPUT_FILE + " content expected same as " + EXPECTED_OUTPUT_FILE, FileUtils.readFileToString(OUTPUT_FILE), is(FileUtils.readFileToString(EXPECTED_OUTPUT_FILE))); } @Test public void handleStatusMessage() throws Exception { initialRequestResponse(); requestStatusMessage(2); nextRequestResponse(3); assertThat(statistics.getPolls(), is(3L)); assertThat(statistics.getLogs(), is(2L)); assertThat(statistics.getErrors(), is(1L)); assertTrue( OUTPUT_FILE + " content expected same as " + EXPECTED_OUTPUT_FILE, FileUtils.contentEquals(OUTPUT_FILE, EXPECTED_OUTPUT_FILE)); } private void initialRequestResponse() throws IOException { when(httpResp.getRawStatusCode()).thenReturn(200); when(httpResp.getBody()).thenReturn(taxiiPollRespBodyInitial); task.run(); verify(httpRequestFactory).createRequest(pollServiceUri, HttpMethod.POST); verify(httpReq).execute(); assertThat(httpReqHeaders, hasAllTaxiiHeaders());
// Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher initialPollRequest(String messageId, String collection) { // return new PollRequestMatcher(messageId, collection, null); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher nextPollRequest(String messageId, String collection, String begin) { // return new PollRequestMatcher(messageId, collection, begin); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HasHeaderMatcher.java // public static Matcher<HttpHeaders> hasAllTaxiiHeaders() { // return allOf( // hasHeader("Content-Type", is("application/xml")), // hasHeader("Accept", is("application/xml")), // hasHeader("X-Taxii-Accept", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-TAXII-Content-Type", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-Taxii-Protocol", is("urn:taxii.mitre.org:protocol:https:1.0")), // hasHeader("X-TAXII-Services", is("urn:taxii.mitre.org:services:1.1")) // ); // } // Path: src/test/java/com/cisco/cta/taxii/adapter/AdapterTaskIT.java import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpResponse; import org.springframework.oxm.Unmarshaller; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.xml.datatype.DatatypeFactory; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.initialPollRequest; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.nextPollRequest; import static com.cisco.cta.taxii.adapter.httpclient.HasHeaderMatcher.hasAllTaxiiHeaders; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; public void runFromEpochBegin() throws Exception { initialRequestResponse(); nextRequestResponse(2); assertThat(statistics.getPolls(), is(2L)); assertThat(statistics.getLogs(), is(2L)); assertThat(statistics.getErrors(), is(0L)); assertThat(OUTPUT_FILE + " content expected same as " + EXPECTED_OUTPUT_FILE, FileUtils.readFileToString(OUTPUT_FILE), is(FileUtils.readFileToString(EXPECTED_OUTPUT_FILE))); } @Test public void handleStatusMessage() throws Exception { initialRequestResponse(); requestStatusMessage(2); nextRequestResponse(3); assertThat(statistics.getPolls(), is(3L)); assertThat(statistics.getLogs(), is(2L)); assertThat(statistics.getErrors(), is(1L)); assertTrue( OUTPUT_FILE + " content expected same as " + EXPECTED_OUTPUT_FILE, FileUtils.contentEquals(OUTPUT_FILE, EXPECTED_OUTPUT_FILE)); } private void initialRequestResponse() throws IOException { when(httpResp.getRawStatusCode()).thenReturn(200); when(httpResp.getBody()).thenReturn(taxiiPollRespBodyInitial); task.run(); verify(httpRequestFactory).createRequest(pollServiceUri, HttpMethod.POST); verify(httpReq).execute(); assertThat(httpReqHeaders, hasAllTaxiiHeaders());
assertThat(httpReqBody, is(initialPollRequest("123", "collection_name")));
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/AdapterTaskIT.java
// Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher initialPollRequest(String messageId, String collection) { // return new PollRequestMatcher(messageId, collection, null); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher nextPollRequest(String messageId, String collection, String begin) { // return new PollRequestMatcher(messageId, collection, begin); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HasHeaderMatcher.java // public static Matcher<HttpHeaders> hasAllTaxiiHeaders() { // return allOf( // hasHeader("Content-Type", is("application/xml")), // hasHeader("Accept", is("application/xml")), // hasHeader("X-Taxii-Accept", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-TAXII-Content-Type", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-Taxii-Protocol", is("urn:taxii.mitre.org:protocol:https:1.0")), // hasHeader("X-TAXII-Services", is("urn:taxii.mitre.org:services:1.1")) // ); // }
import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpResponse; import org.springframework.oxm.Unmarshaller; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.xml.datatype.DatatypeFactory; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.initialPollRequest; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.nextPollRequest; import static com.cisco.cta.taxii.adapter.httpclient.HasHeaderMatcher.hasAllTaxiiHeaders; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*;
public void handleStatusMessage() throws Exception { initialRequestResponse(); requestStatusMessage(2); nextRequestResponse(3); assertThat(statistics.getPolls(), is(3L)); assertThat(statistics.getLogs(), is(2L)); assertThat(statistics.getErrors(), is(1L)); assertTrue( OUTPUT_FILE + " content expected same as " + EXPECTED_OUTPUT_FILE, FileUtils.contentEquals(OUTPUT_FILE, EXPECTED_OUTPUT_FILE)); } private void initialRequestResponse() throws IOException { when(httpResp.getRawStatusCode()).thenReturn(200); when(httpResp.getBody()).thenReturn(taxiiPollRespBodyInitial); task.run(); verify(httpRequestFactory).createRequest(pollServiceUri, HttpMethod.POST); verify(httpReq).execute(); assertThat(httpReqHeaders, hasAllTaxiiHeaders()); assertThat(httpReqBody, is(initialPollRequest("123", "collection_name"))); httpReqBody.reset(); } private void nextRequestResponse(int count) throws IOException { when(httpResp.getRawStatusCode()).thenReturn(200); when(httpResp.getBody()).thenReturn(taxiiPollRespBodyNext); task.run(); verify(httpRequestFactory, times(count)).createRequest(pollServiceUri, HttpMethod.POST); verify(httpReq, times(count)).execute(); assertThat(httpReqHeaders, hasAllTaxiiHeaders());
// Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher initialPollRequest(String messageId, String collection) { // return new PollRequestMatcher(messageId, collection, null); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher nextPollRequest(String messageId, String collection, String begin) { // return new PollRequestMatcher(messageId, collection, begin); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HasHeaderMatcher.java // public static Matcher<HttpHeaders> hasAllTaxiiHeaders() { // return allOf( // hasHeader("Content-Type", is("application/xml")), // hasHeader("Accept", is("application/xml")), // hasHeader("X-Taxii-Accept", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-TAXII-Content-Type", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-Taxii-Protocol", is("urn:taxii.mitre.org:protocol:https:1.0")), // hasHeader("X-TAXII-Services", is("urn:taxii.mitre.org:services:1.1")) // ); // } // Path: src/test/java/com/cisco/cta/taxii/adapter/AdapterTaskIT.java import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpResponse; import org.springframework.oxm.Unmarshaller; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.xml.datatype.DatatypeFactory; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.initialPollRequest; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.nextPollRequest; import static com.cisco.cta.taxii.adapter.httpclient.HasHeaderMatcher.hasAllTaxiiHeaders; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; public void handleStatusMessage() throws Exception { initialRequestResponse(); requestStatusMessage(2); nextRequestResponse(3); assertThat(statistics.getPolls(), is(3L)); assertThat(statistics.getLogs(), is(2L)); assertThat(statistics.getErrors(), is(1L)); assertTrue( OUTPUT_FILE + " content expected same as " + EXPECTED_OUTPUT_FILE, FileUtils.contentEquals(OUTPUT_FILE, EXPECTED_OUTPUT_FILE)); } private void initialRequestResponse() throws IOException { when(httpResp.getRawStatusCode()).thenReturn(200); when(httpResp.getBody()).thenReturn(taxiiPollRespBodyInitial); task.run(); verify(httpRequestFactory).createRequest(pollServiceUri, HttpMethod.POST); verify(httpReq).execute(); assertThat(httpReqHeaders, hasAllTaxiiHeaders()); assertThat(httpReqBody, is(initialPollRequest("123", "collection_name"))); httpReqBody.reset(); } private void nextRequestResponse(int count) throws IOException { when(httpResp.getRawStatusCode()).thenReturn(200); when(httpResp.getBody()).thenReturn(taxiiPollRespBodyNext); task.run(); verify(httpRequestFactory, times(count)).createRequest(pollServiceUri, HttpMethod.POST); verify(httpReq, times(count)).execute(); assertThat(httpReqHeaders, hasAllTaxiiHeaders());
assertThat(httpReqBody, is(nextPollRequest("123",
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/httpclient/HttpClientConfigurationTest.java
// Path: src/test/java/com/cisco/cta/taxii/adapter/YamlFileApplicationContextInitializer.java // public class YamlFileApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { // @Override // public void initialize(ConfigurableApplicationContext applicationContext) { // try { // Resource resource = applicationContext.getResource("classpath:/config/application.yml"); // YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader(); // List<PropertySource<?>> yamlTestPropertiesList = sourceLoader.load("application.yml", resource); // yamlTestPropertiesList.forEach(yamlTestProperties -> applicationContext.getEnvironment().getPropertySources().addLast(yamlTestProperties)); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/RequestFactory.java // @AllArgsConstructor // public class RequestFactory { // // private final URL pollEndpoint; // private final ClientHttpRequestFactory httpRequestFactory; // private final HttpHeadersAppender httpHeadersAppender; // private final HttpBodyWriter httpBodyWriter; // // // /** // * Create the TAXII request. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed. // * @return TAXII poll request. // * @throws Exception When any error occurs. // */ // public ClientHttpRequest createPollRequest(String messageId, TaxiiStatus.Feed feed) throws Exception { // ClientHttpRequest req = httpRequestFactory.createRequest(pollEndpoint.toURI(), HttpMethod.POST); // httpHeadersAppender.appendTo(req.getHeaders()); // httpBodyWriter.write(messageId, feed, req.getBody()); // return req; // } // // /** // * Create the TAXII request. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed name. // * @param resultId TAXII result id. // * @param resultPartNumber TAXII result part number. // * @return TAXII poll request. // * @throws Exception When any error occurs. // */ // public ClientHttpRequest createFulfillmentRequest(String messageId, TaxiiStatus.Feed feed, String resultId, Integer resultPartNumber) throws Exception { // ClientHttpRequest req = httpRequestFactory.createRequest(pollEndpoint.toURI(), HttpMethod.POST); // httpHeadersAppender.appendTo(req.getHeaders()); // httpBodyWriter.write(messageId, feed, resultId, resultPartNumber, req.getBody()); // return req; // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/PersistenceConfiguration.java // @Configuration // @Import({LinuxPersistenceConfiguration.class, WindowsPersistenceConfiguration.class}) // public class PersistenceConfiguration { // // @Autowired // private TaxiiStatusFileHandler taxiiStatusFileHandler; // // @Bean // public TaxiiStatusDao taxiiStatusDao() throws DatatypeConfigurationException { // return new TaxiiStatusDao(taxiiStatusFileHandler); // } // // @Bean // public Jaxb2Marshaller taxiiStatusMarshaller() { // Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller(); // jaxb2Marshaller.setClassesToBeBound(TaxiiStatus.class); // jaxb2Marshaller.setMarshallerProperties(ImmutableMap.of( // javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, true)); // return jaxb2Marshaller; // } // // }
import static org.junit.Assert.assertNotNull; import com.cisco.cta.taxii.adapter.YamlFileApplicationContextInitializer; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.cisco.cta.taxii.adapter.RequestFactory; import com.cisco.cta.taxii.adapter.persistence.PersistenceConfiguration;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; @ContextConfiguration(classes = {HttpClientConfiguration.class, PersistenceConfiguration.class}, initializers = YamlFileApplicationContextInitializer.class) @RunWith(SpringJUnit4ClassRunner.class) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) public class HttpClientConfigurationTest { @Autowired
// Path: src/test/java/com/cisco/cta/taxii/adapter/YamlFileApplicationContextInitializer.java // public class YamlFileApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { // @Override // public void initialize(ConfigurableApplicationContext applicationContext) { // try { // Resource resource = applicationContext.getResource("classpath:/config/application.yml"); // YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader(); // List<PropertySource<?>> yamlTestPropertiesList = sourceLoader.load("application.yml", resource); // yamlTestPropertiesList.forEach(yamlTestProperties -> applicationContext.getEnvironment().getPropertySources().addLast(yamlTestProperties)); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/RequestFactory.java // @AllArgsConstructor // public class RequestFactory { // // private final URL pollEndpoint; // private final ClientHttpRequestFactory httpRequestFactory; // private final HttpHeadersAppender httpHeadersAppender; // private final HttpBodyWriter httpBodyWriter; // // // /** // * Create the TAXII request. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed. // * @return TAXII poll request. // * @throws Exception When any error occurs. // */ // public ClientHttpRequest createPollRequest(String messageId, TaxiiStatus.Feed feed) throws Exception { // ClientHttpRequest req = httpRequestFactory.createRequest(pollEndpoint.toURI(), HttpMethod.POST); // httpHeadersAppender.appendTo(req.getHeaders()); // httpBodyWriter.write(messageId, feed, req.getBody()); // return req; // } // // /** // * Create the TAXII request. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed name. // * @param resultId TAXII result id. // * @param resultPartNumber TAXII result part number. // * @return TAXII poll request. // * @throws Exception When any error occurs. // */ // public ClientHttpRequest createFulfillmentRequest(String messageId, TaxiiStatus.Feed feed, String resultId, Integer resultPartNumber) throws Exception { // ClientHttpRequest req = httpRequestFactory.createRequest(pollEndpoint.toURI(), HttpMethod.POST); // httpHeadersAppender.appendTo(req.getHeaders()); // httpBodyWriter.write(messageId, feed, resultId, resultPartNumber, req.getBody()); // return req; // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/PersistenceConfiguration.java // @Configuration // @Import({LinuxPersistenceConfiguration.class, WindowsPersistenceConfiguration.class}) // public class PersistenceConfiguration { // // @Autowired // private TaxiiStatusFileHandler taxiiStatusFileHandler; // // @Bean // public TaxiiStatusDao taxiiStatusDao() throws DatatypeConfigurationException { // return new TaxiiStatusDao(taxiiStatusFileHandler); // } // // @Bean // public Jaxb2Marshaller taxiiStatusMarshaller() { // Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller(); // jaxb2Marshaller.setClassesToBeBound(TaxiiStatus.class); // jaxb2Marshaller.setMarshallerProperties(ImmutableMap.of( // javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, true)); // return jaxb2Marshaller; // } // // } // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HttpClientConfigurationTest.java import static org.junit.Assert.assertNotNull; import com.cisco.cta.taxii.adapter.YamlFileApplicationContextInitializer; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.cisco.cta.taxii.adapter.RequestFactory; import com.cisco.cta.taxii.adapter.persistence.PersistenceConfiguration; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; @ContextConfiguration(classes = {HttpClientConfiguration.class, PersistenceConfiguration.class}, initializers = YamlFileApplicationContextInitializer.class) @RunWith(SpringJUnit4ClassRunner.class) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) public class HttpClientConfigurationTest { @Autowired
private RequestFactory requestFactory;
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpBodyWriter.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // }
import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import freemarker.cache.ClassTemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.Version; import javax.xml.datatype.XMLGregorianCalendar; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.HashMap; import java.util.Map;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; /** * Writes an HTTP request body to an {@link OutputStream}. * The body is a TAXII poll request composed by <a href="http://freemarker.org/">FreeMarker</a> */ public class HttpBodyWriter { private static final String UTF_8 = "UTF-8"; private final Configuration cfg; private final Template template; private final Template templateFulfillment; public HttpBodyWriter() throws IOException { cfg = new Configuration(new Version(2, 3, 21)); cfg.setDefaultEncoding(UTF_8); cfg.setTemplateLoader(new ClassTemplateLoader(HttpBodyWriter.class, "templates")); template = cfg.getTemplate("poll-request.ftl"); templateFulfillment = cfg.getTemplate("poll-fulfillment-request.ftl"); } /** * Write the TAXII poll request to an {@link OutputStream}. * * @param messageId TAXII message id. * @param feed The TAXII feed. * @param body The {@link OutputStream} to write the body to. * @throws Exception When any error occurs. */
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // } // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpBodyWriter.java import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import freemarker.cache.ClassTemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.Version; import javax.xml.datatype.XMLGregorianCalendar; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.HashMap; import java.util.Map; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; /** * Writes an HTTP request body to an {@link OutputStream}. * The body is a TAXII poll request composed by <a href="http://freemarker.org/">FreeMarker</a> */ public class HttpBodyWriter { private static final String UTF_8 = "UTF-8"; private final Configuration cfg; private final Template template; private final Template templateFulfillment; public HttpBodyWriter() throws IOException { cfg = new Configuration(new Version(2, 3, 21)); cfg.setDefaultEncoding(UTF_8); cfg.setTemplateLoader(new ClassTemplateLoader(HttpBodyWriter.class, "templates")); template = cfg.getTemplate("poll-request.ftl"); templateFulfillment = cfg.getTemplate("poll-fulfillment-request.ftl"); } /** * Write the TAXII poll request to an {@link OutputStream}. * * @param messageId TAXII message id. * @param feed The TAXII feed. * @param body The {@link OutputStream} to write the body to. * @throws Exception When any error occurs. */
public void write(String messageId, TaxiiStatus.Feed feed, OutputStream body) throws Exception {
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/persistence/WindowsPersistenceConfiguration.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/WindowsCondition.java // public class WindowsCondition implements Condition { // // public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { // return SystemUtils.IS_OS_WINDOWS; // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/SettingsConfiguration.java // @Configuration // @EnableConfigurationProperties // public class SettingsConfiguration { // // @Bean // public TaxiiServiceSettings taxiiServiceSettings() { // return new TaxiiServiceSettings(); // } // // @Bean // public TransformSettings transformSettings() { // return new TransformSettings(); // } // // @Bean // public ScheduleSettings scheduleSettings() { // return new ScheduleSettings(); // } // // @Bean // public ProxySettings proxySettings() { // return new ProxySettings(); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import com.cisco.cta.taxii.adapter.WindowsCondition; import com.cisco.cta.taxii.adapter.settings.SettingsConfiguration; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.persistence; /** * Unix/Linux specific part of the {@link PersistenceConfiguration}. */ @Configuration @Conditional(WindowsCondition.class)
// Path: src/main/java/com/cisco/cta/taxii/adapter/WindowsCondition.java // public class WindowsCondition implements Condition { // // public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { // return SystemUtils.IS_OS_WINDOWS; // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/SettingsConfiguration.java // @Configuration // @EnableConfigurationProperties // public class SettingsConfiguration { // // @Bean // public TaxiiServiceSettings taxiiServiceSettings() { // return new TaxiiServiceSettings(); // } // // @Bean // public TransformSettings transformSettings() { // return new TransformSettings(); // } // // @Bean // public ScheduleSettings scheduleSettings() { // return new ScheduleSettings(); // } // // @Bean // public ProxySettings proxySettings() { // return new ProxySettings(); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // } // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/WindowsPersistenceConfiguration.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import com.cisco.cta.taxii.adapter.WindowsCondition; import com.cisco.cta.taxii.adapter.settings.SettingsConfiguration; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.persistence; /** * Unix/Linux specific part of the {@link PersistenceConfiguration}. */ @Configuration @Conditional(WindowsCondition.class)
@Import(SettingsConfiguration.class)
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/persistence/WindowsPersistenceConfiguration.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/WindowsCondition.java // public class WindowsCondition implements Condition { // // public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { // return SystemUtils.IS_OS_WINDOWS; // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/SettingsConfiguration.java // @Configuration // @EnableConfigurationProperties // public class SettingsConfiguration { // // @Bean // public TaxiiServiceSettings taxiiServiceSettings() { // return new TaxiiServiceSettings(); // } // // @Bean // public TransformSettings transformSettings() { // return new TransformSettings(); // } // // @Bean // public ScheduleSettings scheduleSettings() { // return new ScheduleSettings(); // } // // @Bean // public ProxySettings proxySettings() { // return new ProxySettings(); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import com.cisco.cta.taxii.adapter.WindowsCondition; import com.cisco.cta.taxii.adapter.settings.SettingsConfiguration; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.persistence; /** * Unix/Linux specific part of the {@link PersistenceConfiguration}. */ @Configuration @Conditional(WindowsCondition.class) @Import(SettingsConfiguration.class) public class WindowsPersistenceConfiguration { @Autowired
// Path: src/main/java/com/cisco/cta/taxii/adapter/WindowsCondition.java // public class WindowsCondition implements Condition { // // public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { // return SystemUtils.IS_OS_WINDOWS; // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/SettingsConfiguration.java // @Configuration // @EnableConfigurationProperties // public class SettingsConfiguration { // // @Bean // public TaxiiServiceSettings taxiiServiceSettings() { // return new TaxiiServiceSettings(); // } // // @Bean // public TransformSettings transformSettings() { // return new TransformSettings(); // } // // @Bean // public ScheduleSettings scheduleSettings() { // return new ScheduleSettings(); // } // // @Bean // public ProxySettings proxySettings() { // return new ProxySettings(); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // } // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/WindowsPersistenceConfiguration.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import com.cisco.cta.taxii.adapter.WindowsCondition; import com.cisco.cta.taxii.adapter.settings.SettingsConfiguration; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.persistence; /** * Unix/Linux specific part of the {@link PersistenceConfiguration}. */ @Configuration @Conditional(WindowsCondition.class) @Import(SettingsConfiguration.class) public class WindowsPersistenceConfiguration { @Autowired
private TaxiiServiceSettings taxiiServiceSettings;
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/NetworkAppenderTest.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/NetworkAppender.java // public enum Protocol{TCP, UDP}
import ch.qos.logback.classic.spi.ILoggingEvent; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.cisco.cta.taxii.adapter.NetworkAppender.Protocol; import ch.qos.logback.classic.LoggerContext;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; public class NetworkAppenderTest { private NetworkAppender appender; @Before public void setUp() throws Exception { appender = new NetworkAppender(); appender.setHost("localhost"); appender.setContext(new LoggerContext()); } @After public void tearDown() throws Exception { appender.stop(); } @Test public void start() throws Exception { appender.start(); assertTrue(appender.isStarted()); } @Test(timeout=5000) public void sendViaUdp() throws Exception { try (DatagramServer datagramServer = new DatagramServer()) { datagramServer.start();
// Path: src/main/java/com/cisco/cta/taxii/adapter/NetworkAppender.java // public enum Protocol{TCP, UDP} // Path: src/test/java/com/cisco/cta/taxii/adapter/NetworkAppenderTest.java import ch.qos.logback.classic.spi.ILoggingEvent; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.cisco.cta.taxii.adapter.NetworkAppender.Protocol; import ch.qos.logback.classic.LoggerContext; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; public class NetworkAppenderTest { private NetworkAppender appender; @Before public void setUp() throws Exception { appender = new NetworkAppender(); appender.setHost("localhost"); appender.setContext(new LoggerContext()); } @After public void tearDown() throws Exception { appender.stop(); } @Test public void start() throws Exception { appender.start(); assertTrue(appender.isStarted()); } @Test(timeout=5000) public void sendViaUdp() throws Exception { try (DatagramServer datagramServer = new DatagramServer()) { datagramServer.start();
appender.setProtocol(Protocol.UDP);
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/httpclient/HttpHeadersAppenderTest.java
// Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HasHeaderMatcher.java // public static Matcher<HttpHeaders> hasAllTaxiiHeaders() { // return allOf( // hasHeader("Content-Type", is("application/xml")), // hasHeader("Accept", is("application/xml")), // hasHeader("X-Taxii-Accept", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-TAXII-Content-Type", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-Taxii-Protocol", is("urn:taxii.mitre.org:protocol:https:1.0")), // hasHeader("X-TAXII-Services", is("urn:taxii.mitre.org:services:1.1")) // ); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HasHeaderMatcher.java // public static Matcher<HttpHeaders> hasUserAgentHeader() { // return allOf( // hasHeader("User-Agent", is("taxii-log-adapter-UNKNOWN")) // ); // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpHeadersAppender.java // public class HttpHeadersAppender { // // public void appendTo(HttpHeaders headers) { // headers.setContentType(MediaType.APPLICATION_XML); // headers.setAccept(ImmutableList.of(MediaType.APPLICATION_XML)); // headers.set("X-Taxii-Accept", "urn:taxii.mitre.org:message:xml:1.1"); // headers.set("X-TAXII-Content-Type", "urn:taxii.mitre.org:message:xml:1.1"); // headers.set("X-Taxii-Protocol", "urn:taxii.mitre.org:protocol:https:1.0"); // headers.set("X-TAXII-Services", "urn:taxii.mitre.org:services:1.1"); // headers.set("User-Agent", "taxii-log-adapter-" + Version.getImplVersion()); // } // // }
import static com.cisco.cta.taxii.adapter.httpclient.HasHeaderMatcher.hasAllTaxiiHeaders; import static com.cisco.cta.taxii.adapter.httpclient.HasHeaderMatcher.hasUserAgentHeader; import static org.junit.Assert.assertThat; import org.junit.Before; import org.junit.Test; import org.springframework.http.HttpHeaders; import com.cisco.cta.taxii.adapter.httpclient.HttpHeadersAppender;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; public class HttpHeadersAppenderTest { private HttpHeadersAppender appender; private HttpHeaders headers; @Before public void setUp() throws Exception { appender = new HttpHeadersAppender(); headers = new HttpHeaders(); } @Test public void appendHeaders() throws Exception { appender.appendTo(headers);
// Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HasHeaderMatcher.java // public static Matcher<HttpHeaders> hasAllTaxiiHeaders() { // return allOf( // hasHeader("Content-Type", is("application/xml")), // hasHeader("Accept", is("application/xml")), // hasHeader("X-Taxii-Accept", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-TAXII-Content-Type", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-Taxii-Protocol", is("urn:taxii.mitre.org:protocol:https:1.0")), // hasHeader("X-TAXII-Services", is("urn:taxii.mitre.org:services:1.1")) // ); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HasHeaderMatcher.java // public static Matcher<HttpHeaders> hasUserAgentHeader() { // return allOf( // hasHeader("User-Agent", is("taxii-log-adapter-UNKNOWN")) // ); // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpHeadersAppender.java // public class HttpHeadersAppender { // // public void appendTo(HttpHeaders headers) { // headers.setContentType(MediaType.APPLICATION_XML); // headers.setAccept(ImmutableList.of(MediaType.APPLICATION_XML)); // headers.set("X-Taxii-Accept", "urn:taxii.mitre.org:message:xml:1.1"); // headers.set("X-TAXII-Content-Type", "urn:taxii.mitre.org:message:xml:1.1"); // headers.set("X-Taxii-Protocol", "urn:taxii.mitre.org:protocol:https:1.0"); // headers.set("X-TAXII-Services", "urn:taxii.mitre.org:services:1.1"); // headers.set("User-Agent", "taxii-log-adapter-" + Version.getImplVersion()); // } // // } // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HttpHeadersAppenderTest.java import static com.cisco.cta.taxii.adapter.httpclient.HasHeaderMatcher.hasAllTaxiiHeaders; import static com.cisco.cta.taxii.adapter.httpclient.HasHeaderMatcher.hasUserAgentHeader; import static org.junit.Assert.assertThat; import org.junit.Before; import org.junit.Test; import org.springframework.http.HttpHeaders; import com.cisco.cta.taxii.adapter.httpclient.HttpHeadersAppender; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; public class HttpHeadersAppenderTest { private HttpHeadersAppender appender; private HttpHeaders headers; @Before public void setUp() throws Exception { appender = new HttpHeadersAppender(); headers = new HttpHeaders(); } @Test public void appendHeaders() throws Exception { appender.appendTo(headers);
assertThat(headers, hasAllTaxiiHeaders());
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/httpclient/HttpHeadersAppenderTest.java
// Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HasHeaderMatcher.java // public static Matcher<HttpHeaders> hasAllTaxiiHeaders() { // return allOf( // hasHeader("Content-Type", is("application/xml")), // hasHeader("Accept", is("application/xml")), // hasHeader("X-Taxii-Accept", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-TAXII-Content-Type", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-Taxii-Protocol", is("urn:taxii.mitre.org:protocol:https:1.0")), // hasHeader("X-TAXII-Services", is("urn:taxii.mitre.org:services:1.1")) // ); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HasHeaderMatcher.java // public static Matcher<HttpHeaders> hasUserAgentHeader() { // return allOf( // hasHeader("User-Agent", is("taxii-log-adapter-UNKNOWN")) // ); // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpHeadersAppender.java // public class HttpHeadersAppender { // // public void appendTo(HttpHeaders headers) { // headers.setContentType(MediaType.APPLICATION_XML); // headers.setAccept(ImmutableList.of(MediaType.APPLICATION_XML)); // headers.set("X-Taxii-Accept", "urn:taxii.mitre.org:message:xml:1.1"); // headers.set("X-TAXII-Content-Type", "urn:taxii.mitre.org:message:xml:1.1"); // headers.set("X-Taxii-Protocol", "urn:taxii.mitre.org:protocol:https:1.0"); // headers.set("X-TAXII-Services", "urn:taxii.mitre.org:services:1.1"); // headers.set("User-Agent", "taxii-log-adapter-" + Version.getImplVersion()); // } // // }
import static com.cisco.cta.taxii.adapter.httpclient.HasHeaderMatcher.hasAllTaxiiHeaders; import static com.cisco.cta.taxii.adapter.httpclient.HasHeaderMatcher.hasUserAgentHeader; import static org.junit.Assert.assertThat; import org.junit.Before; import org.junit.Test; import org.springframework.http.HttpHeaders; import com.cisco.cta.taxii.adapter.httpclient.HttpHeadersAppender;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; public class HttpHeadersAppenderTest { private HttpHeadersAppender appender; private HttpHeaders headers; @Before public void setUp() throws Exception { appender = new HttpHeadersAppender(); headers = new HttpHeaders(); } @Test public void appendHeaders() throws Exception { appender.appendTo(headers); assertThat(headers, hasAllTaxiiHeaders());
// Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HasHeaderMatcher.java // public static Matcher<HttpHeaders> hasAllTaxiiHeaders() { // return allOf( // hasHeader("Content-Type", is("application/xml")), // hasHeader("Accept", is("application/xml")), // hasHeader("X-Taxii-Accept", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-TAXII-Content-Type", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-Taxii-Protocol", is("urn:taxii.mitre.org:protocol:https:1.0")), // hasHeader("X-TAXII-Services", is("urn:taxii.mitre.org:services:1.1")) // ); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HasHeaderMatcher.java // public static Matcher<HttpHeaders> hasUserAgentHeader() { // return allOf( // hasHeader("User-Agent", is("taxii-log-adapter-UNKNOWN")) // ); // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpHeadersAppender.java // public class HttpHeadersAppender { // // public void appendTo(HttpHeaders headers) { // headers.setContentType(MediaType.APPLICATION_XML); // headers.setAccept(ImmutableList.of(MediaType.APPLICATION_XML)); // headers.set("X-Taxii-Accept", "urn:taxii.mitre.org:message:xml:1.1"); // headers.set("X-TAXII-Content-Type", "urn:taxii.mitre.org:message:xml:1.1"); // headers.set("X-Taxii-Protocol", "urn:taxii.mitre.org:protocol:https:1.0"); // headers.set("X-TAXII-Services", "urn:taxii.mitre.org:services:1.1"); // headers.set("User-Agent", "taxii-log-adapter-" + Version.getImplVersion()); // } // // } // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HttpHeadersAppenderTest.java import static com.cisco.cta.taxii.adapter.httpclient.HasHeaderMatcher.hasAllTaxiiHeaders; import static com.cisco.cta.taxii.adapter.httpclient.HasHeaderMatcher.hasUserAgentHeader; import static org.junit.Assert.assertThat; import org.junit.Before; import org.junit.Test; import org.springframework.http.HttpHeaders; import com.cisco.cta.taxii.adapter.httpclient.HttpHeadersAppender; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; public class HttpHeadersAppenderTest { private HttpHeadersAppender appender; private HttpHeaders headers; @Before public void setUp() throws Exception { appender = new HttpHeadersAppender(); headers = new HttpHeaders(); } @Test public void appendHeaders() throws Exception { appender.appendTo(headers); assertThat(headers, hasAllTaxiiHeaders());
assertThat(headers, hasUserAgentHeader());
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/smoketest/DetectTaxiiAuthenticationFailureTest.java
// Path: src/test/java/com/cisco/cta/taxii/adapter/smoketest/ContainsMessageMatcher.java // public static ArgumentMatcher<ILoggingEvent> containsMessage(String message) { // return new ContainsMessageMatcher(message); // }
import static com.cisco.cta.taxii.adapter.smoketest.ContainsMessageMatcher.containsMessage; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.AbstractHandler; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender;
@SuppressWarnings("unchecked") public void setUp() throws Exception { appender = mock(Appender.class); logger = (Logger) LoggerFactory.getLogger(SmokeTestLifecycle.class); logger.addAppender(appender); server = new Server(8098); server.setHandler(new UnauthorizedHandler()); server.start(); } private static class UnauthorizedHandler extends AbstractHandler { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { response.sendError(403, "Unauthorized"); } } @After public void tearDown() throws Exception { logger.detachAppender(appender); server.stop(); server.join(); } @Test public void failOnTaxiiAuthentication() throws Exception { smokeTestLifecycle.validateTaxiiConnectivity();
// Path: src/test/java/com/cisco/cta/taxii/adapter/smoketest/ContainsMessageMatcher.java // public static ArgumentMatcher<ILoggingEvent> containsMessage(String message) { // return new ContainsMessageMatcher(message); // } // Path: src/test/java/com/cisco/cta/taxii/adapter/smoketest/DetectTaxiiAuthenticationFailureTest.java import static com.cisco.cta.taxii.adapter.smoketest.ContainsMessageMatcher.containsMessage; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.AbstractHandler; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; @SuppressWarnings("unchecked") public void setUp() throws Exception { appender = mock(Appender.class); logger = (Logger) LoggerFactory.getLogger(SmokeTestLifecycle.class); logger.addAppender(appender); server = new Server(8098); server.setHandler(new UnauthorizedHandler()); server.start(); } private static class UnauthorizedHandler extends AbstractHandler { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { response.sendError(403, "Unauthorized"); } } @After public void tearDown() throws Exception { logger.detachAppender(appender); server.stop(); server.join(); } @Test public void failOnTaxiiAuthentication() throws Exception { smokeTestLifecycle.validateTaxiiConnectivity();
verify(appender).doAppend(argThat(containsMessage("verify your credentials in application.yml")));
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/httpclient/CredentialsProviderFactoryTest.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/CredentialsProviderFactory.java // public class CredentialsProviderFactory { // // private TaxiiServiceSettings settings; // private ProxySettings proxySettings; // // public CredentialsProviderFactory(TaxiiServiceSettings settings, ProxySettings proxySettings) { // this.settings = settings; // this.proxySettings = proxySettings; // } // // private void addProxyCredentials(CredentialsProvider credsProvider) { // if (proxySettings.getUrl() == null) { // return ; // } // if (proxySettings.getAuthenticationType() == null) { // throw new IllegalStateException("Both proxy url and proxy authentication type have to be specified."); // } // // ProxyAuthenticationType authType = proxySettings.getAuthenticationType(); // // URL proxyUrl = proxySettings.getUrl(); // HttpHost proxyHost = new HttpHost( // proxyUrl.getHost(), // proxyUrl.getPort(), // proxyUrl.getProtocol()); // // Credentials credentials; // switch(authType) { // case NONE: // break; // // case BASIC: // credentials = new UsernamePasswordCredentials(proxySettings.getUsername(), proxySettings.getPassword()); // credsProvider.setCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()), credentials); // break; // // case NTLM: // credentials = new NTCredentials( // proxySettings.getUsername(), // proxySettings.getPassword(), // proxySettings.getWorkstation(), // proxySettings.getDomain()); // credsProvider.setCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()), credentials); // break; // // default: // throw new IllegalStateException("Unsupported authentication type: " + authType); // } // } // // private void addTaxiiCredentials(CredentialsProvider credsProvider) { // URL url = settings.getPollEndpoint(); // HttpHost targetHost = new HttpHost( // url.getHost(), // url.getPort(), // url.getProtocol()); // credsProvider.setCredentials( // new AuthScope(targetHost.getHostName(), targetHost.getPort()), // new UsernamePasswordCredentials(settings.getUsername(), settings.getPassword())); // } // // public CredentialsProvider build() { // // Create credentials provider for BASIC auth // CredentialsProvider credsProvider = new BasicCredentialsProvider(); // addProxyCredentials(credsProvider); // addTaxiiCredentials(credsProvider); // return credsProvider; // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/ProxyAuthenticationType.java // public enum ProxyAuthenticationType { // NONE, // BASIC, // NTLM // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java // @ConfigurationProperties(prefix="proxy") // @Data // public class ProxySettings { // // private URL url; // // private ProxyAuthenticationType authenticationType; // // private String domain; // // private String username; // // private String password; // // private String workstation; // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettingsFactory.java // public class TaxiiServiceSettingsFactory { // // public static TaxiiServiceSettings createDefaults() { // try { // TaxiiServiceSettings connSettings = new TaxiiServiceSettings(); // connSettings.setPollEndpoint(new URL("http://localhost:8080/service")); // connSettings.setUsername("user"); // connSettings.setPassword("pass"); // return connSettings; // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // }
import static junit.framework.TestCase.assertNotNull; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertNull; import com.cisco.cta.taxii.adapter.httpclient.CredentialsProviderFactory; import com.cisco.cta.taxii.adapter.httpclient.ProxyAuthenticationType; import com.cisco.cta.taxii.adapter.settings.ProxySettings; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettingsFactory; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.client.CredentialsProvider; import org.junit.Before; import org.junit.Test; import java.net.MalformedURLException; import java.net.URL;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; public class CredentialsProviderFactoryTest { private TaxiiServiceSettings taxiiSettings; @Before public void setUp() throws Exception {
// Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/CredentialsProviderFactory.java // public class CredentialsProviderFactory { // // private TaxiiServiceSettings settings; // private ProxySettings proxySettings; // // public CredentialsProviderFactory(TaxiiServiceSettings settings, ProxySettings proxySettings) { // this.settings = settings; // this.proxySettings = proxySettings; // } // // private void addProxyCredentials(CredentialsProvider credsProvider) { // if (proxySettings.getUrl() == null) { // return ; // } // if (proxySettings.getAuthenticationType() == null) { // throw new IllegalStateException("Both proxy url and proxy authentication type have to be specified."); // } // // ProxyAuthenticationType authType = proxySettings.getAuthenticationType(); // // URL proxyUrl = proxySettings.getUrl(); // HttpHost proxyHost = new HttpHost( // proxyUrl.getHost(), // proxyUrl.getPort(), // proxyUrl.getProtocol()); // // Credentials credentials; // switch(authType) { // case NONE: // break; // // case BASIC: // credentials = new UsernamePasswordCredentials(proxySettings.getUsername(), proxySettings.getPassword()); // credsProvider.setCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()), credentials); // break; // // case NTLM: // credentials = new NTCredentials( // proxySettings.getUsername(), // proxySettings.getPassword(), // proxySettings.getWorkstation(), // proxySettings.getDomain()); // credsProvider.setCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()), credentials); // break; // // default: // throw new IllegalStateException("Unsupported authentication type: " + authType); // } // } // // private void addTaxiiCredentials(CredentialsProvider credsProvider) { // URL url = settings.getPollEndpoint(); // HttpHost targetHost = new HttpHost( // url.getHost(), // url.getPort(), // url.getProtocol()); // credsProvider.setCredentials( // new AuthScope(targetHost.getHostName(), targetHost.getPort()), // new UsernamePasswordCredentials(settings.getUsername(), settings.getPassword())); // } // // public CredentialsProvider build() { // // Create credentials provider for BASIC auth // CredentialsProvider credsProvider = new BasicCredentialsProvider(); // addProxyCredentials(credsProvider); // addTaxiiCredentials(credsProvider); // return credsProvider; // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/ProxyAuthenticationType.java // public enum ProxyAuthenticationType { // NONE, // BASIC, // NTLM // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java // @ConfigurationProperties(prefix="proxy") // @Data // public class ProxySettings { // // private URL url; // // private ProxyAuthenticationType authenticationType; // // private String domain; // // private String username; // // private String password; // // private String workstation; // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettingsFactory.java // public class TaxiiServiceSettingsFactory { // // public static TaxiiServiceSettings createDefaults() { // try { // TaxiiServiceSettings connSettings = new TaxiiServiceSettings(); // connSettings.setPollEndpoint(new URL("http://localhost:8080/service")); // connSettings.setUsername("user"); // connSettings.setPassword("pass"); // return connSettings; // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // } // } // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/CredentialsProviderFactoryTest.java import static junit.framework.TestCase.assertNotNull; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertNull; import com.cisco.cta.taxii.adapter.httpclient.CredentialsProviderFactory; import com.cisco.cta.taxii.adapter.httpclient.ProxyAuthenticationType; import com.cisco.cta.taxii.adapter.settings.ProxySettings; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettingsFactory; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.client.CredentialsProvider; import org.junit.Before; import org.junit.Test; import java.net.MalformedURLException; import java.net.URL; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; public class CredentialsProviderFactoryTest { private TaxiiServiceSettings taxiiSettings; @Before public void setUp() throws Exception {
taxiiSettings = TaxiiServiceSettingsFactory.createDefaults();
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/persistence/LinuxPersistenceConfiguration.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/NonWindowsCondition.java // public class NonWindowsCondition implements Condition { // // public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { // return ! SystemUtils.IS_OS_WINDOWS; // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/SettingsConfiguration.java // @Configuration // @EnableConfigurationProperties // public class SettingsConfiguration { // // @Bean // public TaxiiServiceSettings taxiiServiceSettings() { // return new TaxiiServiceSettings(); // } // // @Bean // public TransformSettings transformSettings() { // return new TransformSettings(); // } // // @Bean // public ScheduleSettings scheduleSettings() { // return new ScheduleSettings(); // } // // @Bean // public ProxySettings proxySettings() { // return new ProxySettings(); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // }
import org.dellroad.stuff.pobj.PersistentObject; import org.dellroad.stuff.pobj.PersistentObjectDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import com.cisco.cta.taxii.adapter.NonWindowsCondition; import com.cisco.cta.taxii.adapter.settings.SettingsConfiguration; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.persistence; /** * Unix/Linux specific part of the {@link PersistenceConfiguration}. */ @Configuration @Conditional(NonWindowsCondition.class)
// Path: src/main/java/com/cisco/cta/taxii/adapter/NonWindowsCondition.java // public class NonWindowsCondition implements Condition { // // public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { // return ! SystemUtils.IS_OS_WINDOWS; // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/SettingsConfiguration.java // @Configuration // @EnableConfigurationProperties // public class SettingsConfiguration { // // @Bean // public TaxiiServiceSettings taxiiServiceSettings() { // return new TaxiiServiceSettings(); // } // // @Bean // public TransformSettings transformSettings() { // return new TransformSettings(); // } // // @Bean // public ScheduleSettings scheduleSettings() { // return new ScheduleSettings(); // } // // @Bean // public ProxySettings proxySettings() { // return new ProxySettings(); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // } // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/LinuxPersistenceConfiguration.java import org.dellroad.stuff.pobj.PersistentObject; import org.dellroad.stuff.pobj.PersistentObjectDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import com.cisco.cta.taxii.adapter.NonWindowsCondition; import com.cisco.cta.taxii.adapter.settings.SettingsConfiguration; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.persistence; /** * Unix/Linux specific part of the {@link PersistenceConfiguration}. */ @Configuration @Conditional(NonWindowsCondition.class)
@Import(SettingsConfiguration.class)
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/persistence/LinuxPersistenceConfiguration.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/NonWindowsCondition.java // public class NonWindowsCondition implements Condition { // // public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { // return ! SystemUtils.IS_OS_WINDOWS; // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/SettingsConfiguration.java // @Configuration // @EnableConfigurationProperties // public class SettingsConfiguration { // // @Bean // public TaxiiServiceSettings taxiiServiceSettings() { // return new TaxiiServiceSettings(); // } // // @Bean // public TransformSettings transformSettings() { // return new TransformSettings(); // } // // @Bean // public ScheduleSettings scheduleSettings() { // return new ScheduleSettings(); // } // // @Bean // public ProxySettings proxySettings() { // return new ProxySettings(); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // }
import org.dellroad.stuff.pobj.PersistentObject; import org.dellroad.stuff.pobj.PersistentObjectDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import com.cisco.cta.taxii.adapter.NonWindowsCondition; import com.cisco.cta.taxii.adapter.settings.SettingsConfiguration; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.persistence; /** * Unix/Linux specific part of the {@link PersistenceConfiguration}. */ @Configuration @Conditional(NonWindowsCondition.class) @Import(SettingsConfiguration.class) public class LinuxPersistenceConfiguration { @Autowired
// Path: src/main/java/com/cisco/cta/taxii/adapter/NonWindowsCondition.java // public class NonWindowsCondition implements Condition { // // public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { // return ! SystemUtils.IS_OS_WINDOWS; // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/SettingsConfiguration.java // @Configuration // @EnableConfigurationProperties // public class SettingsConfiguration { // // @Bean // public TaxiiServiceSettings taxiiServiceSettings() { // return new TaxiiServiceSettings(); // } // // @Bean // public TransformSettings transformSettings() { // return new TransformSettings(); // } // // @Bean // public ScheduleSettings scheduleSettings() { // return new ScheduleSettings(); // } // // @Bean // public ProxySettings proxySettings() { // return new ProxySettings(); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // } // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/LinuxPersistenceConfiguration.java import org.dellroad.stuff.pobj.PersistentObject; import org.dellroad.stuff.pobj.PersistentObjectDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import com.cisco.cta.taxii.adapter.NonWindowsCondition; import com.cisco.cta.taxii.adapter.settings.SettingsConfiguration; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.persistence; /** * Unix/Linux specific part of the {@link PersistenceConfiguration}. */ @Configuration @Conditional(NonWindowsCondition.class) @Import(SettingsConfiguration.class) public class LinuxPersistenceConfiguration { @Autowired
private TaxiiServiceSettings taxiiServiceSettings;
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/AdapterRunner.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/error/ChainHandler.java // public class ChainHandler implements Handler<Throwable> { // // private final Handler<BindValidationException> bindExceptionHandler = new BindExceptionHandler(System.err); // private final Handler<YAMLException> yamlExceptionHandler = new YamlExceptionHandler(System.err); // private final Handler<Throwable> causeHandler = new CauseHandler(System.err); // private final Handler<Throwable> fallBackHandler = new FallBackHandler(System.err); // // // @Override // public void handle(Throwable t) { // try { // throw t; // // } catch (NestedRuntimeException e) { // try { // throw e.getMostSpecificCause(); // } catch (BindValidationException bindRootCause) { // bindExceptionHandler.handle(bindRootCause); // } catch (Throwable unknownRootCause) { // fallBackHandler.handle(unknownRootCause); // } // // } catch (YAMLException target) { // yamlExceptionHandler.handle(target); // // } catch (IllegalStateException illegal) { // causeHandler.handle(illegal); // // } catch (Throwable e) { // fallBackHandler.handle(e); // } // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/error/Handler.java // public interface Handler<T extends Throwable> { // // void handle(T t); // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/smoketest/SmokeTestConfiguration.java // @Configuration // @Profile("smoketest") // @Import(AdapterConfiguration.class) // public class SmokeTestConfiguration { // // @Autowired // private SettingsConfiguration settingsConfig; // // @Autowired // private RequestFactory requestFactory; // // @Autowired // private Templates templates; // // @Autowired // private Writer logWriter; // // @Bean // public SmokeTestLifecycle smokeTest() { // return new SmokeTestLifecycle(settingsConfig, requestFactory, templates, logWriter); // } // // }
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.PrintStream; import org.springframework.boot.Banner.Mode; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.ApplicationPidFileWriter; import org.springframework.context.ConfigurableApplicationContext; import com.cisco.cta.taxii.adapter.error.ChainHandler; import com.cisco.cta.taxii.adapter.error.Handler; import com.cisco.cta.taxii.adapter.smoketest.SmokeTestConfiguration; import com.google.common.io.ByteStreams;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Adapter main class. */ public class AdapterRunner { static ConfigurableApplicationContext ctx;
// Path: src/main/java/com/cisco/cta/taxii/adapter/error/ChainHandler.java // public class ChainHandler implements Handler<Throwable> { // // private final Handler<BindValidationException> bindExceptionHandler = new BindExceptionHandler(System.err); // private final Handler<YAMLException> yamlExceptionHandler = new YamlExceptionHandler(System.err); // private final Handler<Throwable> causeHandler = new CauseHandler(System.err); // private final Handler<Throwable> fallBackHandler = new FallBackHandler(System.err); // // // @Override // public void handle(Throwable t) { // try { // throw t; // // } catch (NestedRuntimeException e) { // try { // throw e.getMostSpecificCause(); // } catch (BindValidationException bindRootCause) { // bindExceptionHandler.handle(bindRootCause); // } catch (Throwable unknownRootCause) { // fallBackHandler.handle(unknownRootCause); // } // // } catch (YAMLException target) { // yamlExceptionHandler.handle(target); // // } catch (IllegalStateException illegal) { // causeHandler.handle(illegal); // // } catch (Throwable e) { // fallBackHandler.handle(e); // } // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/error/Handler.java // public interface Handler<T extends Throwable> { // // void handle(T t); // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/smoketest/SmokeTestConfiguration.java // @Configuration // @Profile("smoketest") // @Import(AdapterConfiguration.class) // public class SmokeTestConfiguration { // // @Autowired // private SettingsConfiguration settingsConfig; // // @Autowired // private RequestFactory requestFactory; // // @Autowired // private Templates templates; // // @Autowired // private Writer logWriter; // // @Bean // public SmokeTestLifecycle smokeTest() { // return new SmokeTestLifecycle(settingsConfig, requestFactory, templates, logWriter); // } // // } // Path: src/main/java/com/cisco/cta/taxii/adapter/AdapterRunner.java import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.PrintStream; import org.springframework.boot.Banner.Mode; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.ApplicationPidFileWriter; import org.springframework.context.ConfigurableApplicationContext; import com.cisco.cta.taxii.adapter.error.ChainHandler; import com.cisco.cta.taxii.adapter.error.Handler; import com.cisco.cta.taxii.adapter.smoketest.SmokeTestConfiguration; import com.google.common.io.ByteStreams; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Adapter main class. */ public class AdapterRunner { static ConfigurableApplicationContext ctx;
private static final Handler<Throwable> errHandler = new ChainHandler();
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/AdapterRunner.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/error/ChainHandler.java // public class ChainHandler implements Handler<Throwable> { // // private final Handler<BindValidationException> bindExceptionHandler = new BindExceptionHandler(System.err); // private final Handler<YAMLException> yamlExceptionHandler = new YamlExceptionHandler(System.err); // private final Handler<Throwable> causeHandler = new CauseHandler(System.err); // private final Handler<Throwable> fallBackHandler = new FallBackHandler(System.err); // // // @Override // public void handle(Throwable t) { // try { // throw t; // // } catch (NestedRuntimeException e) { // try { // throw e.getMostSpecificCause(); // } catch (BindValidationException bindRootCause) { // bindExceptionHandler.handle(bindRootCause); // } catch (Throwable unknownRootCause) { // fallBackHandler.handle(unknownRootCause); // } // // } catch (YAMLException target) { // yamlExceptionHandler.handle(target); // // } catch (IllegalStateException illegal) { // causeHandler.handle(illegal); // // } catch (Throwable e) { // fallBackHandler.handle(e); // } // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/error/Handler.java // public interface Handler<T extends Throwable> { // // void handle(T t); // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/smoketest/SmokeTestConfiguration.java // @Configuration // @Profile("smoketest") // @Import(AdapterConfiguration.class) // public class SmokeTestConfiguration { // // @Autowired // private SettingsConfiguration settingsConfig; // // @Autowired // private RequestFactory requestFactory; // // @Autowired // private Templates templates; // // @Autowired // private Writer logWriter; // // @Bean // public SmokeTestLifecycle smokeTest() { // return new SmokeTestLifecycle(settingsConfig, requestFactory, templates, logWriter); // } // // }
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.PrintStream; import org.springframework.boot.Banner.Mode; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.ApplicationPidFileWriter; import org.springframework.context.ConfigurableApplicationContext; import com.cisco.cta.taxii.adapter.error.ChainHandler; import com.cisco.cta.taxii.adapter.error.Handler; import com.cisco.cta.taxii.adapter.smoketest.SmokeTestConfiguration; import com.google.common.io.ByteStreams;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Adapter main class. */ public class AdapterRunner { static ConfigurableApplicationContext ctx;
// Path: src/main/java/com/cisco/cta/taxii/adapter/error/ChainHandler.java // public class ChainHandler implements Handler<Throwable> { // // private final Handler<BindValidationException> bindExceptionHandler = new BindExceptionHandler(System.err); // private final Handler<YAMLException> yamlExceptionHandler = new YamlExceptionHandler(System.err); // private final Handler<Throwable> causeHandler = new CauseHandler(System.err); // private final Handler<Throwable> fallBackHandler = new FallBackHandler(System.err); // // // @Override // public void handle(Throwable t) { // try { // throw t; // // } catch (NestedRuntimeException e) { // try { // throw e.getMostSpecificCause(); // } catch (BindValidationException bindRootCause) { // bindExceptionHandler.handle(bindRootCause); // } catch (Throwable unknownRootCause) { // fallBackHandler.handle(unknownRootCause); // } // // } catch (YAMLException target) { // yamlExceptionHandler.handle(target); // // } catch (IllegalStateException illegal) { // causeHandler.handle(illegal); // // } catch (Throwable e) { // fallBackHandler.handle(e); // } // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/error/Handler.java // public interface Handler<T extends Throwable> { // // void handle(T t); // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/smoketest/SmokeTestConfiguration.java // @Configuration // @Profile("smoketest") // @Import(AdapterConfiguration.class) // public class SmokeTestConfiguration { // // @Autowired // private SettingsConfiguration settingsConfig; // // @Autowired // private RequestFactory requestFactory; // // @Autowired // private Templates templates; // // @Autowired // private Writer logWriter; // // @Bean // public SmokeTestLifecycle smokeTest() { // return new SmokeTestLifecycle(settingsConfig, requestFactory, templates, logWriter); // } // // } // Path: src/main/java/com/cisco/cta/taxii/adapter/AdapterRunner.java import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.PrintStream; import org.springframework.boot.Banner.Mode; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.ApplicationPidFileWriter; import org.springframework.context.ConfigurableApplicationContext; import com.cisco.cta.taxii.adapter.error.ChainHandler; import com.cisco.cta.taxii.adapter.error.Handler; import com.cisco.cta.taxii.adapter.smoketest.SmokeTestConfiguration; import com.google.common.io.ByteStreams; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Adapter main class. */ public class AdapterRunner { static ConfigurableApplicationContext ctx;
private static final Handler<Throwable> errHandler = new ChainHandler();
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/AdapterRunner.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/error/ChainHandler.java // public class ChainHandler implements Handler<Throwable> { // // private final Handler<BindValidationException> bindExceptionHandler = new BindExceptionHandler(System.err); // private final Handler<YAMLException> yamlExceptionHandler = new YamlExceptionHandler(System.err); // private final Handler<Throwable> causeHandler = new CauseHandler(System.err); // private final Handler<Throwable> fallBackHandler = new FallBackHandler(System.err); // // // @Override // public void handle(Throwable t) { // try { // throw t; // // } catch (NestedRuntimeException e) { // try { // throw e.getMostSpecificCause(); // } catch (BindValidationException bindRootCause) { // bindExceptionHandler.handle(bindRootCause); // } catch (Throwable unknownRootCause) { // fallBackHandler.handle(unknownRootCause); // } // // } catch (YAMLException target) { // yamlExceptionHandler.handle(target); // // } catch (IllegalStateException illegal) { // causeHandler.handle(illegal); // // } catch (Throwable e) { // fallBackHandler.handle(e); // } // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/error/Handler.java // public interface Handler<T extends Throwable> { // // void handle(T t); // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/smoketest/SmokeTestConfiguration.java // @Configuration // @Profile("smoketest") // @Import(AdapterConfiguration.class) // public class SmokeTestConfiguration { // // @Autowired // private SettingsConfiguration settingsConfig; // // @Autowired // private RequestFactory requestFactory; // // @Autowired // private Templates templates; // // @Autowired // private Writer logWriter; // // @Bean // public SmokeTestLifecycle smokeTest() { // return new SmokeTestLifecycle(settingsConfig, requestFactory, templates, logWriter); // } // // }
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.PrintStream; import org.springframework.boot.Banner.Mode; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.ApplicationPidFileWriter; import org.springframework.context.ConfigurableApplicationContext; import com.cisco.cta.taxii.adapter.error.ChainHandler; import com.cisco.cta.taxii.adapter.error.Handler; import com.cisco.cta.taxii.adapter.smoketest.SmokeTestConfiguration; import com.google.common.io.ByteStreams;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Adapter main class. */ public class AdapterRunner { static ConfigurableApplicationContext ctx; private static final Handler<Throwable> errHandler = new ChainHandler(); /** * @param args The command line arguments. */ @SuppressFBWarnings(value="DM_DEFAULT_ENCODING", justification="DEV-NULL encoding is irrelevant") public static void main(String[] args) { try (PrintStream devNull = new PrintStream(ByteStreams.nullOutputStream())) { System.setErr(devNull); ctx = new SpringApplicationBuilder( ScheduleConfiguration.class, RunNowConfiguration.class,
// Path: src/main/java/com/cisco/cta/taxii/adapter/error/ChainHandler.java // public class ChainHandler implements Handler<Throwable> { // // private final Handler<BindValidationException> bindExceptionHandler = new BindExceptionHandler(System.err); // private final Handler<YAMLException> yamlExceptionHandler = new YamlExceptionHandler(System.err); // private final Handler<Throwable> causeHandler = new CauseHandler(System.err); // private final Handler<Throwable> fallBackHandler = new FallBackHandler(System.err); // // // @Override // public void handle(Throwable t) { // try { // throw t; // // } catch (NestedRuntimeException e) { // try { // throw e.getMostSpecificCause(); // } catch (BindValidationException bindRootCause) { // bindExceptionHandler.handle(bindRootCause); // } catch (Throwable unknownRootCause) { // fallBackHandler.handle(unknownRootCause); // } // // } catch (YAMLException target) { // yamlExceptionHandler.handle(target); // // } catch (IllegalStateException illegal) { // causeHandler.handle(illegal); // // } catch (Throwable e) { // fallBackHandler.handle(e); // } // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/error/Handler.java // public interface Handler<T extends Throwable> { // // void handle(T t); // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/smoketest/SmokeTestConfiguration.java // @Configuration // @Profile("smoketest") // @Import(AdapterConfiguration.class) // public class SmokeTestConfiguration { // // @Autowired // private SettingsConfiguration settingsConfig; // // @Autowired // private RequestFactory requestFactory; // // @Autowired // private Templates templates; // // @Autowired // private Writer logWriter; // // @Bean // public SmokeTestLifecycle smokeTest() { // return new SmokeTestLifecycle(settingsConfig, requestFactory, templates, logWriter); // } // // } // Path: src/main/java/com/cisco/cta/taxii/adapter/AdapterRunner.java import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.PrintStream; import org.springframework.boot.Banner.Mode; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.ApplicationPidFileWriter; import org.springframework.context.ConfigurableApplicationContext; import com.cisco.cta.taxii.adapter.error.ChainHandler; import com.cisco.cta.taxii.adapter.error.Handler; import com.cisco.cta.taxii.adapter.smoketest.SmokeTestConfiguration; import com.google.common.io.ByteStreams; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Adapter main class. */ public class AdapterRunner { static ConfigurableApplicationContext ctx; private static final Handler<Throwable> errHandler = new ChainHandler(); /** * @param args The command line arguments. */ @SuppressFBWarnings(value="DM_DEFAULT_ENCODING", justification="DEV-NULL encoding is irrelevant") public static void main(String[] args) { try (PrintStream devNull = new PrintStream(ByteStreams.nullOutputStream())) { System.setErr(devNull); ctx = new SpringApplicationBuilder( ScheduleConfiguration.class, RunNowConfiguration.class,
SmokeTestConfiguration.class,
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpClientConfiguration.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/RequestFactory.java // @AllArgsConstructor // public class RequestFactory { // // private final URL pollEndpoint; // private final ClientHttpRequestFactory httpRequestFactory; // private final HttpHeadersAppender httpHeadersAppender; // private final HttpBodyWriter httpBodyWriter; // // // /** // * Create the TAXII request. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed. // * @return TAXII poll request. // * @throws Exception When any error occurs. // */ // public ClientHttpRequest createPollRequest(String messageId, TaxiiStatus.Feed feed) throws Exception { // ClientHttpRequest req = httpRequestFactory.createRequest(pollEndpoint.toURI(), HttpMethod.POST); // httpHeadersAppender.appendTo(req.getHeaders()); // httpBodyWriter.write(messageId, feed, req.getBody()); // return req; // } // // /** // * Create the TAXII request. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed name. // * @param resultId TAXII result id. // * @param resultPartNumber TAXII result part number. // * @return TAXII poll request. // * @throws Exception When any error occurs. // */ // public ClientHttpRequest createFulfillmentRequest(String messageId, TaxiiStatus.Feed feed, String resultId, Integer resultPartNumber) throws Exception { // ClientHttpRequest req = httpRequestFactory.createRequest(pollEndpoint.toURI(), HttpMethod.POST); // httpHeadersAppender.appendTo(req.getHeaders()); // httpBodyWriter.write(messageId, feed, resultId, resultPartNumber, req.getBody()); // return req; // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java // @ConfigurationProperties(prefix="proxy") // @Data // public class ProxySettings { // // private URL url; // // private ProxyAuthenticationType authenticationType; // // private String domain; // // private String username; // // private String password; // // private String workstation; // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // }
import com.cisco.cta.taxii.adapter.RequestFactory; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import com.cisco.cta.taxii.adapter.settings.ProxySettings; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; @Configuration public class HttpClientConfiguration { @Autowired
// Path: src/main/java/com/cisco/cta/taxii/adapter/RequestFactory.java // @AllArgsConstructor // public class RequestFactory { // // private final URL pollEndpoint; // private final ClientHttpRequestFactory httpRequestFactory; // private final HttpHeadersAppender httpHeadersAppender; // private final HttpBodyWriter httpBodyWriter; // // // /** // * Create the TAXII request. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed. // * @return TAXII poll request. // * @throws Exception When any error occurs. // */ // public ClientHttpRequest createPollRequest(String messageId, TaxiiStatus.Feed feed) throws Exception { // ClientHttpRequest req = httpRequestFactory.createRequest(pollEndpoint.toURI(), HttpMethod.POST); // httpHeadersAppender.appendTo(req.getHeaders()); // httpBodyWriter.write(messageId, feed, req.getBody()); // return req; // } // // /** // * Create the TAXII request. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed name. // * @param resultId TAXII result id. // * @param resultPartNumber TAXII result part number. // * @return TAXII poll request. // * @throws Exception When any error occurs. // */ // public ClientHttpRequest createFulfillmentRequest(String messageId, TaxiiStatus.Feed feed, String resultId, Integer resultPartNumber) throws Exception { // ClientHttpRequest req = httpRequestFactory.createRequest(pollEndpoint.toURI(), HttpMethod.POST); // httpHeadersAppender.appendTo(req.getHeaders()); // httpBodyWriter.write(messageId, feed, resultId, resultPartNumber, req.getBody()); // return req; // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java // @ConfigurationProperties(prefix="proxy") // @Data // public class ProxySettings { // // private URL url; // // private ProxyAuthenticationType authenticationType; // // private String domain; // // private String username; // // private String password; // // private String workstation; // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // } // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpClientConfiguration.java import com.cisco.cta.taxii.adapter.RequestFactory; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import com.cisco.cta.taxii.adapter.settings.ProxySettings; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; @Configuration public class HttpClientConfiguration { @Autowired
private TaxiiServiceSettings taxiiServiceSettings;
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpClientConfiguration.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/RequestFactory.java // @AllArgsConstructor // public class RequestFactory { // // private final URL pollEndpoint; // private final ClientHttpRequestFactory httpRequestFactory; // private final HttpHeadersAppender httpHeadersAppender; // private final HttpBodyWriter httpBodyWriter; // // // /** // * Create the TAXII request. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed. // * @return TAXII poll request. // * @throws Exception When any error occurs. // */ // public ClientHttpRequest createPollRequest(String messageId, TaxiiStatus.Feed feed) throws Exception { // ClientHttpRequest req = httpRequestFactory.createRequest(pollEndpoint.toURI(), HttpMethod.POST); // httpHeadersAppender.appendTo(req.getHeaders()); // httpBodyWriter.write(messageId, feed, req.getBody()); // return req; // } // // /** // * Create the TAXII request. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed name. // * @param resultId TAXII result id. // * @param resultPartNumber TAXII result part number. // * @return TAXII poll request. // * @throws Exception When any error occurs. // */ // public ClientHttpRequest createFulfillmentRequest(String messageId, TaxiiStatus.Feed feed, String resultId, Integer resultPartNumber) throws Exception { // ClientHttpRequest req = httpRequestFactory.createRequest(pollEndpoint.toURI(), HttpMethod.POST); // httpHeadersAppender.appendTo(req.getHeaders()); // httpBodyWriter.write(messageId, feed, resultId, resultPartNumber, req.getBody()); // return req; // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java // @ConfigurationProperties(prefix="proxy") // @Data // public class ProxySettings { // // private URL url; // // private ProxyAuthenticationType authenticationType; // // private String domain; // // private String username; // // private String password; // // private String workstation; // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // }
import com.cisco.cta.taxii.adapter.RequestFactory; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import com.cisco.cta.taxii.adapter.settings.ProxySettings; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; @Configuration public class HttpClientConfiguration { @Autowired private TaxiiServiceSettings taxiiServiceSettings; @Autowired
// Path: src/main/java/com/cisco/cta/taxii/adapter/RequestFactory.java // @AllArgsConstructor // public class RequestFactory { // // private final URL pollEndpoint; // private final ClientHttpRequestFactory httpRequestFactory; // private final HttpHeadersAppender httpHeadersAppender; // private final HttpBodyWriter httpBodyWriter; // // // /** // * Create the TAXII request. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed. // * @return TAXII poll request. // * @throws Exception When any error occurs. // */ // public ClientHttpRequest createPollRequest(String messageId, TaxiiStatus.Feed feed) throws Exception { // ClientHttpRequest req = httpRequestFactory.createRequest(pollEndpoint.toURI(), HttpMethod.POST); // httpHeadersAppender.appendTo(req.getHeaders()); // httpBodyWriter.write(messageId, feed, req.getBody()); // return req; // } // // /** // * Create the TAXII request. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed name. // * @param resultId TAXII result id. // * @param resultPartNumber TAXII result part number. // * @return TAXII poll request. // * @throws Exception When any error occurs. // */ // public ClientHttpRequest createFulfillmentRequest(String messageId, TaxiiStatus.Feed feed, String resultId, Integer resultPartNumber) throws Exception { // ClientHttpRequest req = httpRequestFactory.createRequest(pollEndpoint.toURI(), HttpMethod.POST); // httpHeadersAppender.appendTo(req.getHeaders()); // httpBodyWriter.write(messageId, feed, resultId, resultPartNumber, req.getBody()); // return req; // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java // @ConfigurationProperties(prefix="proxy") // @Data // public class ProxySettings { // // private URL url; // // private ProxyAuthenticationType authenticationType; // // private String domain; // // private String username; // // private String password; // // private String workstation; // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // } // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpClientConfiguration.java import com.cisco.cta.taxii.adapter.RequestFactory; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import com.cisco.cta.taxii.adapter.settings.ProxySettings; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; @Configuration public class HttpClientConfiguration { @Autowired private TaxiiServiceSettings taxiiServiceSettings; @Autowired
private TaxiiStatusDao taxiiStatusDao;
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpClientConfiguration.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/RequestFactory.java // @AllArgsConstructor // public class RequestFactory { // // private final URL pollEndpoint; // private final ClientHttpRequestFactory httpRequestFactory; // private final HttpHeadersAppender httpHeadersAppender; // private final HttpBodyWriter httpBodyWriter; // // // /** // * Create the TAXII request. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed. // * @return TAXII poll request. // * @throws Exception When any error occurs. // */ // public ClientHttpRequest createPollRequest(String messageId, TaxiiStatus.Feed feed) throws Exception { // ClientHttpRequest req = httpRequestFactory.createRequest(pollEndpoint.toURI(), HttpMethod.POST); // httpHeadersAppender.appendTo(req.getHeaders()); // httpBodyWriter.write(messageId, feed, req.getBody()); // return req; // } // // /** // * Create the TAXII request. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed name. // * @param resultId TAXII result id. // * @param resultPartNumber TAXII result part number. // * @return TAXII poll request. // * @throws Exception When any error occurs. // */ // public ClientHttpRequest createFulfillmentRequest(String messageId, TaxiiStatus.Feed feed, String resultId, Integer resultPartNumber) throws Exception { // ClientHttpRequest req = httpRequestFactory.createRequest(pollEndpoint.toURI(), HttpMethod.POST); // httpHeadersAppender.appendTo(req.getHeaders()); // httpBodyWriter.write(messageId, feed, resultId, resultPartNumber, req.getBody()); // return req; // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java // @ConfigurationProperties(prefix="proxy") // @Data // public class ProxySettings { // // private URL url; // // private ProxyAuthenticationType authenticationType; // // private String domain; // // private String username; // // private String password; // // private String workstation; // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // }
import com.cisco.cta.taxii.adapter.RequestFactory; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import com.cisco.cta.taxii.adapter.settings.ProxySettings; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; @Configuration public class HttpClientConfiguration { @Autowired private TaxiiServiceSettings taxiiServiceSettings; @Autowired private TaxiiStatusDao taxiiStatusDao; @Autowired
// Path: src/main/java/com/cisco/cta/taxii/adapter/RequestFactory.java // @AllArgsConstructor // public class RequestFactory { // // private final URL pollEndpoint; // private final ClientHttpRequestFactory httpRequestFactory; // private final HttpHeadersAppender httpHeadersAppender; // private final HttpBodyWriter httpBodyWriter; // // // /** // * Create the TAXII request. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed. // * @return TAXII poll request. // * @throws Exception When any error occurs. // */ // public ClientHttpRequest createPollRequest(String messageId, TaxiiStatus.Feed feed) throws Exception { // ClientHttpRequest req = httpRequestFactory.createRequest(pollEndpoint.toURI(), HttpMethod.POST); // httpHeadersAppender.appendTo(req.getHeaders()); // httpBodyWriter.write(messageId, feed, req.getBody()); // return req; // } // // /** // * Create the TAXII request. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed name. // * @param resultId TAXII result id. // * @param resultPartNumber TAXII result part number. // * @return TAXII poll request. // * @throws Exception When any error occurs. // */ // public ClientHttpRequest createFulfillmentRequest(String messageId, TaxiiStatus.Feed feed, String resultId, Integer resultPartNumber) throws Exception { // ClientHttpRequest req = httpRequestFactory.createRequest(pollEndpoint.toURI(), HttpMethod.POST); // httpHeadersAppender.appendTo(req.getHeaders()); // httpBodyWriter.write(messageId, feed, resultId, resultPartNumber, req.getBody()); // return req; // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java // @ConfigurationProperties(prefix="proxy") // @Data // public class ProxySettings { // // private URL url; // // private ProxyAuthenticationType authenticationType; // // private String domain; // // private String username; // // private String password; // // private String workstation; // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // } // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpClientConfiguration.java import com.cisco.cta.taxii.adapter.RequestFactory; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import com.cisco.cta.taxii.adapter.settings.ProxySettings; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; @Configuration public class HttpClientConfiguration { @Autowired private TaxiiServiceSettings taxiiServiceSettings; @Autowired private TaxiiStatusDao taxiiStatusDao; @Autowired
private ProxySettings proxySettings;
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/smoketest/DetectUnreachableTaxiiTest.java
// Path: src/test/java/com/cisco/cta/taxii/adapter/YamlFileApplicationContextInitializer.java // public class YamlFileApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { // @Override // public void initialize(ConfigurableApplicationContext applicationContext) { // try { // Resource resource = applicationContext.getResource("classpath:/config/application.yml"); // YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader(); // List<PropertySource<?>> yamlTestPropertiesList = sourceLoader.load("application.yml", resource); // yamlTestPropertiesList.forEach(yamlTestProperties -> applicationContext.getEnvironment().getPropertySources().addLast(yamlTestProperties)); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/smoketest/ContainsMessageMatcher.java // public static ArgumentMatcher<ILoggingEvent> containsMessage(String message) { // return new ContainsMessageMatcher(message); // }
import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; import com.cisco.cta.taxii.adapter.YamlFileApplicationContextInitializer; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static com.cisco.cta.taxii.adapter.smoketest.ContainsMessageMatcher.containsMessage; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.smoketest; @ContextConfiguration(classes = {SmokeTestConfiguration.class}, initializers = YamlFileApplicationContextInitializer.class) @ActiveProfiles("smoketest") @TestPropertySource(properties={ "taxiiService.pollEndpoint=http://nosuchsite", "proxy.url=http://nosuchsite" }) @RunWith(SpringJUnit4ClassRunner.class) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) public class DetectUnreachableTaxiiTest { @Autowired private SmokeTestLifecycle smokeTestLifecycle; private Logger logger; private Appender<ILoggingEvent> appender; @Before @SuppressWarnings("unchecked") public void setUp() throws Exception { appender = mock(Appender.class); logger = (Logger) LoggerFactory.getLogger(SmokeTestLifecycle.class); logger.addAppender(appender); } @After public void tearDown() throws Exception { logger.detachAppender(appender); } @Test public void failOnUnreachableTaxiiEndpoint() throws Exception { smokeTestLifecycle.validateTaxiiConnectivity();
// Path: src/test/java/com/cisco/cta/taxii/adapter/YamlFileApplicationContextInitializer.java // public class YamlFileApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { // @Override // public void initialize(ConfigurableApplicationContext applicationContext) { // try { // Resource resource = applicationContext.getResource("classpath:/config/application.yml"); // YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader(); // List<PropertySource<?>> yamlTestPropertiesList = sourceLoader.load("application.yml", resource); // yamlTestPropertiesList.forEach(yamlTestProperties -> applicationContext.getEnvironment().getPropertySources().addLast(yamlTestProperties)); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/smoketest/ContainsMessageMatcher.java // public static ArgumentMatcher<ILoggingEvent> containsMessage(String message) { // return new ContainsMessageMatcher(message); // } // Path: src/test/java/com/cisco/cta/taxii/adapter/smoketest/DetectUnreachableTaxiiTest.java import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; import com.cisco.cta.taxii.adapter.YamlFileApplicationContextInitializer; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static com.cisco.cta.taxii.adapter.smoketest.ContainsMessageMatcher.containsMessage; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.smoketest; @ContextConfiguration(classes = {SmokeTestConfiguration.class}, initializers = YamlFileApplicationContextInitializer.class) @ActiveProfiles("smoketest") @TestPropertySource(properties={ "taxiiService.pollEndpoint=http://nosuchsite", "proxy.url=http://nosuchsite" }) @RunWith(SpringJUnit4ClassRunner.class) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) public class DetectUnreachableTaxiiTest { @Autowired private SmokeTestLifecycle smokeTestLifecycle; private Logger logger; private Appender<ILoggingEvent> appender; @Before @SuppressWarnings("unchecked") public void setUp() throws Exception { appender = mock(Appender.class); logger = (Logger) LoggerFactory.getLogger(SmokeTestLifecycle.class); logger.addAppender(appender); } @After public void tearDown() throws Exception { logger.detachAppender(appender); } @Test public void failOnUnreachableTaxiiEndpoint() throws Exception { smokeTestLifecycle.validateTaxiiConnectivity();
verify(appender).doAppend(argThat(containsMessage("Unable to resolve host name http://nosuchsite, verify your application.yml and your DNS settings")));
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/ProxyAuthenticationType.java // public enum ProxyAuthenticationType { // NONE, // BASIC, // NTLM // // }
import com.cisco.cta.taxii.adapter.httpclient.ProxyAuthenticationType; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import java.net.URL;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.settings; @ConfigurationProperties(prefix="proxy") @Data public class ProxySettings { private URL url;
// Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/ProxyAuthenticationType.java // public enum ProxyAuthenticationType { // NONE, // BASIC, // NTLM // // } // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java import com.cisco.cta.taxii.adapter.httpclient.ProxyAuthenticationType; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import java.net.URL; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.settings; @ConfigurationProperties(prefix="proxy") @Data public class ProxySettings { private URL url;
private ProxyAuthenticationType authenticationType;
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/settings/SettingsConfigurationTest.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/ProxyAuthenticationType.java // public enum ProxyAuthenticationType { // NONE, // BASIC, // NTLM // // }
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.core.NestedRuntimeException; import org.springframework.core.env.PropertySource; import org.springframework.mock.env.MockPropertySource; import java.net.URL; import java.util.List; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.fail; import com.cisco.cta.taxii.adapter.httpclient.ProxyAuthenticationType; import org.junit.Test; import org.springframework.beans.factory.BeanCreationException; import org.springframework.boot.context.properties.bind.validation.BindValidationException; import org.springframework.context.ConfigurableApplicationContext;
try (ConfigurableApplicationContext ctx = context(validProperties())) { assertThat(ctx.getBean(TaxiiServiceSettings.class).getFeeds().get(0), is("alpha-feed")); } } private ConfigurableApplicationContext context(PropertySource<?> source) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(SettingsConfiguration.class); ctx.getEnvironment().getPropertySources().addFirst(source); ctx.refresh(); return ctx; } private MockPropertySource validProperties() { return new MockPropertySource() .withProperty("taxii-service.pollEndpoint", "http://taxii") .withProperty("taxii-service.username", "smith") .withProperty("taxii-service.password", "secret") .withProperty("taxii-service.feeds[0]", "alpha-feed") .withProperty("taxii-service.statusFile", "taxii-status.xml") .withProperty("schedule.cron", "* * * * * *") .withProperty("transform.stylesheet", "transform.xsl") .withProperty("proxy.url", "http://localhost:8001/") .withProperty("proxy.authenticationType", "NONE"); } @Test public void typeConversion() throws Exception { try (ConfigurableApplicationContext ctx = context(validProperties())) { assertThat(ctx.getBean(ProxySettings.class).getUrl(), is(new URL("http://localhost:8001/")));
// Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/ProxyAuthenticationType.java // public enum ProxyAuthenticationType { // NONE, // BASIC, // NTLM // // } // Path: src/test/java/com/cisco/cta/taxii/adapter/settings/SettingsConfigurationTest.java import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.core.NestedRuntimeException; import org.springframework.core.env.PropertySource; import org.springframework.mock.env.MockPropertySource; import java.net.URL; import java.util.List; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.fail; import com.cisco.cta.taxii.adapter.httpclient.ProxyAuthenticationType; import org.junit.Test; import org.springframework.beans.factory.BeanCreationException; import org.springframework.boot.context.properties.bind.validation.BindValidationException; import org.springframework.context.ConfigurableApplicationContext; try (ConfigurableApplicationContext ctx = context(validProperties())) { assertThat(ctx.getBean(TaxiiServiceSettings.class).getFeeds().get(0), is("alpha-feed")); } } private ConfigurableApplicationContext context(PropertySource<?> source) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(SettingsConfiguration.class); ctx.getEnvironment().getPropertySources().addFirst(source); ctx.refresh(); return ctx; } private MockPropertySource validProperties() { return new MockPropertySource() .withProperty("taxii-service.pollEndpoint", "http://taxii") .withProperty("taxii-service.username", "smith") .withProperty("taxii-service.password", "secret") .withProperty("taxii-service.feeds[0]", "alpha-feed") .withProperty("taxii-service.statusFile", "taxii-status.xml") .withProperty("schedule.cron", "* * * * * *") .withProperty("transform.stylesheet", "transform.xsl") .withProperty("proxy.url", "http://localhost:8001/") .withProperty("proxy.authenticationType", "NONE"); } @Test public void typeConversion() throws Exception { try (ConfigurableApplicationContext ctx = context(validProperties())) { assertThat(ctx.getBean(ProxySettings.class).getUrl(), is(new URL("http://localhost:8001/")));
assertThat(ctx.getBean(ProxySettings.class).getAuthenticationType(), is(ProxyAuthenticationType.NONE));
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/RunNowConfiguration.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // }
import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Profile;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Spring configuration providing factory methods for run-now beans. */ @Configuration @Profile("now") @Import(AdapterConfiguration.class) public class RunNowConfiguration { @Bean
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // } // Path: src/main/java/com/cisco/cta/taxii/adapter/RunNowConfiguration.java import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Profile; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Spring configuration providing factory methods for run-now beans. */ @Configuration @Profile("now") @Import(AdapterConfiguration.class) public class RunNowConfiguration { @Bean
public RunAndExit runAndExit(AdapterConfiguration adapterConfiguration, RequestFactory requestFactory, TaxiiServiceSettings taxiiServiceSettings, TaxiiStatusDao taxiiStatusDao) throws Exception {
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/RunNowConfiguration.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // }
import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Profile;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Spring configuration providing factory methods for run-now beans. */ @Configuration @Profile("now") @Import(AdapterConfiguration.class) public class RunNowConfiguration { @Bean
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // } // Path: src/main/java/com/cisco/cta/taxii/adapter/RunNowConfiguration.java import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Profile; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Spring configuration providing factory methods for run-now beans. */ @Configuration @Profile("now") @Import(AdapterConfiguration.class) public class RunNowConfiguration { @Bean
public RunAndExit runAndExit(AdapterConfiguration adapterConfiguration, RequestFactory requestFactory, TaxiiServiceSettings taxiiServiceSettings, TaxiiStatusDao taxiiStatusDao) throws Exception {
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/httpclient/HttpBodyWriterTest.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher initialPollRequest(String messageId, String collection) { // return new PollRequestMatcher(messageId, collection, null); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher nextPollRequest(String messageId, String collection, String begin) { // return new PollRequestMatcher(messageId, collection, begin); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollFulfillmentMatcher.java // public static PollFulfillmentMatcher pollFulfillment(String messageId, String collection, String resultId, String resultPartNumber) { // return new PollFulfillmentMatcher(messageId, collection, resultId, resultPartNumber); // }
import static com.cisco.cta.taxii.adapter.PollFulfillmentMatcher.pollFulfillment; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.io.ByteArrayOutputStream; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.initialPollRequest; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.nextPollRequest;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; @RunWith(MockitoJUnitRunner.class) public class HttpBodyWriterTest { @InjectMocks private HttpBodyWriter writer; @Spy private ByteArrayOutputStream out = new ByteArrayOutputStream();
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher initialPollRequest(String messageId, String collection) { // return new PollRequestMatcher(messageId, collection, null); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher nextPollRequest(String messageId, String collection, String begin) { // return new PollRequestMatcher(messageId, collection, begin); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollFulfillmentMatcher.java // public static PollFulfillmentMatcher pollFulfillment(String messageId, String collection, String resultId, String resultPartNumber) { // return new PollFulfillmentMatcher(messageId, collection, resultId, resultPartNumber); // } // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HttpBodyWriterTest.java import static com.cisco.cta.taxii.adapter.PollFulfillmentMatcher.pollFulfillment; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.io.ByteArrayOutputStream; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.initialPollRequest; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.nextPollRequest; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; @RunWith(MockitoJUnitRunner.class) public class HttpBodyWriterTest { @InjectMocks private HttpBodyWriter writer; @Spy private ByteArrayOutputStream out = new ByteArrayOutputStream();
private TaxiiStatus.Feed feed;
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/httpclient/HttpBodyWriterTest.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher initialPollRequest(String messageId, String collection) { // return new PollRequestMatcher(messageId, collection, null); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher nextPollRequest(String messageId, String collection, String begin) { // return new PollRequestMatcher(messageId, collection, begin); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollFulfillmentMatcher.java // public static PollFulfillmentMatcher pollFulfillment(String messageId, String collection, String resultId, String resultPartNumber) { // return new PollFulfillmentMatcher(messageId, collection, resultId, resultPartNumber); // }
import static com.cisco.cta.taxii.adapter.PollFulfillmentMatcher.pollFulfillment; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.io.ByteArrayOutputStream; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.initialPollRequest; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.nextPollRequest;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; @RunWith(MockitoJUnitRunner.class) public class HttpBodyWriterTest { @InjectMocks private HttpBodyWriter writer; @Spy private ByteArrayOutputStream out = new ByteArrayOutputStream(); private TaxiiStatus.Feed feed; private DatatypeFactory datatypeFactory; private XMLGregorianCalendar cal; @Before public void setUp() throws Exception { feed = new TaxiiStatus.Feed(); feed.setName("my-feed"); datatypeFactory = DatatypeFactory.newInstance(); cal = datatypeFactory.newXMLGregorianCalendar("2015-01-01T00:00:00"); } @Test public void writeInitialPollRequest() throws Exception { writer.write("tla-123", feed, out);
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher initialPollRequest(String messageId, String collection) { // return new PollRequestMatcher(messageId, collection, null); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher nextPollRequest(String messageId, String collection, String begin) { // return new PollRequestMatcher(messageId, collection, begin); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollFulfillmentMatcher.java // public static PollFulfillmentMatcher pollFulfillment(String messageId, String collection, String resultId, String resultPartNumber) { // return new PollFulfillmentMatcher(messageId, collection, resultId, resultPartNumber); // } // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HttpBodyWriterTest.java import static com.cisco.cta.taxii.adapter.PollFulfillmentMatcher.pollFulfillment; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.io.ByteArrayOutputStream; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.initialPollRequest; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.nextPollRequest; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; @RunWith(MockitoJUnitRunner.class) public class HttpBodyWriterTest { @InjectMocks private HttpBodyWriter writer; @Spy private ByteArrayOutputStream out = new ByteArrayOutputStream(); private TaxiiStatus.Feed feed; private DatatypeFactory datatypeFactory; private XMLGregorianCalendar cal; @Before public void setUp() throws Exception { feed = new TaxiiStatus.Feed(); feed.setName("my-feed"); datatypeFactory = DatatypeFactory.newInstance(); cal = datatypeFactory.newXMLGregorianCalendar("2015-01-01T00:00:00"); } @Test public void writeInitialPollRequest() throws Exception { writer.write("tla-123", feed, out);
assertThat(out, is(initialPollRequest("tla-123", "my-feed")));
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/httpclient/HttpBodyWriterTest.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher initialPollRequest(String messageId, String collection) { // return new PollRequestMatcher(messageId, collection, null); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher nextPollRequest(String messageId, String collection, String begin) { // return new PollRequestMatcher(messageId, collection, begin); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollFulfillmentMatcher.java // public static PollFulfillmentMatcher pollFulfillment(String messageId, String collection, String resultId, String resultPartNumber) { // return new PollFulfillmentMatcher(messageId, collection, resultId, resultPartNumber); // }
import static com.cisco.cta.taxii.adapter.PollFulfillmentMatcher.pollFulfillment; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.io.ByteArrayOutputStream; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.initialPollRequest; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.nextPollRequest;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; @RunWith(MockitoJUnitRunner.class) public class HttpBodyWriterTest { @InjectMocks private HttpBodyWriter writer; @Spy private ByteArrayOutputStream out = new ByteArrayOutputStream(); private TaxiiStatus.Feed feed; private DatatypeFactory datatypeFactory; private XMLGregorianCalendar cal; @Before public void setUp() throws Exception { feed = new TaxiiStatus.Feed(); feed.setName("my-feed"); datatypeFactory = DatatypeFactory.newInstance(); cal = datatypeFactory.newXMLGregorianCalendar("2015-01-01T00:00:00"); } @Test public void writeInitialPollRequest() throws Exception { writer.write("tla-123", feed, out); assertThat(out, is(initialPollRequest("tla-123", "my-feed"))); verify(out).close(); } @Test public void writeNextPollRequest() throws Exception { feed.setLastUpdate(cal); writer.write("tla-123", feed, out);
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher initialPollRequest(String messageId, String collection) { // return new PollRequestMatcher(messageId, collection, null); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher nextPollRequest(String messageId, String collection, String begin) { // return new PollRequestMatcher(messageId, collection, begin); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollFulfillmentMatcher.java // public static PollFulfillmentMatcher pollFulfillment(String messageId, String collection, String resultId, String resultPartNumber) { // return new PollFulfillmentMatcher(messageId, collection, resultId, resultPartNumber); // } // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HttpBodyWriterTest.java import static com.cisco.cta.taxii.adapter.PollFulfillmentMatcher.pollFulfillment; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.io.ByteArrayOutputStream; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.initialPollRequest; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.nextPollRequest; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; @RunWith(MockitoJUnitRunner.class) public class HttpBodyWriterTest { @InjectMocks private HttpBodyWriter writer; @Spy private ByteArrayOutputStream out = new ByteArrayOutputStream(); private TaxiiStatus.Feed feed; private DatatypeFactory datatypeFactory; private XMLGregorianCalendar cal; @Before public void setUp() throws Exception { feed = new TaxiiStatus.Feed(); feed.setName("my-feed"); datatypeFactory = DatatypeFactory.newInstance(); cal = datatypeFactory.newXMLGregorianCalendar("2015-01-01T00:00:00"); } @Test public void writeInitialPollRequest() throws Exception { writer.write("tla-123", feed, out); assertThat(out, is(initialPollRequest("tla-123", "my-feed"))); verify(out).close(); } @Test public void writeNextPollRequest() throws Exception { feed.setLastUpdate(cal); writer.write("tla-123", feed, out);
assertThat(out, is(nextPollRequest("tla-123", "my-feed", "2015-01-01T00:00:00")));
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/httpclient/HttpBodyWriterTest.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher initialPollRequest(String messageId, String collection) { // return new PollRequestMatcher(messageId, collection, null); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher nextPollRequest(String messageId, String collection, String begin) { // return new PollRequestMatcher(messageId, collection, begin); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollFulfillmentMatcher.java // public static PollFulfillmentMatcher pollFulfillment(String messageId, String collection, String resultId, String resultPartNumber) { // return new PollFulfillmentMatcher(messageId, collection, resultId, resultPartNumber); // }
import static com.cisco.cta.taxii.adapter.PollFulfillmentMatcher.pollFulfillment; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.io.ByteArrayOutputStream; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.initialPollRequest; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.nextPollRequest;
private XMLGregorianCalendar cal; @Before public void setUp() throws Exception { feed = new TaxiiStatus.Feed(); feed.setName("my-feed"); datatypeFactory = DatatypeFactory.newInstance(); cal = datatypeFactory.newXMLGregorianCalendar("2015-01-01T00:00:00"); } @Test public void writeInitialPollRequest() throws Exception { writer.write("tla-123", feed, out); assertThat(out, is(initialPollRequest("tla-123", "my-feed"))); verify(out).close(); } @Test public void writeNextPollRequest() throws Exception { feed.setLastUpdate(cal); writer.write("tla-123", feed, out); assertThat(out, is(nextPollRequest("tla-123", "my-feed", "2015-01-01T00:00:00"))); verify(out).close(); } @Test public void resultPartNumberFormattedCorrectly() throws Exception { feed.setLastUpdate(cal); writer.write("tla-123", feed, "123#456", 1000, out);
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher initialPollRequest(String messageId, String collection) { // return new PollRequestMatcher(messageId, collection, null); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher nextPollRequest(String messageId, String collection, String begin) { // return new PollRequestMatcher(messageId, collection, begin); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollFulfillmentMatcher.java // public static PollFulfillmentMatcher pollFulfillment(String messageId, String collection, String resultId, String resultPartNumber) { // return new PollFulfillmentMatcher(messageId, collection, resultId, resultPartNumber); // } // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HttpBodyWriterTest.java import static com.cisco.cta.taxii.adapter.PollFulfillmentMatcher.pollFulfillment; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.io.ByteArrayOutputStream; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.initialPollRequest; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.nextPollRequest; private XMLGregorianCalendar cal; @Before public void setUp() throws Exception { feed = new TaxiiStatus.Feed(); feed.setName("my-feed"); datatypeFactory = DatatypeFactory.newInstance(); cal = datatypeFactory.newXMLGregorianCalendar("2015-01-01T00:00:00"); } @Test public void writeInitialPollRequest() throws Exception { writer.write("tla-123", feed, out); assertThat(out, is(initialPollRequest("tla-123", "my-feed"))); verify(out).close(); } @Test public void writeNextPollRequest() throws Exception { feed.setLastUpdate(cal); writer.write("tla-123", feed, out); assertThat(out, is(nextPollRequest("tla-123", "my-feed", "2015-01-01T00:00:00"))); verify(out).close(); } @Test public void resultPartNumberFormattedCorrectly() throws Exception { feed.setLastUpdate(cal); writer.write("tla-123", feed, "123#456", 1000, out);
assertThat(out, is(pollFulfillment("tla-123", "my-feed", "123#456", "1000")));
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/ResponseTransformerTest.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // }
import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatcher; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.client.ClientHttpResponse; import javax.xml.stream.XMLStreamConstants; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.stax.StAXSource; import javax.xml.transform.stream.StreamResult; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import static org.mockito.Answers.RETURNS_MOCKS; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; public class ResponseTransformerTest { private ResponseTransformer responseTransformer; @Mock private TaxiiPollResponseReaderFactory readerFactory; @Mock private Writer logWriter; @Mock
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // } // Path: src/test/java/com/cisco/cta/taxii/adapter/ResponseTransformerTest.java import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatcher; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.client.ClientHttpResponse; import javax.xml.stream.XMLStreamConstants; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.stax.StAXSource; import javax.xml.transform.stream.StreamResult; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import static org.mockito.Answers.RETURNS_MOCKS; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; public class ResponseTransformerTest { private ResponseTransformer responseTransformer; @Mock private TaxiiPollResponseReaderFactory readerFactory; @Mock private Writer logWriter; @Mock
private TaxiiStatusDao taxiiStatusDao;
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/ResponseTransformerTest.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // }
import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatcher; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.client.ClientHttpResponse; import javax.xml.stream.XMLStreamConstants; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.stax.StAXSource; import javax.xml.transform.stream.StreamResult; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import static org.mockito.Answers.RETURNS_MOCKS; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; public class ResponseTransformerTest { private ResponseTransformer responseTransformer; @Mock private TaxiiPollResponseReaderFactory readerFactory; @Mock private Writer logWriter; @Mock private TaxiiStatusDao taxiiStatusDao; @Mock private Templates templates; @Mock private ClientHttpResponse resp; @Mock private InputStream body; @Mock private Transformer transformer; @Mock(answer=RETURNS_MOCKS) private TaxiiPollResponseReader responseReader;
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // } // Path: src/test/java/com/cisco/cta/taxii/adapter/ResponseTransformerTest.java import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatcher; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.client.ClientHttpResponse; import javax.xml.stream.XMLStreamConstants; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.stax.StAXSource; import javax.xml.transform.stream.StreamResult; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import static org.mockito.Answers.RETURNS_MOCKS; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; public class ResponseTransformerTest { private ResponseTransformer responseTransformer; @Mock private TaxiiPollResponseReaderFactory readerFactory; @Mock private Writer logWriter; @Mock private TaxiiStatusDao taxiiStatusDao; @Mock private Templates templates; @Mock private ClientHttpResponse resp; @Mock private InputStream body; @Mock private Transformer transformer; @Mock(answer=RETURNS_MOCKS) private TaxiiPollResponseReader responseReader;
private TaxiiStatus.Feed feed;
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/httpclient/CredentialsProviderFactory.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java // @ConfigurationProperties(prefix="proxy") // @Data // public class ProxySettings { // // private URL url; // // private ProxyAuthenticationType authenticationType; // // private String domain; // // private String username; // // private String password; // // private String workstation; // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // }
import com.cisco.cta.taxii.adapter.settings.ProxySettings; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.NTCredentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import java.net.URL;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; public class CredentialsProviderFactory { private TaxiiServiceSettings settings;
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/ProxySettings.java // @ConfigurationProperties(prefix="proxy") // @Data // public class ProxySettings { // // private URL url; // // private ProxyAuthenticationType authenticationType; // // private String domain; // // private String username; // // private String password; // // private String workstation; // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // } // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/CredentialsProviderFactory.java import com.cisco.cta.taxii.adapter.settings.ProxySettings; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.NTCredentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import java.net.URL; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; public class CredentialsProviderFactory { private TaxiiServiceSettings settings;
private ProxySettings proxySettings;
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/httpclient/BasicAuthHttpRequestFactory.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // }
import java.net.URI; import java.net.URL; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import org.apache.http.HttpHost; import org.apache.http.client.AuthCache; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicAuthCache; import org.apache.http.protocol.HttpContext; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; /** * {@link ClientHttpRequestFactory} implementation with basic HTTP authentication. * This class gets the credentials from {@link TaxiiServiceSettings}. */ public class BasicAuthHttpRequestFactory extends HttpComponentsClientHttpRequestFactory { private final CredentialsProvider credsProvider; private final AuthCache authCache;
// Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // } // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/BasicAuthHttpRequestFactory.java import java.net.URI; import java.net.URL; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import org.apache.http.HttpHost; import org.apache.http.client.AuthCache; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicAuthCache; import org.apache.http.protocol.HttpContext; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.httpclient; /** * {@link ClientHttpRequestFactory} implementation with basic HTTP authentication. * This class gets the credentials from {@link TaxiiServiceSettings}. */ public class BasicAuthHttpRequestFactory extends HttpComponentsClientHttpRequestFactory { private final CredentialsProvider credsProvider; private final AuthCache authCache;
public BasicAuthHttpRequestFactory(HttpClient httpClient, TaxiiServiceSettings settings, CredentialsProvider credsProvider) {
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/RequestFactory.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpBodyWriter.java // public class HttpBodyWriter { // // private static final String UTF_8 = "UTF-8"; // // private final Configuration cfg; // private final Template template; // private final Template templateFulfillment; // // public HttpBodyWriter() throws IOException { // cfg = new Configuration(new Version(2, 3, 21)); // cfg.setDefaultEncoding(UTF_8); // cfg.setTemplateLoader(new ClassTemplateLoader(HttpBodyWriter.class, "templates")); // template = cfg.getTemplate("poll-request.ftl"); // templateFulfillment = cfg.getTemplate("poll-fulfillment-request.ftl"); // } // // /** // * Write the TAXII poll request to an {@link OutputStream}. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed. // * @param body The {@link OutputStream} to write the body to. // * @throws Exception When any error occurs. // */ // public void write(String messageId, TaxiiStatus.Feed feed, OutputStream body) throws Exception { // try (OutputStreamWriter out = new OutputStreamWriter(body, UTF_8)) { // Map<String, Object> data = new HashMap<>(); // data.put("messageId", messageId); // data.put("collection", feed.getName()); // XMLGregorianCalendar lastUpdate = getLastUpdate(feed); // if (lastUpdate != null) { // data.put("begin", lastUpdate.toXMLFormat()); // } // template.process(data, out); // } // } // // /** // * Write the TAXII poll fulfillment request to an {@link OutputStream}. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed. // * @param resultId result id. // * @param resultPartNumber result part number. // * @param body The {@link OutputStream} to write the body to. // * @throws Exception When any error occurs. // */ // public void write(String messageId, TaxiiStatus.Feed feed, String resultId, Integer resultPartNumber, OutputStream body) throws Exception { // try (OutputStreamWriter out = new OutputStreamWriter(body, UTF_8)) { // Map<String, Object> data = new HashMap<>(); // data.put("messageId", messageId); // data.put("collection", feed.getName()); // data.put("resultId", resultId); // data.put("resultPartNumber", resultPartNumber); // templateFulfillment.process(data, out); // } // } // // private XMLGregorianCalendar getLastUpdate(TaxiiStatus.Feed feed) { // if (feed != null && feed.getLastUpdate() != null) { // return feed.getLastUpdate(); // } else { // return null; // } // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpHeadersAppender.java // public class HttpHeadersAppender { // // public void appendTo(HttpHeaders headers) { // headers.setContentType(MediaType.APPLICATION_XML); // headers.setAccept(ImmutableList.of(MediaType.APPLICATION_XML)); // headers.set("X-Taxii-Accept", "urn:taxii.mitre.org:message:xml:1.1"); // headers.set("X-TAXII-Content-Type", "urn:taxii.mitre.org:message:xml:1.1"); // headers.set("X-Taxii-Protocol", "urn:taxii.mitre.org:protocol:https:1.0"); // headers.set("X-TAXII-Services", "urn:taxii.mitre.org:services:1.1"); // headers.set("User-Agent", "taxii-log-adapter-" + Version.getImplVersion()); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // }
import com.cisco.cta.taxii.adapter.httpclient.HttpBodyWriter; import com.cisco.cta.taxii.adapter.httpclient.HttpHeadersAppender; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import lombok.AllArgsConstructor; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import java.net.URL;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Factory to create complete TAXII requests. */ @AllArgsConstructor public class RequestFactory { private final URL pollEndpoint; private final ClientHttpRequestFactory httpRequestFactory;
// Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpBodyWriter.java // public class HttpBodyWriter { // // private static final String UTF_8 = "UTF-8"; // // private final Configuration cfg; // private final Template template; // private final Template templateFulfillment; // // public HttpBodyWriter() throws IOException { // cfg = new Configuration(new Version(2, 3, 21)); // cfg.setDefaultEncoding(UTF_8); // cfg.setTemplateLoader(new ClassTemplateLoader(HttpBodyWriter.class, "templates")); // template = cfg.getTemplate("poll-request.ftl"); // templateFulfillment = cfg.getTemplate("poll-fulfillment-request.ftl"); // } // // /** // * Write the TAXII poll request to an {@link OutputStream}. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed. // * @param body The {@link OutputStream} to write the body to. // * @throws Exception When any error occurs. // */ // public void write(String messageId, TaxiiStatus.Feed feed, OutputStream body) throws Exception { // try (OutputStreamWriter out = new OutputStreamWriter(body, UTF_8)) { // Map<String, Object> data = new HashMap<>(); // data.put("messageId", messageId); // data.put("collection", feed.getName()); // XMLGregorianCalendar lastUpdate = getLastUpdate(feed); // if (lastUpdate != null) { // data.put("begin", lastUpdate.toXMLFormat()); // } // template.process(data, out); // } // } // // /** // * Write the TAXII poll fulfillment request to an {@link OutputStream}. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed. // * @param resultId result id. // * @param resultPartNumber result part number. // * @param body The {@link OutputStream} to write the body to. // * @throws Exception When any error occurs. // */ // public void write(String messageId, TaxiiStatus.Feed feed, String resultId, Integer resultPartNumber, OutputStream body) throws Exception { // try (OutputStreamWriter out = new OutputStreamWriter(body, UTF_8)) { // Map<String, Object> data = new HashMap<>(); // data.put("messageId", messageId); // data.put("collection", feed.getName()); // data.put("resultId", resultId); // data.put("resultPartNumber", resultPartNumber); // templateFulfillment.process(data, out); // } // } // // private XMLGregorianCalendar getLastUpdate(TaxiiStatus.Feed feed) { // if (feed != null && feed.getLastUpdate() != null) { // return feed.getLastUpdate(); // } else { // return null; // } // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpHeadersAppender.java // public class HttpHeadersAppender { // // public void appendTo(HttpHeaders headers) { // headers.setContentType(MediaType.APPLICATION_XML); // headers.setAccept(ImmutableList.of(MediaType.APPLICATION_XML)); // headers.set("X-Taxii-Accept", "urn:taxii.mitre.org:message:xml:1.1"); // headers.set("X-TAXII-Content-Type", "urn:taxii.mitre.org:message:xml:1.1"); // headers.set("X-Taxii-Protocol", "urn:taxii.mitre.org:protocol:https:1.0"); // headers.set("X-TAXII-Services", "urn:taxii.mitre.org:services:1.1"); // headers.set("User-Agent", "taxii-log-adapter-" + Version.getImplVersion()); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // Path: src/main/java/com/cisco/cta/taxii/adapter/RequestFactory.java import com.cisco.cta.taxii.adapter.httpclient.HttpBodyWriter; import com.cisco.cta.taxii.adapter.httpclient.HttpHeadersAppender; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import lombok.AllArgsConstructor; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import java.net.URL; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Factory to create complete TAXII requests. */ @AllArgsConstructor public class RequestFactory { private final URL pollEndpoint; private final ClientHttpRequestFactory httpRequestFactory;
private final HttpHeadersAppender httpHeadersAppender;
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/RequestFactory.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpBodyWriter.java // public class HttpBodyWriter { // // private static final String UTF_8 = "UTF-8"; // // private final Configuration cfg; // private final Template template; // private final Template templateFulfillment; // // public HttpBodyWriter() throws IOException { // cfg = new Configuration(new Version(2, 3, 21)); // cfg.setDefaultEncoding(UTF_8); // cfg.setTemplateLoader(new ClassTemplateLoader(HttpBodyWriter.class, "templates")); // template = cfg.getTemplate("poll-request.ftl"); // templateFulfillment = cfg.getTemplate("poll-fulfillment-request.ftl"); // } // // /** // * Write the TAXII poll request to an {@link OutputStream}. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed. // * @param body The {@link OutputStream} to write the body to. // * @throws Exception When any error occurs. // */ // public void write(String messageId, TaxiiStatus.Feed feed, OutputStream body) throws Exception { // try (OutputStreamWriter out = new OutputStreamWriter(body, UTF_8)) { // Map<String, Object> data = new HashMap<>(); // data.put("messageId", messageId); // data.put("collection", feed.getName()); // XMLGregorianCalendar lastUpdate = getLastUpdate(feed); // if (lastUpdate != null) { // data.put("begin", lastUpdate.toXMLFormat()); // } // template.process(data, out); // } // } // // /** // * Write the TAXII poll fulfillment request to an {@link OutputStream}. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed. // * @param resultId result id. // * @param resultPartNumber result part number. // * @param body The {@link OutputStream} to write the body to. // * @throws Exception When any error occurs. // */ // public void write(String messageId, TaxiiStatus.Feed feed, String resultId, Integer resultPartNumber, OutputStream body) throws Exception { // try (OutputStreamWriter out = new OutputStreamWriter(body, UTF_8)) { // Map<String, Object> data = new HashMap<>(); // data.put("messageId", messageId); // data.put("collection", feed.getName()); // data.put("resultId", resultId); // data.put("resultPartNumber", resultPartNumber); // templateFulfillment.process(data, out); // } // } // // private XMLGregorianCalendar getLastUpdate(TaxiiStatus.Feed feed) { // if (feed != null && feed.getLastUpdate() != null) { // return feed.getLastUpdate(); // } else { // return null; // } // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpHeadersAppender.java // public class HttpHeadersAppender { // // public void appendTo(HttpHeaders headers) { // headers.setContentType(MediaType.APPLICATION_XML); // headers.setAccept(ImmutableList.of(MediaType.APPLICATION_XML)); // headers.set("X-Taxii-Accept", "urn:taxii.mitre.org:message:xml:1.1"); // headers.set("X-TAXII-Content-Type", "urn:taxii.mitre.org:message:xml:1.1"); // headers.set("X-Taxii-Protocol", "urn:taxii.mitre.org:protocol:https:1.0"); // headers.set("X-TAXII-Services", "urn:taxii.mitre.org:services:1.1"); // headers.set("User-Agent", "taxii-log-adapter-" + Version.getImplVersion()); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // }
import com.cisco.cta.taxii.adapter.httpclient.HttpBodyWriter; import com.cisco.cta.taxii.adapter.httpclient.HttpHeadersAppender; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import lombok.AllArgsConstructor; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import java.net.URL;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Factory to create complete TAXII requests. */ @AllArgsConstructor public class RequestFactory { private final URL pollEndpoint; private final ClientHttpRequestFactory httpRequestFactory; private final HttpHeadersAppender httpHeadersAppender;
// Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpBodyWriter.java // public class HttpBodyWriter { // // private static final String UTF_8 = "UTF-8"; // // private final Configuration cfg; // private final Template template; // private final Template templateFulfillment; // // public HttpBodyWriter() throws IOException { // cfg = new Configuration(new Version(2, 3, 21)); // cfg.setDefaultEncoding(UTF_8); // cfg.setTemplateLoader(new ClassTemplateLoader(HttpBodyWriter.class, "templates")); // template = cfg.getTemplate("poll-request.ftl"); // templateFulfillment = cfg.getTemplate("poll-fulfillment-request.ftl"); // } // // /** // * Write the TAXII poll request to an {@link OutputStream}. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed. // * @param body The {@link OutputStream} to write the body to. // * @throws Exception When any error occurs. // */ // public void write(String messageId, TaxiiStatus.Feed feed, OutputStream body) throws Exception { // try (OutputStreamWriter out = new OutputStreamWriter(body, UTF_8)) { // Map<String, Object> data = new HashMap<>(); // data.put("messageId", messageId); // data.put("collection", feed.getName()); // XMLGregorianCalendar lastUpdate = getLastUpdate(feed); // if (lastUpdate != null) { // data.put("begin", lastUpdate.toXMLFormat()); // } // template.process(data, out); // } // } // // /** // * Write the TAXII poll fulfillment request to an {@link OutputStream}. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed. // * @param resultId result id. // * @param resultPartNumber result part number. // * @param body The {@link OutputStream} to write the body to. // * @throws Exception When any error occurs. // */ // public void write(String messageId, TaxiiStatus.Feed feed, String resultId, Integer resultPartNumber, OutputStream body) throws Exception { // try (OutputStreamWriter out = new OutputStreamWriter(body, UTF_8)) { // Map<String, Object> data = new HashMap<>(); // data.put("messageId", messageId); // data.put("collection", feed.getName()); // data.put("resultId", resultId); // data.put("resultPartNumber", resultPartNumber); // templateFulfillment.process(data, out); // } // } // // private XMLGregorianCalendar getLastUpdate(TaxiiStatus.Feed feed) { // if (feed != null && feed.getLastUpdate() != null) { // return feed.getLastUpdate(); // } else { // return null; // } // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpHeadersAppender.java // public class HttpHeadersAppender { // // public void appendTo(HttpHeaders headers) { // headers.setContentType(MediaType.APPLICATION_XML); // headers.setAccept(ImmutableList.of(MediaType.APPLICATION_XML)); // headers.set("X-Taxii-Accept", "urn:taxii.mitre.org:message:xml:1.1"); // headers.set("X-TAXII-Content-Type", "urn:taxii.mitre.org:message:xml:1.1"); // headers.set("X-Taxii-Protocol", "urn:taxii.mitre.org:protocol:https:1.0"); // headers.set("X-TAXII-Services", "urn:taxii.mitre.org:services:1.1"); // headers.set("User-Agent", "taxii-log-adapter-" + Version.getImplVersion()); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // Path: src/main/java/com/cisco/cta/taxii/adapter/RequestFactory.java import com.cisco.cta.taxii.adapter.httpclient.HttpBodyWriter; import com.cisco.cta.taxii.adapter.httpclient.HttpHeadersAppender; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import lombok.AllArgsConstructor; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import java.net.URL; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Factory to create complete TAXII requests. */ @AllArgsConstructor public class RequestFactory { private final URL pollEndpoint; private final ClientHttpRequestFactory httpRequestFactory; private final HttpHeadersAppender httpHeadersAppender;
private final HttpBodyWriter httpBodyWriter;
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/RequestFactory.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpBodyWriter.java // public class HttpBodyWriter { // // private static final String UTF_8 = "UTF-8"; // // private final Configuration cfg; // private final Template template; // private final Template templateFulfillment; // // public HttpBodyWriter() throws IOException { // cfg = new Configuration(new Version(2, 3, 21)); // cfg.setDefaultEncoding(UTF_8); // cfg.setTemplateLoader(new ClassTemplateLoader(HttpBodyWriter.class, "templates")); // template = cfg.getTemplate("poll-request.ftl"); // templateFulfillment = cfg.getTemplate("poll-fulfillment-request.ftl"); // } // // /** // * Write the TAXII poll request to an {@link OutputStream}. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed. // * @param body The {@link OutputStream} to write the body to. // * @throws Exception When any error occurs. // */ // public void write(String messageId, TaxiiStatus.Feed feed, OutputStream body) throws Exception { // try (OutputStreamWriter out = new OutputStreamWriter(body, UTF_8)) { // Map<String, Object> data = new HashMap<>(); // data.put("messageId", messageId); // data.put("collection", feed.getName()); // XMLGregorianCalendar lastUpdate = getLastUpdate(feed); // if (lastUpdate != null) { // data.put("begin", lastUpdate.toXMLFormat()); // } // template.process(data, out); // } // } // // /** // * Write the TAXII poll fulfillment request to an {@link OutputStream}. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed. // * @param resultId result id. // * @param resultPartNumber result part number. // * @param body The {@link OutputStream} to write the body to. // * @throws Exception When any error occurs. // */ // public void write(String messageId, TaxiiStatus.Feed feed, String resultId, Integer resultPartNumber, OutputStream body) throws Exception { // try (OutputStreamWriter out = new OutputStreamWriter(body, UTF_8)) { // Map<String, Object> data = new HashMap<>(); // data.put("messageId", messageId); // data.put("collection", feed.getName()); // data.put("resultId", resultId); // data.put("resultPartNumber", resultPartNumber); // templateFulfillment.process(data, out); // } // } // // private XMLGregorianCalendar getLastUpdate(TaxiiStatus.Feed feed) { // if (feed != null && feed.getLastUpdate() != null) { // return feed.getLastUpdate(); // } else { // return null; // } // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpHeadersAppender.java // public class HttpHeadersAppender { // // public void appendTo(HttpHeaders headers) { // headers.setContentType(MediaType.APPLICATION_XML); // headers.setAccept(ImmutableList.of(MediaType.APPLICATION_XML)); // headers.set("X-Taxii-Accept", "urn:taxii.mitre.org:message:xml:1.1"); // headers.set("X-TAXII-Content-Type", "urn:taxii.mitre.org:message:xml:1.1"); // headers.set("X-Taxii-Protocol", "urn:taxii.mitre.org:protocol:https:1.0"); // headers.set("X-TAXII-Services", "urn:taxii.mitre.org:services:1.1"); // headers.set("User-Agent", "taxii-log-adapter-" + Version.getImplVersion()); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // }
import com.cisco.cta.taxii.adapter.httpclient.HttpBodyWriter; import com.cisco.cta.taxii.adapter.httpclient.HttpHeadersAppender; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import lombok.AllArgsConstructor; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import java.net.URL;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Factory to create complete TAXII requests. */ @AllArgsConstructor public class RequestFactory { private final URL pollEndpoint; private final ClientHttpRequestFactory httpRequestFactory; private final HttpHeadersAppender httpHeadersAppender; private final HttpBodyWriter httpBodyWriter; /** * Create the TAXII request. * * @param messageId TAXII message id. * @param feed The TAXII feed. * @return TAXII poll request. * @throws Exception When any error occurs. */
// Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpBodyWriter.java // public class HttpBodyWriter { // // private static final String UTF_8 = "UTF-8"; // // private final Configuration cfg; // private final Template template; // private final Template templateFulfillment; // // public HttpBodyWriter() throws IOException { // cfg = new Configuration(new Version(2, 3, 21)); // cfg.setDefaultEncoding(UTF_8); // cfg.setTemplateLoader(new ClassTemplateLoader(HttpBodyWriter.class, "templates")); // template = cfg.getTemplate("poll-request.ftl"); // templateFulfillment = cfg.getTemplate("poll-fulfillment-request.ftl"); // } // // /** // * Write the TAXII poll request to an {@link OutputStream}. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed. // * @param body The {@link OutputStream} to write the body to. // * @throws Exception When any error occurs. // */ // public void write(String messageId, TaxiiStatus.Feed feed, OutputStream body) throws Exception { // try (OutputStreamWriter out = new OutputStreamWriter(body, UTF_8)) { // Map<String, Object> data = new HashMap<>(); // data.put("messageId", messageId); // data.put("collection", feed.getName()); // XMLGregorianCalendar lastUpdate = getLastUpdate(feed); // if (lastUpdate != null) { // data.put("begin", lastUpdate.toXMLFormat()); // } // template.process(data, out); // } // } // // /** // * Write the TAXII poll fulfillment request to an {@link OutputStream}. // * // * @param messageId TAXII message id. // * @param feed The TAXII feed. // * @param resultId result id. // * @param resultPartNumber result part number. // * @param body The {@link OutputStream} to write the body to. // * @throws Exception When any error occurs. // */ // public void write(String messageId, TaxiiStatus.Feed feed, String resultId, Integer resultPartNumber, OutputStream body) throws Exception { // try (OutputStreamWriter out = new OutputStreamWriter(body, UTF_8)) { // Map<String, Object> data = new HashMap<>(); // data.put("messageId", messageId); // data.put("collection", feed.getName()); // data.put("resultId", resultId); // data.put("resultPartNumber", resultPartNumber); // templateFulfillment.process(data, out); // } // } // // private XMLGregorianCalendar getLastUpdate(TaxiiStatus.Feed feed) { // if (feed != null && feed.getLastUpdate() != null) { // return feed.getLastUpdate(); // } else { // return null; // } // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/httpclient/HttpHeadersAppender.java // public class HttpHeadersAppender { // // public void appendTo(HttpHeaders headers) { // headers.setContentType(MediaType.APPLICATION_XML); // headers.setAccept(ImmutableList.of(MediaType.APPLICATION_XML)); // headers.set("X-Taxii-Accept", "urn:taxii.mitre.org:message:xml:1.1"); // headers.set("X-TAXII-Content-Type", "urn:taxii.mitre.org:message:xml:1.1"); // headers.set("X-Taxii-Protocol", "urn:taxii.mitre.org:protocol:https:1.0"); // headers.set("X-TAXII-Services", "urn:taxii.mitre.org:services:1.1"); // headers.set("User-Agent", "taxii-log-adapter-" + Version.getImplVersion()); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // Path: src/main/java/com/cisco/cta/taxii/adapter/RequestFactory.java import com.cisco.cta.taxii.adapter.httpclient.HttpBodyWriter; import com.cisco.cta.taxii.adapter.httpclient.HttpHeadersAppender; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import lombok.AllArgsConstructor; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import java.net.URL; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Factory to create complete TAXII requests. */ @AllArgsConstructor public class RequestFactory { private final URL pollEndpoint; private final ClientHttpRequestFactory httpRequestFactory; private final HttpHeadersAppender httpHeadersAppender; private final HttpBodyWriter httpBodyWriter; /** * Create the TAXII request. * * @param messageId TAXII message id. * @param feed The TAXII feed. * @return TAXII poll request. * @throws Exception When any error occurs. */
public ClientHttpRequest createPollRequest(String messageId, TaxiiStatus.Feed feed) throws Exception {
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // }
import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus.Feed; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.persistence; /** * Data access object to persist consumption status of the TAXII service. */ public class TaxiiStatusDao { private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); private final TaxiiStatusFileHandler fileHandler; private TaxiiStatus dirtyStatus; public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { this.fileHandler = fileHandler; dirtyStatus = fileHandler.load(); if (dirtyStatus == null) { LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); dirtyStatus = new TaxiiStatus(); } else { LOG.debug("TAXII status file loaded: {}", dirtyStatus); } }
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus.Feed; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.persistence; /** * Data access object to persist consumption status of the TAXII service. */ public class TaxiiStatusDao { private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); private final TaxiiStatusFileHandler fileHandler; private TaxiiStatus dirtyStatus; public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { this.fileHandler = fileHandler; dirtyStatus = fileHandler.load(); if (dirtyStatus == null) { LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); dirtyStatus = new TaxiiStatus(); } else { LOG.debug("TAXII status file loaded: {}", dirtyStatus); } }
public Feed find(String feedName) {
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/AdapterTask.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // }
import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpResponse; import javax.xml.datatype.XMLGregorianCalendar; import java.io.IOException; import java.util.List; import java.util.UUID;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Wraps everything what has to be triggered by a scheduler. */ public class AdapterTask implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(AdapterTask.class); private static final String MESSAGE_ID_PREFIX = "tla-"; private static final Integer MAX_HTTP_CONNECTION_ATTEMPTS = 3; private final RequestFactory requestFactory; private final ResponseTransformer responseTransformer; private final List<String> feeds; private final AdapterStatistics statistics;
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // } // Path: src/main/java/com/cisco/cta/taxii/adapter/AdapterTask.java import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpResponse; import javax.xml.datatype.XMLGregorianCalendar; import java.io.IOException; import java.util.List; import java.util.UUID; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Wraps everything what has to be triggered by a scheduler. */ public class AdapterTask implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(AdapterTask.class); private static final String MESSAGE_ID_PREFIX = "tla-"; private static final Integer MAX_HTTP_CONNECTION_ATTEMPTS = 3; private final RequestFactory requestFactory; private final ResponseTransformer responseTransformer; private final List<String> feeds; private final AdapterStatistics statistics;
private final TaxiiStatusDao taxiiStatusDao;
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/AdapterTask.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // }
import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpResponse; import javax.xml.datatype.XMLGregorianCalendar; import java.io.IOException; import java.util.List; import java.util.UUID;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Wraps everything what has to be triggered by a scheduler. */ public class AdapterTask implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(AdapterTask.class); private static final String MESSAGE_ID_PREFIX = "tla-"; private static final Integer MAX_HTTP_CONNECTION_ATTEMPTS = 3; private final RequestFactory requestFactory; private final ResponseTransformer responseTransformer; private final List<String> feeds; private final AdapterStatistics statistics; private final TaxiiStatusDao taxiiStatusDao;
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // } // Path: src/main/java/com/cisco/cta/taxii/adapter/AdapterTask.java import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpResponse; import javax.xml.datatype.XMLGregorianCalendar; import java.io.IOException; import java.util.List; import java.util.UUID; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Wraps everything what has to be triggered by a scheduler. */ public class AdapterTask implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(AdapterTask.class); private static final String MESSAGE_ID_PREFIX = "tla-"; private static final Integer MAX_HTTP_CONNECTION_ATTEMPTS = 3; private final RequestFactory requestFactory; private final ResponseTransformer responseTransformer; private final List<String> feeds; private final AdapterStatistics statistics; private final TaxiiStatusDao taxiiStatusDao;
public AdapterTask(RequestFactory requestFactory, ResponseTransformer responseTransformer, TaxiiServiceSettings settings, AdapterStatistics statistics, TaxiiStatusDao taxiiStatusDao) {
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/AdapterTask.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // }
import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpResponse; import javax.xml.datatype.XMLGregorianCalendar; import java.io.IOException; import java.util.List; import java.util.UUID;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Wraps everything what has to be triggered by a scheduler. */ public class AdapterTask implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(AdapterTask.class); private static final String MESSAGE_ID_PREFIX = "tla-"; private static final Integer MAX_HTTP_CONNECTION_ATTEMPTS = 3; private final RequestFactory requestFactory; private final ResponseTransformer responseTransformer; private final List<String> feeds; private final AdapterStatistics statistics; private final TaxiiStatusDao taxiiStatusDao; public AdapterTask(RequestFactory requestFactory, ResponseTransformer responseTransformer, TaxiiServiceSettings settings, AdapterStatistics statistics, TaxiiStatusDao taxiiStatusDao) { this.requestFactory = requestFactory; this.responseTransformer = responseTransformer; this.feeds = settings.getFeeds(); this.statistics = statistics; this.taxiiStatusDao = taxiiStatusDao; } private String createMessageId() { return MESSAGE_ID_PREFIX + UUID.randomUUID().toString(); } /** * Invoked by the scheduler. */ @Override public void run() { LOG.trace("triggering task..."); feeds.parallelStream().forEach(this::downloadFeed); } private void downloadFeed(String feedName) { try { MDC.put("feed", feedName);
// Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatus.java // @Data // @XmlRootElement(name="taxii-status") // @XmlAccessorType(XmlAccessType.NONE) // public class TaxiiStatus { // // @XmlElement // private final List<Feed> feed = new ArrayList<>(); // // // /** // * JAXB annotated class holding consumption status of a single TAXII feed. // * @see TaxiiStatusDao // */ // @Data // @XmlAccessorType(XmlAccessType.NONE) // public static class Feed { // // @XmlAttribute // private String name; // // @XmlAttribute // private XMLGregorianCalendar lastUpdate; // // @XmlAttribute // private Boolean more; // // @XmlAttribute // private String resultId; // // @XmlAttribute // private Integer resultPartNumber; // // @XmlAttribute // private Integer ioErrorCount; // // } // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/persistence/TaxiiStatusDao.java // public class TaxiiStatusDao { // // private static final Logger LOG = LoggerFactory.getLogger(TaxiiStatusDao.class); // // private final TaxiiStatusFileHandler fileHandler; // private TaxiiStatus dirtyStatus; // // public TaxiiStatusDao(TaxiiStatusFileHandler fileHandler) { // this.fileHandler = fileHandler; // dirtyStatus = fileHandler.load(); // if (dirtyStatus == null) { // LOG.warn("TAXII status file not found, all feeds will be fully downloaded"); // dirtyStatus = new TaxiiStatus(); // } else { // LOG.debug("TAXII status file loaded: {}", dirtyStatus); // } // } // // public Feed find(String feedName) { // for (Feed feed : dirtyStatus.getFeed()) { // if (feed.getName().equals(feedName)) { // return feed; // } // } // return null; // } // // public synchronized void updateOrAdd(Feed feed) { // Feed savedFeed = find(feed.getName()); // if (savedFeed != null) { // savedFeed.setMore(feed.getMore()); // savedFeed.setResultId(feed.getResultId()); // savedFeed.setResultPartNumber(feed.getResultPartNumber()); // savedFeed.setLastUpdate(feed.getLastUpdate()); // } else { // dirtyStatus.getFeed().add(feed); // } // fileHandler.save(dirtyStatus); // } // // } // // Path: src/main/java/com/cisco/cta/taxii/adapter/settings/TaxiiServiceSettings.java // @ConfigurationProperties(prefix="taxii-service") // @Data // @Validated // public class TaxiiServiceSettings { // // private static final Charset UTF8 = Charset.forName("UTF-8"); // // @NotNull // private URL pollEndpoint; // // @NotNull // private String username; // // @NotNull // private String password; // // private List<String> feeds; // // private File feedNamesFile; // // private File statusFile = new File("taxii-status.xml"); // // @PostConstruct // public void loadFeedNames() throws IOException { // Preconditions.checkState( // feeds != null ^ feedNamesFile != null, // "taxii-service.feeds or taxii-service.feedNamesFile must be set"); // if (feedNamesFile != null) { // feeds = Files.readLines(feedNamesFile, UTF8); // } // } // } // Path: src/main/java/com/cisco/cta/taxii/adapter/AdapterTask.java import com.cisco.cta.taxii.adapter.persistence.TaxiiStatus; import com.cisco.cta.taxii.adapter.persistence.TaxiiStatusDao; import com.cisco.cta.taxii.adapter.settings.TaxiiServiceSettings; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpResponse; import javax.xml.datatype.XMLGregorianCalendar; import java.io.IOException; import java.util.List; import java.util.UUID; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter; /** * Wraps everything what has to be triggered by a scheduler. */ public class AdapterTask implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(AdapterTask.class); private static final String MESSAGE_ID_PREFIX = "tla-"; private static final Integer MAX_HTTP_CONNECTION_ATTEMPTS = 3; private final RequestFactory requestFactory; private final ResponseTransformer responseTransformer; private final List<String> feeds; private final AdapterStatistics statistics; private final TaxiiStatusDao taxiiStatusDao; public AdapterTask(RequestFactory requestFactory, ResponseTransformer responseTransformer, TaxiiServiceSettings settings, AdapterStatistics statistics, TaxiiStatusDao taxiiStatusDao) { this.requestFactory = requestFactory; this.responseTransformer = responseTransformer; this.feeds = settings.getFeeds(); this.statistics = statistics; this.taxiiStatusDao = taxiiStatusDao; } private String createMessageId() { return MESSAGE_ID_PREFIX + UUID.randomUUID().toString(); } /** * Invoked by the scheduler. */ @Override public void run() { LOG.trace("triggering task..."); feeds.parallelStream().forEach(this::downloadFeed); } private void downloadFeed(String feedName) { try { MDC.put("feed", feedName);
TaxiiStatus.Feed feed = taxiiStatusDao.find(feedName);
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/filter/JsonValidationFilterTest.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/OutputValidationException.java // public class OutputValidationException extends RuntimeException { // public static final String MDC_KEY = "OutputValidationException"; // // public OutputValidationException(String message) { // super("Output validation failed: " + message); // } // // }
import static org.hamcrest.core.IsNull.notNullValue; import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.core.spi.FilterReply; import com.cisco.cta.taxii.adapter.OutputValidationException; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.slf4j.MDC; import java.io.IOException; import java.io.InputStream; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.core.Is.is;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.filter; public class JsonValidationFilterTest { private JsonValidationFilter jsonValidationFilter = new JsonValidationFilter(); private String readFirstLine(String resource) throws IOException { try(InputStream istream = getClass().getResourceAsStream(resource)) { List<String> lines = IOUtils.readLines(istream); return lines.get(0); } } @Test public void decideValidJson() throws IOException { LoggingEvent loggingEvent = new LoggingEvent(); loggingEvent.setMessage(readFirstLine("/valid-json.json")); FilterReply reply = jsonValidationFilter.decide(loggingEvent); assertThat(reply, is(FilterReply.ACCEPT));
// Path: src/main/java/com/cisco/cta/taxii/adapter/OutputValidationException.java // public class OutputValidationException extends RuntimeException { // public static final String MDC_KEY = "OutputValidationException"; // // public OutputValidationException(String message) { // super("Output validation failed: " + message); // } // // } // Path: src/test/java/com/cisco/cta/taxii/adapter/filter/JsonValidationFilterTest.java import static org.hamcrest.core.IsNull.notNullValue; import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.core.spi.FilterReply; import com.cisco.cta.taxii.adapter.OutputValidationException; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.slf4j.MDC; import java.io.IOException; import java.io.InputStream; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.core.Is.is; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.filter; public class JsonValidationFilterTest { private JsonValidationFilter jsonValidationFilter = new JsonValidationFilter(); private String readFirstLine(String resource) throws IOException { try(InputStream istream = getClass().getResourceAsStream(resource)) { List<String> lines = IOUtils.readLines(istream); return lines.get(0); } } @Test public void decideValidJson() throws IOException { LoggingEvent loggingEvent = new LoggingEvent(); loggingEvent.setMessage(readFirstLine("/valid-json.json")); FilterReply reply = jsonValidationFilter.decide(loggingEvent); assertThat(reply, is(FilterReply.ACCEPT));
assertThat(MDC.get(OutputValidationException.MDC_KEY), nullValue());
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/AdapterTaskMultipartIT.java
// Path: src/test/java/com/cisco/cta/taxii/adapter/PollFulfillmentMatcher.java // public static PollFulfillmentMatcher pollFulfillment(String messageId, String collection, String resultId, String resultPartNumber) { // return new PollFulfillmentMatcher(messageId, collection, resultId, resultPartNumber); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher initialPollRequest(String messageId, String collection) { // return new PollRequestMatcher(messageId, collection, null); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HasHeaderMatcher.java // public static Matcher<HttpHeaders> hasAllTaxiiHeaders() { // return allOf( // hasHeader("Content-Type", is("application/xml")), // hasHeader("Accept", is("application/xml")), // hasHeader("X-Taxii-Accept", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-TAXII-Content-Type", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-Taxii-Protocol", is("urn:taxii.mitre.org:protocol:https:1.0")), // hasHeader("X-TAXII-Services", is("urn:taxii.mitre.org:services:1.1")) // ); // }
import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpResponse; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import static com.cisco.cta.taxii.adapter.PollFulfillmentMatcher.pollFulfillment; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.initialPollRequest; import static com.cisco.cta.taxii.adapter.httpclient.HasHeaderMatcher.hasAllTaxiiHeaders; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); context.reset(); configurator.doConfigure("src/test/resources/logback-test.xml"); } @After public void tearDown() throws Exception { taxiiPollRespBodyInitial.close(); taxiiPollRespBodyNext.close(); } @Test public void runFromEpochBegin() throws Exception { initialMultipartRequestResponse(); assertThat(statistics.getPolls(), is(2L)); assertThat(statistics.getLogs(), is(2L)); assertThat(statistics.getErrors(), is(0L)); assertThat(OUTPUT_FILE + " content expected same as " + EXPECTED_OUTPUT_FILE, FileUtils.readFileToString(OUTPUT_FILE), is(FileUtils.readFileToString(EXPECTED_OUTPUT_FILE))); } private void initialMultipartRequestResponse() throws IOException { when(httpResp.getRawStatusCode()).thenReturn(200); when(httpResp.getBody()).thenReturn(taxiiPollRespBodyInitial); when(httpResp2.getRawStatusCode()).thenReturn(200); when(httpResp2.getBody()).thenReturn(taxiiPollRespBodyNext); task.run(); verify(httpRequestFactory, times(2)).createRequest(pollServiceUri, HttpMethod.POST);
// Path: src/test/java/com/cisco/cta/taxii/adapter/PollFulfillmentMatcher.java // public static PollFulfillmentMatcher pollFulfillment(String messageId, String collection, String resultId, String resultPartNumber) { // return new PollFulfillmentMatcher(messageId, collection, resultId, resultPartNumber); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher initialPollRequest(String messageId, String collection) { // return new PollRequestMatcher(messageId, collection, null); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HasHeaderMatcher.java // public static Matcher<HttpHeaders> hasAllTaxiiHeaders() { // return allOf( // hasHeader("Content-Type", is("application/xml")), // hasHeader("Accept", is("application/xml")), // hasHeader("X-Taxii-Accept", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-TAXII-Content-Type", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-Taxii-Protocol", is("urn:taxii.mitre.org:protocol:https:1.0")), // hasHeader("X-TAXII-Services", is("urn:taxii.mitre.org:services:1.1")) // ); // } // Path: src/test/java/com/cisco/cta/taxii/adapter/AdapterTaskMultipartIT.java import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpResponse; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import static com.cisco.cta.taxii.adapter.PollFulfillmentMatcher.pollFulfillment; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.initialPollRequest; import static com.cisco.cta.taxii.adapter.httpclient.HasHeaderMatcher.hasAllTaxiiHeaders; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); context.reset(); configurator.doConfigure("src/test/resources/logback-test.xml"); } @After public void tearDown() throws Exception { taxiiPollRespBodyInitial.close(); taxiiPollRespBodyNext.close(); } @Test public void runFromEpochBegin() throws Exception { initialMultipartRequestResponse(); assertThat(statistics.getPolls(), is(2L)); assertThat(statistics.getLogs(), is(2L)); assertThat(statistics.getErrors(), is(0L)); assertThat(OUTPUT_FILE + " content expected same as " + EXPECTED_OUTPUT_FILE, FileUtils.readFileToString(OUTPUT_FILE), is(FileUtils.readFileToString(EXPECTED_OUTPUT_FILE))); } private void initialMultipartRequestResponse() throws IOException { when(httpResp.getRawStatusCode()).thenReturn(200); when(httpResp.getBody()).thenReturn(taxiiPollRespBodyInitial); when(httpResp2.getRawStatusCode()).thenReturn(200); when(httpResp2.getBody()).thenReturn(taxiiPollRespBodyNext); task.run(); verify(httpRequestFactory, times(2)).createRequest(pollServiceUri, HttpMethod.POST);
assertThat(httpReqHeaders, hasAllTaxiiHeaders());
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/AdapterTaskMultipartIT.java
// Path: src/test/java/com/cisco/cta/taxii/adapter/PollFulfillmentMatcher.java // public static PollFulfillmentMatcher pollFulfillment(String messageId, String collection, String resultId, String resultPartNumber) { // return new PollFulfillmentMatcher(messageId, collection, resultId, resultPartNumber); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher initialPollRequest(String messageId, String collection) { // return new PollRequestMatcher(messageId, collection, null); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HasHeaderMatcher.java // public static Matcher<HttpHeaders> hasAllTaxiiHeaders() { // return allOf( // hasHeader("Content-Type", is("application/xml")), // hasHeader("Accept", is("application/xml")), // hasHeader("X-Taxii-Accept", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-TAXII-Content-Type", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-Taxii-Protocol", is("urn:taxii.mitre.org:protocol:https:1.0")), // hasHeader("X-TAXII-Services", is("urn:taxii.mitre.org:services:1.1")) // ); // }
import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpResponse; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import static com.cisco.cta.taxii.adapter.PollFulfillmentMatcher.pollFulfillment; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.initialPollRequest; import static com.cisco.cta.taxii.adapter.httpclient.HasHeaderMatcher.hasAllTaxiiHeaders; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
context.reset(); configurator.doConfigure("src/test/resources/logback-test.xml"); } @After public void tearDown() throws Exception { taxiiPollRespBodyInitial.close(); taxiiPollRespBodyNext.close(); } @Test public void runFromEpochBegin() throws Exception { initialMultipartRequestResponse(); assertThat(statistics.getPolls(), is(2L)); assertThat(statistics.getLogs(), is(2L)); assertThat(statistics.getErrors(), is(0L)); assertThat(OUTPUT_FILE + " content expected same as " + EXPECTED_OUTPUT_FILE, FileUtils.readFileToString(OUTPUT_FILE), is(FileUtils.readFileToString(EXPECTED_OUTPUT_FILE))); } private void initialMultipartRequestResponse() throws IOException { when(httpResp.getRawStatusCode()).thenReturn(200); when(httpResp.getBody()).thenReturn(taxiiPollRespBodyInitial); when(httpResp2.getRawStatusCode()).thenReturn(200); when(httpResp2.getBody()).thenReturn(taxiiPollRespBodyNext); task.run(); verify(httpRequestFactory, times(2)).createRequest(pollServiceUri, HttpMethod.POST); assertThat(httpReqHeaders, hasAllTaxiiHeaders()); verify(httpReq).execute(); verify(httpReq2).execute();
// Path: src/test/java/com/cisco/cta/taxii/adapter/PollFulfillmentMatcher.java // public static PollFulfillmentMatcher pollFulfillment(String messageId, String collection, String resultId, String resultPartNumber) { // return new PollFulfillmentMatcher(messageId, collection, resultId, resultPartNumber); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher initialPollRequest(String messageId, String collection) { // return new PollRequestMatcher(messageId, collection, null); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HasHeaderMatcher.java // public static Matcher<HttpHeaders> hasAllTaxiiHeaders() { // return allOf( // hasHeader("Content-Type", is("application/xml")), // hasHeader("Accept", is("application/xml")), // hasHeader("X-Taxii-Accept", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-TAXII-Content-Type", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-Taxii-Protocol", is("urn:taxii.mitre.org:protocol:https:1.0")), // hasHeader("X-TAXII-Services", is("urn:taxii.mitre.org:services:1.1")) // ); // } // Path: src/test/java/com/cisco/cta/taxii/adapter/AdapterTaskMultipartIT.java import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpResponse; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import static com.cisco.cta.taxii.adapter.PollFulfillmentMatcher.pollFulfillment; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.initialPollRequest; import static com.cisco.cta.taxii.adapter.httpclient.HasHeaderMatcher.hasAllTaxiiHeaders; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; context.reset(); configurator.doConfigure("src/test/resources/logback-test.xml"); } @After public void tearDown() throws Exception { taxiiPollRespBodyInitial.close(); taxiiPollRespBodyNext.close(); } @Test public void runFromEpochBegin() throws Exception { initialMultipartRequestResponse(); assertThat(statistics.getPolls(), is(2L)); assertThat(statistics.getLogs(), is(2L)); assertThat(statistics.getErrors(), is(0L)); assertThat(OUTPUT_FILE + " content expected same as " + EXPECTED_OUTPUT_FILE, FileUtils.readFileToString(OUTPUT_FILE), is(FileUtils.readFileToString(EXPECTED_OUTPUT_FILE))); } private void initialMultipartRequestResponse() throws IOException { when(httpResp.getRawStatusCode()).thenReturn(200); when(httpResp.getBody()).thenReturn(taxiiPollRespBodyInitial); when(httpResp2.getRawStatusCode()).thenReturn(200); when(httpResp2.getBody()).thenReturn(taxiiPollRespBodyNext); task.run(); verify(httpRequestFactory, times(2)).createRequest(pollServiceUri, HttpMethod.POST); assertThat(httpReqHeaders, hasAllTaxiiHeaders()); verify(httpReq).execute(); verify(httpReq2).execute();
assertThat(httpReqBody, is(initialPollRequest("123", "collection_name")));
CiscoCTA/taxii-log-adapter
src/test/java/com/cisco/cta/taxii/adapter/AdapterTaskMultipartIT.java
// Path: src/test/java/com/cisco/cta/taxii/adapter/PollFulfillmentMatcher.java // public static PollFulfillmentMatcher pollFulfillment(String messageId, String collection, String resultId, String resultPartNumber) { // return new PollFulfillmentMatcher(messageId, collection, resultId, resultPartNumber); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher initialPollRequest(String messageId, String collection) { // return new PollRequestMatcher(messageId, collection, null); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HasHeaderMatcher.java // public static Matcher<HttpHeaders> hasAllTaxiiHeaders() { // return allOf( // hasHeader("Content-Type", is("application/xml")), // hasHeader("Accept", is("application/xml")), // hasHeader("X-Taxii-Accept", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-TAXII-Content-Type", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-Taxii-Protocol", is("urn:taxii.mitre.org:protocol:https:1.0")), // hasHeader("X-TAXII-Services", is("urn:taxii.mitre.org:services:1.1")) // ); // }
import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpResponse; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import static com.cisco.cta.taxii.adapter.PollFulfillmentMatcher.pollFulfillment; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.initialPollRequest; import static com.cisco.cta.taxii.adapter.httpclient.HasHeaderMatcher.hasAllTaxiiHeaders; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
configurator.doConfigure("src/test/resources/logback-test.xml"); } @After public void tearDown() throws Exception { taxiiPollRespBodyInitial.close(); taxiiPollRespBodyNext.close(); } @Test public void runFromEpochBegin() throws Exception { initialMultipartRequestResponse(); assertThat(statistics.getPolls(), is(2L)); assertThat(statistics.getLogs(), is(2L)); assertThat(statistics.getErrors(), is(0L)); assertThat(OUTPUT_FILE + " content expected same as " + EXPECTED_OUTPUT_FILE, FileUtils.readFileToString(OUTPUT_FILE), is(FileUtils.readFileToString(EXPECTED_OUTPUT_FILE))); } private void initialMultipartRequestResponse() throws IOException { when(httpResp.getRawStatusCode()).thenReturn(200); when(httpResp.getBody()).thenReturn(taxiiPollRespBodyInitial); when(httpResp2.getRawStatusCode()).thenReturn(200); when(httpResp2.getBody()).thenReturn(taxiiPollRespBodyNext); task.run(); verify(httpRequestFactory, times(2)).createRequest(pollServiceUri, HttpMethod.POST); assertThat(httpReqHeaders, hasAllTaxiiHeaders()); verify(httpReq).execute(); verify(httpReq2).execute(); assertThat(httpReqBody, is(initialPollRequest("123", "collection_name")));
// Path: src/test/java/com/cisco/cta/taxii/adapter/PollFulfillmentMatcher.java // public static PollFulfillmentMatcher pollFulfillment(String messageId, String collection, String resultId, String resultPartNumber) { // return new PollFulfillmentMatcher(messageId, collection, resultId, resultPartNumber); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/PollRequestMatcher.java // public static PollRequestMatcher initialPollRequest(String messageId, String collection) { // return new PollRequestMatcher(messageId, collection, null); // } // // Path: src/test/java/com/cisco/cta/taxii/adapter/httpclient/HasHeaderMatcher.java // public static Matcher<HttpHeaders> hasAllTaxiiHeaders() { // return allOf( // hasHeader("Content-Type", is("application/xml")), // hasHeader("Accept", is("application/xml")), // hasHeader("X-Taxii-Accept", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-TAXII-Content-Type", is("urn:taxii.mitre.org:message:xml:1.1")), // hasHeader("X-Taxii-Protocol", is("urn:taxii.mitre.org:protocol:https:1.0")), // hasHeader("X-TAXII-Services", is("urn:taxii.mitre.org:services:1.1")) // ); // } // Path: src/test/java/com/cisco/cta/taxii/adapter/AdapterTaskMultipartIT.java import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.ClientHttpResponse; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import static com.cisco.cta.taxii.adapter.PollFulfillmentMatcher.pollFulfillment; import static com.cisco.cta.taxii.adapter.PollRequestMatcher.initialPollRequest; import static com.cisco.cta.taxii.adapter.httpclient.HasHeaderMatcher.hasAllTaxiiHeaders; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; configurator.doConfigure("src/test/resources/logback-test.xml"); } @After public void tearDown() throws Exception { taxiiPollRespBodyInitial.close(); taxiiPollRespBodyNext.close(); } @Test public void runFromEpochBegin() throws Exception { initialMultipartRequestResponse(); assertThat(statistics.getPolls(), is(2L)); assertThat(statistics.getLogs(), is(2L)); assertThat(statistics.getErrors(), is(0L)); assertThat(OUTPUT_FILE + " content expected same as " + EXPECTED_OUTPUT_FILE, FileUtils.readFileToString(OUTPUT_FILE), is(FileUtils.readFileToString(EXPECTED_OUTPUT_FILE))); } private void initialMultipartRequestResponse() throws IOException { when(httpResp.getRawStatusCode()).thenReturn(200); when(httpResp.getBody()).thenReturn(taxiiPollRespBodyInitial); when(httpResp2.getRawStatusCode()).thenReturn(200); when(httpResp2.getBody()).thenReturn(taxiiPollRespBodyNext); task.run(); verify(httpRequestFactory, times(2)).createRequest(pollServiceUri, HttpMethod.POST); assertThat(httpReqHeaders, hasAllTaxiiHeaders()); verify(httpReq).execute(); verify(httpReq2).execute(); assertThat(httpReqBody, is(initialPollRequest("123", "collection_name")));
assertThat(httpReq2Body, is(pollFulfillment("123", "collection_name", "1000#2000", "2")));
CiscoCTA/taxii-log-adapter
src/main/java/com/cisco/cta/taxii/adapter/filter/JsonValidationFilter.java
// Path: src/main/java/com/cisco/cta/taxii/adapter/OutputValidationException.java // public class OutputValidationException extends RuntimeException { // public static final String MDC_KEY = "OutputValidationException"; // // public OutputValidationException(String message) { // super("Output validation failed: " + message); // } // // }
import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.filter.Filter; import ch.qos.logback.core.spi.FilterReply; import com.cisco.cta.taxii.adapter.OutputValidationException; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.MDC; import java.io.IOException;
/* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.filter; public class JsonValidationFilter extends Filter<ILoggingEvent> { private ObjectMapper mapper = new ObjectMapper(); @Override public FilterReply decide(ILoggingEvent event) { String messsage = event.getMessage(); try { mapper.readTree(messsage); }catch(IOException e) {
// Path: src/main/java/com/cisco/cta/taxii/adapter/OutputValidationException.java // public class OutputValidationException extends RuntimeException { // public static final String MDC_KEY = "OutputValidationException"; // // public OutputValidationException(String message) { // super("Output validation failed: " + message); // } // // } // Path: src/main/java/com/cisco/cta/taxii/adapter/filter/JsonValidationFilter.java import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.filter.Filter; import ch.qos.logback.core.spi.FilterReply; import com.cisco.cta.taxii.adapter.OutputValidationException; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.MDC; import java.io.IOException; /* Copyright 2015 Cisco Systems Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.cisco.cta.taxii.adapter.filter; public class JsonValidationFilter extends Filter<ILoggingEvent> { private ObjectMapper mapper = new ObjectMapper(); @Override public FilterReply decide(ILoggingEvent event) { String messsage = event.getMessage(); try { mapper.readTree(messsage); }catch(IOException e) {
MDC.put(OutputValidationException.MDC_KEY, e.getMessage());