answer
stringlengths
17
10.2M
package com.amplitude.unity.plugins; import android.app.Application; import android.content.Context; import com.amplitude.api.Amplitude; import com.amplitude.api.Identify; import com.amplitude.api.Revenue; import com.amplitude.api.TrackingOptions; import com.amplitude.api.Utils; import org.json.JSONException; import org.json.JSONObject; public class AmplitudePlugin { public static JSONObject ToJSONObject(String jsonString) { JSONObject properties = null; try { properties = new JSONObject(jsonString); } catch (JSONException e) { e.printStackTrace(); } return properties; } public static void init(String instanceName, Context context, String apiKey) { Amplitude.getInstance(instanceName).initialize(context, apiKey); } public static void init(String instanceName, Context context, String apiKey, String userId) { Amplitude.getInstance(instanceName).initialize(context, apiKey, userId); } public static void setTrackingOptions(String instanceName, String trackingOptionsJson) { JSONObject trackingOptionsDict = ToJSONObject(trackingOptionsJson); TrackingOptions trackingOptions = new TrackingOptions(); if (trackingOptionsDict.optBoolean("disableADID", false)) { trackingOptions.disableAdid(); } if (trackingOptionsDict.optBoolean("disableCarrier", false)) { trackingOptions.disableCarrier(); } if (trackingOptionsDict.optBoolean("disableCity", false)) { trackingOptions.disableCity(); } if (trackingOptionsDict.optBoolean("disableCountry", false)) { trackingOptions.disableCountry(); } if (trackingOptionsDict.optBoolean("disableDeviceBrand", false)) { trackingOptions.disableDeviceBrand(); } if (trackingOptionsDict.optBoolean("disableDeviceManufacturer", false)) { trackingOptions.disableDeviceManufacturer(); } if (trackingOptionsDict.optBoolean("disableDeviceModel", false)) { trackingOptions.disableDeviceModel(); } if (trackingOptionsDict.optBoolean("disableDMA", false)) { trackingOptions.disableDma(); } if (trackingOptionsDict.optBoolean("disableIPAddress", false)) { trackingOptions.disableIpAddress(); } if (trackingOptionsDict.optBoolean("disableLanguage", false)) { trackingOptions.disableLanguage(); } if (trackingOptionsDict.optBoolean("disableLatLng", false)) { trackingOptions.disableLatLng(); } if (trackingOptionsDict.optBoolean("disableOSName", false)) { trackingOptions.disableOsName(); } if (trackingOptionsDict.optBoolean("disableOSVersion", false)) { trackingOptions.disableOsVersion(); } if (trackingOptionsDict.optBoolean("disableApiLevel", false)) { trackingOptions.disableApiLevel(); } if (trackingOptionsDict.optBoolean("disablePlatform", false)) { trackingOptions.disablePlatform(); } if (trackingOptionsDict.optBoolean("disableRegion", false)) { trackingOptions.disableRegion(); } if (trackingOptionsDict.optBoolean("disableVersionName", false)) { trackingOptions.disableVersionName(); } Amplitude.getInstance(instanceName).setTrackingOptions(trackingOptions); } public static void enableForegroundTracking(String instanceName, Application app) { Amplitude.getInstance(instanceName).enableForegroundTracking(app); } public static void enableCoppaControl(String instanceName) { Amplitude.getInstance(instanceName).enableCoppaControl(); } public static void disableCoppaControl(String instanceName) { Amplitude.getInstance(instanceName).disableCoppaControl(); } public static void setLibraryName(String instanceName, String libraryName) { Amplitude.getInstance(instanceName).setLibraryName(libraryName); } public static void setLibraryVersion(String instanceName, String libraryVersion) { Amplitude.getInstance(instanceName).setLibraryVersion(libraryVersion); } public static void setServerUrl(String instanceName, String serverUrl) { Amplitude.getInstance(instanceName).setServerUrl(serverUrl); } @Deprecated public static void startSession() { return; } @Deprecated public static void endSession() { return; } public static void logEvent(String instanceName, String event) { Amplitude.getInstance(instanceName).logEvent(event); } public static void logEvent(String instanceName, String event, String jsonProperties) { Amplitude.getInstance(instanceName).logEvent(event, ToJSONObject(jsonProperties)); } public static void logEvent(String instanceName, String event, String jsonProperties, boolean outOfSession) { Amplitude.getInstance(instanceName).logEvent(event, ToJSONObject(jsonProperties), outOfSession); } public static void uploadEvents(String instanceName) { Amplitude.getInstance(instanceName).uploadEvents(); } public static void useAdvertisingIdForDeviceId(String instanceName) { Amplitude.getInstance(instanceName).useAdvertisingIdForDeviceId(); } public static void setOffline(String instanceName, boolean offline) { Amplitude.getInstance(instanceName).setOffline(offline); } public static void setUserId(String instanceName, String userId) { Amplitude.getInstance(instanceName).setUserId(userId); } public static void setOptOut(String instanceName, boolean enabled) { Amplitude.getInstance(instanceName).setOptOut(enabled); } public static void setMinTimeBetweenSessionsMillis(String instanceName, long minTimeBetweenSessionsMillis) { Amplitude.getInstance(instanceName).setMinTimeBetweenSessionsMillis(minTimeBetweenSessionsMillis); } public static void setEventUploadPeriodMillis(String instanceName, int eventUploadPeriodMillis) { Amplitude.getInstance(instanceName).setEventUploadPeriodMillis(eventUploadPeriodMillis); } public static void setUserProperties(String instanceName, String jsonProperties) { Amplitude.getInstance(instanceName).setUserProperties(ToJSONObject(jsonProperties)); } public static void logRevenue(String instanceName, double amount) { Amplitude.getInstance(instanceName).logRevenue(amount); } public static void logRevenue(String instanceName, String productId, int quantity, double price) { Amplitude.getInstance(instanceName).logRevenue(productId, quantity, price); } public static void logRevenue(String instanceName, String productId, int quantity, double price, String receipt, String receiptSignature) { Amplitude.getInstance(instanceName).logRevenue(productId, quantity, price, receipt, receiptSignature); } public static void logRevenue(String instanceName, String productId, int quantity, double price, String receipt, String receiptSignature, String revenueType, String jsonProperties) { Revenue revenue = new Revenue().setQuantity(quantity).setPrice(price); if (!Utils.isEmptyString(productId)) { revenue.setProductId(productId); } if (!Utils.isEmptyString(receipt) && !Utils.isEmptyString(receiptSignature)) { revenue.setReceipt(receipt, receiptSignature); } if (!Utils.isEmptyString(revenueType)) { revenue.setRevenueType(revenueType); } if (!Utils.isEmptyString(jsonProperties)) { revenue.setEventProperties(ToJSONObject(jsonProperties)); } Amplitude.getInstance(instanceName).logRevenueV2(revenue); } public static String getDeviceId(String instanceName) { return Amplitude.getInstance(instanceName).getDeviceId(); } public static void setDeviceId(String instanceName, String deviceId) { Amplitude.getInstance(instanceName).setDeviceId(deviceId); } public static void regenerateDeviceId(String instanceName) { Amplitude.getInstance(instanceName).regenerateDeviceId(); } public static void trackSessionEvents(String instanceName, boolean enabled) { Amplitude.getInstance(instanceName).trackSessionEvents(enabled); } public static long getSessionId(String instanceName) { return Amplitude.getInstance(instanceName).getSessionId(); } // User Property Operations // clear user properties public static void clearUserProperties(String instanceName) { Amplitude.getInstance(instanceName).clearUserProperties(); } // unset user property public static void unsetUserProperty(String instanceName, String property) { Amplitude.getInstance(instanceName).identify(new Identify().unset(property)); } // setOnce user property public static void setOnceUserProperty(String instanceName, String property, boolean value) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, value)); } public static void setOnceUserProperty(String instanceName, String property, double value) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, value)); } public static void setOnceUserProperty(String instanceName, String property, float value) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, value)); } public static void setOnceUserProperty(String instanceName, String property, int value) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, value)); } public static void setOnceUserProperty(String instanceName, String property, long value) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, value)); } public static void setOnceUserProperty(String instanceName, String property, String value) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, value)); } public static void setOnceUserPropertyDict(String instanceName, String property, String values) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, ToJSONObject(values))); } public static void setOnceUserPropertyList(String instanceName, String property, String values) { JSONObject properties = ToJSONObject(values); if (properties == null) { return; } Amplitude.getInstance(instanceName).identify(new Identify().setOnce( property, properties.optJSONArray("list") )); } public static void setOnceUserProperty(String instanceName, String property, boolean[] values) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, values)); } public static void setOnceUserProperty(String instanceName, String property, double[] values) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, values)); } public static void setOnceUserProperty(String instanceName, String property, float[] values) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, values)); } public static void setOnceUserProperty(String instanceName, String property, int[] values) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, values)); } public static void setOnceUserProperty(String instanceName, String property, long[] values) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, values)); } public static void setOnceUserProperty(String instanceName, String property, String[] values) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, values)); } // set user property public static void setUserProperty(String instanceName, String property, boolean value) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, value)); } public static void setUserProperty(String instanceName, String property, double value) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, value)); } public static void setUserProperty(String instanceName, String property, float value) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, value)); } public static void setUserProperty(String instanceName, String property, int value) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, value)); } public static void setUserProperty(String instanceName, String property, long value) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, value)); } public static void setUserProperty(String instanceName, String property, String value) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, value)); } public static void setUserPropertyDict(String instanceName, String property, String values) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, ToJSONObject(values))); } public static void setUserPropertyList(String instanceName, String property, String values) { JSONObject properties = ToJSONObject(values); if (properties == null) { return; } Amplitude.getInstance(instanceName).identify(new Identify().set( property, properties.optJSONArray("list") )); } public static void setUserProperty(String instanceName, String property, boolean[] values) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, values)); } public static void setUserProperty(String instanceName, String property, double[] values) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, values)); } public static void setUserProperty(String instanceName, String property, float[] values) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, values)); } public static void setUserProperty(String instanceName, String property, int[] values) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, values)); } public static void setUserProperty(String instanceName, String property, long[] values) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, values)); } public static void setUserProperty(String instanceName, String property, String[] values) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, values)); } // add public static void addUserProperty(String instanceName, String property, double value) { Amplitude.getInstance(instanceName).identify(new Identify().add(property, value)); } public static void addUserProperty(String instanceName, String property, float value) { Amplitude.getInstance(instanceName).identify(new Identify().add(property, value)); } public static void addUserProperty(String instanceName, String property, int value) { Amplitude.getInstance(instanceName).identify(new Identify().add(property, value)); } public static void addUserProperty(String instanceName, String property, long value) { Amplitude.getInstance(instanceName).identify(new Identify().add(property, value)); } public static void addUserProperty(String instanceName, String property, String value) { Amplitude.getInstance(instanceName).identify(new Identify().add(property, value)); } public static void addUserPropertyDict(String instanceName, String property, String values) { Amplitude.getInstance(instanceName).identify(new Identify().add(property, ToJSONObject(values))); } // append user property public static void appendUserProperty(String instanceName, String property, boolean value) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, value)); } public static void appendUserProperty(String instanceName, String property, double value) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, value)); } public static void appendUserProperty(String instanceName, String property, float value) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, value)); } public static void appendUserProperty(String instanceName, String property, int value) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, value)); } public static void appendUserProperty(String instanceName, String property, long value) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, value)); } public static void appendUserProperty(String instanceName, String property, String value) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, value)); } public static void appendUserPropertyDict(String instanceName, String property, String values) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, ToJSONObject(values))); } public static void appendUserPropertyList(String instanceName, String property, String values) { JSONObject properties = ToJSONObject(values); if (properties == null) { return; } Amplitude.getInstance(instanceName).identify(new Identify().append( property, properties.optJSONArray("list") )); } public static void appendUserProperty(String instanceName, String property, boolean[] values) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, values)); } public static void appendUserProperty(String instanceName, String property, double[] values) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, values)); } public static void appendUserProperty(String instanceName, String property, float[] values) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, values)); } public static void appendUserProperty(String instanceName, String property, int[] values) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, values)); } public static void appendUserProperty(String instanceName, String property, long[] values) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, values)); } public static void appendUserProperty(String instanceName, String property, String[] values) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, values)); } }
package com.amplitude.unity.plugins; import android.app.Application; import android.content.Context; import com.amplitude.api.Amplitude; import com.amplitude.api.Identify; import com.amplitude.api.Revenue; import com.amplitude.api.TrackingOptions; import com.amplitude.api.Utils; import org.json.JSONException; import org.json.JSONObject; public class AmplitudePlugin { public static JSONObject ToJSONObject(String jsonString) { JSONObject properties = null; try { properties = new JSONObject(jsonString); } catch (JSONException e) { e.printStackTrace(); } return properties; } public static void init(String instanceName, Context context, String apiKey) { Amplitude.getInstance(instanceName).initialize(context, apiKey); } public static void init(String instanceName, Context context, String apiKey, String userId) { Amplitude.getInstance(instanceName).initialize(context, apiKey, userId); } public static void setTrackingOptions(String instanceName, String trackingOptionsJson) { JSONObject trackingOptionsDict = ToJSONObject(trackingOptionsJson); TrackingOptions trackingOptions = new TrackingOptions(); if (trackingOptionsDict.optBoolean("disableADID", false)) { trackingOptions.disableAdid(); } if (trackingOptionsDict.optBoolean("disableCarrier", false)) { trackingOptions.disableCarrier(); } if (trackingOptionsDict.optBoolean("disableCity", false)) { trackingOptions.disableCity(); } if (trackingOptionsDict.optBoolean("disableCountry", false)) { trackingOptions.disableCountry(); } if (trackingOptionsDict.optBoolean("disableDeviceBrand", false)) { trackingOptions.disableDeviceBrand(); } if (trackingOptionsDict.optBoolean("disableDeviceManufacturer", false)) { trackingOptions.disableDeviceManufacturer(); } if (trackingOptionsDict.optBoolean("disableDeviceModel", false)) { trackingOptions.disableDeviceModel(); } if (trackingOptionsDict.optBoolean("disableDMA", false)) { trackingOptions.disableDma(); } if (trackingOptionsDict.optBoolean("disableIPAddress", false)) { trackingOptions.disableIpAddress(); } if (trackingOptionsDict.optBoolean("disableLanguage", false)) { trackingOptions.disableLanguage(); } if (trackingOptionsDict.optBoolean("disableLatLng", false)) { trackingOptions.disableLatLng(); } if (trackingOptionsDict.optBoolean("disableOSName", false)) { trackingOptions.disableOsName(); } if (trackingOptionsDict.optBoolean("disableOSVersion", false)) { trackingOptions.disableOsVersion(); } if (trackingOptionsDict.optBoolean("disableApiLevel", false)) { trackingOptions.disableApiLevel(); } if (trackingOptionsDict.optBoolean("disablePlatform", false)) { trackingOptions.disablePlatform(); } if (trackingOptionsDict.optBoolean("disableRegion", false)) { trackingOptions.disableRegion(); } if (trackingOptionsDict.optBoolean("disableVersionName", false)) { trackingOptions.disableVersionName(); } Amplitude.getInstance(instanceName).setTrackingOptions(trackingOptions); } public static void enableForegroundTracking(String instanceName, Application app) { Amplitude.getInstance(instanceName).enableForegroundTracking(app); } public static void enableCoppaControl(String instanceName) { Amplitude.getInstance(instanceName).enableCoppaControl(); } public static void disableCoppaControl(String instanceName) { Amplitude.getInstance(instanceName).disableCoppaControl(); } public static void setLibraryName(String instanceName, String libraryName) { Amplitude.getInstance(instanceName).setLibraryName(libraryName); } public static void setLibraryVersion(String instanceName, String libraryVersion) { Amplitude.getInstance(instanceName).setLibraryVersion(libraryVersion); } public static void setServerUrl(String instanceName, String serverUrl) { Amplitude.getInstance(instanceName).setServerUrl(serverUrl); } @Deprecated public static void startSession() { return; } @Deprecated public static void endSession() { return; } public static void logEvent(String instanceName, String event) { Amplitude.getInstance(instanceName).logEvent(event); } public static void logEvent(String instanceName, String event, String jsonProperties) { Amplitude.getInstance(instanceName).logEvent(event, ToJSONObject(jsonProperties)); } public static void logEvent(String instanceName, String event, String jsonProperties, boolean outOfSession) { Amplitude.getInstance(instanceName).logEvent(event, ToJSONObject(jsonProperties), outOfSession); } public static void uploadEvents(String instanceName) { Amplitude.getInstance(instanceName).uploadEvents(); } public static void useAdvertisingIdForDeviceId(String instanceName) { Amplitude.getInstance(instanceName).useAdvertisingIdForDeviceId(); } public static void setOffline(String instanceName, boolean offline) { Amplitude.getInstance(instanceName).setOffline(offline); } public static void setUserId(String instanceName, String userId) { Amplitude.getInstance(instanceName).setUserId(userId); } public static void setOptOut(String instanceName, boolean enabled) { Amplitude.getInstance(instanceName).setOptOut(enabled); } public static void setUserProperties(String instanceName, String jsonProperties) { Amplitude.getInstance(instanceName).setUserProperties(ToJSONObject(jsonProperties)); } public static void logRevenue(String instanceName, double amount) { Amplitude.getInstance(instanceName).logRevenue(amount); } public static void logRevenue(String instanceName, String productId, int quantity, double price) { Amplitude.getInstance(instanceName).logRevenue(productId, quantity, price); } public static void logRevenue(String instanceName, String productId, int quantity, double price, String receipt, String receiptSignature) { Amplitude.getInstance(instanceName).logRevenue(productId, quantity, price, receipt, receiptSignature); } public static void logRevenue(String instanceName, String productId, int quantity, double price, String receipt, String receiptSignature, String revenueType, String jsonProperties) { Revenue revenue = new Revenue().setQuantity(quantity).setPrice(price); if (!Utils.isEmptyString(productId)) { revenue.setProductId(productId); } if (!Utils.isEmptyString(receipt) && !Utils.isEmptyString(receiptSignature)) { revenue.setReceipt(receipt, receiptSignature); } if (!Utils.isEmptyString(revenueType)) { revenue.setRevenueType(revenueType); } if (!Utils.isEmptyString(jsonProperties)) { revenue.setEventProperties(ToJSONObject(jsonProperties)); } Amplitude.getInstance(instanceName).logRevenueV2(revenue); } public static String getDeviceId(String instanceName) { return Amplitude.getInstance(instanceName).getDeviceId(); } public static void setDeviceId(String instanceName, String deviceId) { Amplitude.getInstance(instanceName).setDeviceId(deviceId); } public static void regenerateDeviceId(String instanceName) { Amplitude.getInstance(instanceName).regenerateDeviceId(); } public static void trackSessionEvents(String instanceName, boolean enabled) { Amplitude.getInstance(instanceName).trackSessionEvents(enabled); } public static long getSessionId(String instanceName) { return Amplitude.getInstance(instanceName).getSessionId(); } // User Property Operations // clear user properties public static void clearUserProperties(String instanceName) { Amplitude.getInstance(instanceName).clearUserProperties(); } // unset user property public static void unsetUserProperty(String instanceName, String property) { Amplitude.getInstance(instanceName).identify(new Identify().unset(property)); } // setOnce user property public static void setOnceUserProperty(String instanceName, String property, boolean value) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, value)); } public static void setOnceUserProperty(String instanceName, String property, double value) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, value)); } public static void setOnceUserProperty(String instanceName, String property, float value) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, value)); } public static void setOnceUserProperty(String instanceName, String property, int value) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, value)); } public static void setOnceUserProperty(String instanceName, String property, long value) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, value)); } public static void setOnceUserProperty(String instanceName, String property, String value) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, value)); } public static void setOnceUserPropertyDict(String instanceName, String property, String values) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, ToJSONObject(values))); } public static void setOnceUserPropertyList(String instanceName, String property, String values) { JSONObject properties = ToJSONObject(values); if (properties == null) { return; } Amplitude.getInstance(instanceName).identify(new Identify().setOnce( property, properties.optJSONArray("list") )); } public static void setOnceUserProperty(String instanceName, String property, boolean[] values) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, values)); } public static void setOnceUserProperty(String instanceName, String property, double[] values) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, values)); } public static void setOnceUserProperty(String instanceName, String property, float[] values) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, values)); } public static void setOnceUserProperty(String instanceName, String property, int[] values) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, values)); } public static void setOnceUserProperty(String instanceName, String property, long[] values) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, values)); } public static void setOnceUserProperty(String instanceName, String property, String[] values) { Amplitude.getInstance(instanceName).identify(new Identify().setOnce(property, values)); } // set user property public static void setUserProperty(String instanceName, String property, boolean value) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, value)); } public static void setUserProperty(String instanceName, String property, double value) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, value)); } public static void setUserProperty(String instanceName, String property, float value) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, value)); } public static void setUserProperty(String instanceName, String property, int value) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, value)); } public static void setUserProperty(String instanceName, String property, long value) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, value)); } public static void setUserProperty(String instanceName, String property, String value) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, value)); } public static void setUserPropertyDict(String instanceName, String property, String values) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, ToJSONObject(values))); } public static void setUserPropertyList(String instanceName, String property, String values) { JSONObject properties = ToJSONObject(values); if (properties == null) { return; } Amplitude.getInstance(instanceName).identify(new Identify().set( property, properties.optJSONArray("list") )); } public static void setUserProperty(String instanceName, String property, boolean[] values) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, values)); } public static void setUserProperty(String instanceName, String property, double[] values) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, values)); } public static void setUserProperty(String instanceName, String property, float[] values) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, values)); } public static void setUserProperty(String instanceName, String property, int[] values) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, values)); } public static void setUserProperty(String instanceName, String property, long[] values) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, values)); } public static void setUserProperty(String instanceName, String property, String[] values) { Amplitude.getInstance(instanceName).identify(new Identify().set(property, values)); } // add public static void addUserProperty(String instanceName, String property, double value) { Amplitude.getInstance(instanceName).identify(new Identify().add(property, value)); } public static void addUserProperty(String instanceName, String property, float value) { Amplitude.getInstance(instanceName).identify(new Identify().add(property, value)); } public static void addUserProperty(String instanceName, String property, int value) { Amplitude.getInstance(instanceName).identify(new Identify().add(property, value)); } public static void addUserProperty(String instanceName, String property, long value) { Amplitude.getInstance(instanceName).identify(new Identify().add(property, value)); } public static void addUserProperty(String instanceName, String property, String value) { Amplitude.getInstance(instanceName).identify(new Identify().add(property, value)); } public static void addUserPropertyDict(String instanceName, String property, String values) { Amplitude.getInstance(instanceName).identify(new Identify().add(property, ToJSONObject(values))); } // append user property public static void appendUserProperty(String instanceName, String property, boolean value) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, value)); } public static void appendUserProperty(String instanceName, String property, double value) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, value)); } public static void appendUserProperty(String instanceName, String property, float value) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, value)); } public static void appendUserProperty(String instanceName, String property, int value) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, value)); } public static void appendUserProperty(String instanceName, String property, long value) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, value)); } public static void appendUserProperty(String instanceName, String property, String value) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, value)); } public static void appendUserPropertyDict(String instanceName, String property, String values) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, ToJSONObject(values))); } public static void appendUserPropertyList(String instanceName, String property, String values) { JSONObject properties = ToJSONObject(values); if (properties == null) { return; } Amplitude.getInstance(instanceName).identify(new Identify().append( property, properties.optJSONArray("list") )); } public static void appendUserProperty(String instanceName, String property, boolean[] values) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, values)); } public static void appendUserProperty(String instanceName, String property, double[] values) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, values)); } public static void appendUserProperty(String instanceName, String property, float[] values) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, values)); } public static void appendUserProperty(String instanceName, String property, int[] values) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, values)); } public static void appendUserProperty(String instanceName, String property, long[] values) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, values)); } public static void appendUserProperty(String instanceName, String property, String[] values) { Amplitude.getInstance(instanceName).identify(new Identify().append(property, values)); } }
package com.carlosefonseca.common.utils; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.media.MediaPlayer; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.widget.Toast; import com.carlosefonseca.common.CFApp; import de.greenrobot.event.EventBus; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.Queue; public class AudioPlayer { private static final String TAG = CodeUtils.getTag(AudioPlayer.class); private static final Context c = CFApp.getContext(); public static final int STOPPED = 0; public static final int PLAYING = 1; public static final int PAUSED = 2; @Nullable private static MediaPlayer currentMediaPlayer; private static File currentFile; private static Queue<MediaPlayerWrapper> queue = new LinkedList<>(); public static class AudioPlayerNotification { public final Status status; public final File file; public final MediaPlayer mediaPlayer; public enum Status { PLAY, PAUSE, STOP} public AudioPlayerNotification(Status status, @Nullable File file, @Nullable MediaPlayer mediaPlayer) { this.status = status; this.file = file; this.mediaPlayer = mediaPlayer; } @Override public String toString() { return String.format("AudioNotif:%-5s-%s", status, file != null ? file.getName() : ""); } public static void PostStart(@Nullable File file) { EventBus.getDefault().postSticky(new AudioPlayerNotification(Status.PLAY, file, null)); } public static void PostStart(@Nullable File file, MediaPlayer mediaPlayer) { EventBus.getDefault().postSticky(new AudioPlayerNotification(Status.PLAY, file, mediaPlayer)); } public static void PostPause(File file) { EventBus.getDefault().postSticky(new AudioPlayerNotification(Status.PAUSE, file, null)); } public static void PostPause(File file, MediaPlayer mediaPlayer) { EventBus.getDefault().postSticky(new AudioPlayerNotification(Status.PAUSE, file, mediaPlayer)); } public static void PostStop(File file) { EventBus.getDefault().postSticky(new AudioPlayerNotification(Status.STOP, file, null)); } public static void register(Object object) { EventBus.getDefault().register(object, AudioPlayerNotification.class); } public static void unregister(Object object) { EventBus.getDefault().unregister(object, AudioPlayerNotification.class); } } // // SINGLETON CRAP // static AudioPlayer instance = null; // public static AudioPlayer getInstance() { // if (instance == null) { // instance = new AudioPlayer(); // return instance; // END SINGLETON CRAP static void play() { Log.i(TAG, "Poping queue (Q size: " + queue.size() + ")"); MediaPlayerWrapper mediaPlayerWrapper = queue.poll(); if (mediaPlayerWrapper != null) play(mediaPlayerWrapper.mediaPlayer, mediaPlayerWrapper.file); } /** * THE PLAY METHOD */ private static void play(@NonNull MediaPlayer mediaPlayer, @Nullable File file) { stop(); currentFile = file; currentMediaPlayer = mediaPlayer; currentMediaPlayer.setOnCompletionListener(onEnd.instance); currentMediaPlayer.start(); AudioPlayerNotification.PostStart(currentFile, mediaPlayer); Log.v(TAG, "" + (file != null ? file.getName() : "???") + " Playing."); } /** * Starts playing the file, stopping another that was playing. */ public static void playFile(File audioFile) { if (!audioFile.exists()) { Log.i(TAG, "File " + audioFile + " doesn't exist."); CodeUtils.toast("File " + audioFile + " doesn't exist."); return; } MediaPlayer mediaPlayerForFile = getMediaPlayerForFile(c, audioFile); if (mediaPlayerForFile != null) { play(mediaPlayerForFile, audioFile); } } /** * Starts playing the file, stopping another that was playing. */ public static void playOrResumeFile(File audioFile) { // if (!audioFile.exists()) { // Log.i(TAG, "File " + audioFile + " doesn't exist."); // CodeUtils.toast("File " + audioFile + " doesn't exist."); // return; if (currentFile != null && currentFile.equals(audioFile) && currentMediaPlayer != null && !currentMediaPlayer.isPlaying()) { resume(); } else { MediaPlayer mediaPlayerForFile = getMediaPlayerForFile(c, audioFile); if (mediaPlayerForFile != null) { play(mediaPlayerForFile, audioFile); } } } public static void stop() { if (isPlaying()) { if (currentMediaPlayer != null) currentMediaPlayer.stop(); AudioPlayerNotification.PostStop(currentFile); currentMediaPlayer = null; currentFile = null; queue.clear(); } EventBus.getDefault().removeStickyEvent(AudioPlayer.AudioPlayerNotification.class); } /** * Adds the file to the queue or simply plays the file is nothing is playing */ public static void queueFile(@NonNull File audioFile) { if (!isPlaying()) { playFile(audioFile); } else { if (!audioFile.exists()) { Log.i(TAG, "" + audioFile + " doesn't exist."); return; } MediaPlayerWrapper mp = getWrappedMediaPlayerForFile(c, audioFile); if (mp != null) { queue.add(mp); Log.v(TAG, "" + audioFile.getName() + " queued. (Q size: "+queue.size()+")"); } } } @Nullable public static MediaPlayerWrapper getWrappedMediaPlayerForFile(Context c, File audioFile) { if (!audioFile.exists()) { Log.i(TAG, "" + audioFile + " doesn't exist."); return null; } return new MediaPlayerWrapper(getMediaPlayerForFile(c, audioFile), audioFile); } /** * Creates a MediaPlayer object. * * @return New media player or null if it couldn't be created. */ @Nullable public static MediaPlayer getMediaPlayerForFile(Context c, File audioFile) { if (audioFile.exists() && audioFile.isFile()) { Log.v(TAG, "" + audioFile.getName() + " Setting up..."); MediaPlayer mediaPlayer = MediaPlayer.create(c, Uri.fromFile(audioFile)); if (mediaPlayer != null) { mediaPlayer.setOnCompletionListener(onEnd.instance); } else { Log.e(TAG, new Exception("Failed to create MediaPlayer for audioFile " + audioFile.getName())); } return mediaPlayer; } else if (UIL.existsOnPackage(audioFile.getName())) { try { AssetFileDescriptor afd = c.getAssets().openFd(audioFile.getName()); MediaPlayer player = new MediaPlayer(); player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); player.prepare(); return player; } catch (IOException e) { Log.e(TAG, "" + e.getMessage(), e); } } Log.i(TAG, "" + audioFile.getName() + " doesn't exist!"); Toast.makeText(c, "Audio File " + audioFile.getName() + " doesn't exist!", Toast.LENGTH_SHORT).show(); return null; } public static void pause() { if (currentMediaPlayer == null) { Log.e(TAG, new Exception("Media player not initialized")); return; } currentMediaPlayer.pause(); AudioPlayerNotification.PostPause(currentFile, currentMediaPlayer); } public static void resume() { if (currentMediaPlayer == null) { Log.e(TAG, new Exception("Media player not initialized")); return; } currentMediaPlayer.start(); AudioPlayerNotification.PostStart(currentFile, currentMediaPlayer); } /* private void pauseAudio() { if (currentMediaPlayer == null) { Log.e(TAG, new Exception("Media player not initialized")); return; } currentMediaPlayer.pause(); } */ public static boolean isPlaying() { return currentMediaPlayer != null && currentMediaPlayer.isPlaying(); } public static int getStatus() { if (currentMediaPlayer != null) { return currentMediaPlayer.isPlaying() ? PLAYING : currentMediaPlayer.getCurrentPosition() < currentMediaPlayer.getDuration() ? PAUSED : STOPPED; } else { return STOPPED; } } @Nullable public static MediaPlayer getMediaPlayer() { return currentMediaPlayer; } static class onEnd implements MediaPlayer.OnCompletionListener { static onEnd instance = new onEnd(); private onEnd() { } @Override public void onCompletion(MediaPlayer mediaPlayer) { AudioPlayerNotification.PostStop(currentFile); play(); } } public static File getCurrentFile() { return currentFile; } static class MediaPlayerWrapper { MediaPlayer mediaPlayer; File file; MediaPlayerWrapper(@Nullable MediaPlayer mediaPlayer, File file) { this.mediaPlayer = mediaPlayer; this.file = file; } } }
package com.castlemon.maven.processing; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.maven.model.Model; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.graph.Dependency; import org.eclipse.aether.resolution.ArtifactDescriptorResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.castlemon.maven.control.Controller; import com.castlemon.maven.domain.RunData; import com.castlemon.maven.domain.Usage; @Component public class PomProcessor { @Autowired private AetherProcessor aetherProcessor; private static final Logger LOGGER = LoggerFactory.getLogger(Controller.class); public void processPoms(RunData runData, Collection<File> pomFiles) { List<Usage> usages = new ArrayList<Usage>(); MavenXpp3Reader reader = new MavenXpp3Reader(); for (File pom : pomFiles) { try { Model model = reader.read(new FileReader(pom)); String groupId = model.getGroupId() != null ? model.getGroupId() : model.getParent().getGroupId(); String version = model.getVersion() != null ? model.getVersion() : model.getParent().getVersion(); ArtifactDescriptorResult descriptorResult = aetherProcessor.getDirectDependencies(groupId, model.getArtifactId(), version, runData); if (descriptorResult != null) { usages.add(processDescriptor(descriptorResult, runData, runData.getArtifact())); runData.incrementPomsProcessed(); } else { runData.incrementPomsReadError(); runData.getPomsInError().add(pom.getAbsolutePath()); } } catch (FileNotFoundException e) { LOGGER.error("unable to find pom file: " + pom.getAbsolutePath()); runData.incrementPomsReadError(); runData.getPomsInError().add(pom.getAbsolutePath()); } catch (IOException e) { LOGGER.error("unable to read pom file: " + pom.getAbsolutePath()); runData.incrementPomsReadError(); runData.getPomsInError().add(pom.getAbsolutePath()); } catch (XmlPullParserException e) { LOGGER.error("unable to parse pom file: " + pom.getAbsolutePath()); runData.incrementPomsReadError(); runData.getPomsInError().add(pom.getAbsolutePath()); } } runData.setUsages(usages); } private Usage processDescriptor(ArtifactDescriptorResult descriptorResult, RunData runData, String artifact) { Artifact artifactBeingProcessed = descriptorResult.getArtifact(); List<Dependency> dependencies = descriptorResult.getDependencies(); for (Dependency dependency : dependencies) { if (dependency.getArtifact().getGroupId().equals(runData.getGroup()) && dependency.getArtifact().getArtifactId().equals(artifact)) { // we have a match Usage usage = new Usage(); usage.setGroupId(artifactBeingProcessed.getGroupId()); usage.setArtifactId(artifactBeingProcessed.getArtifactId()); usage.setVersion(artifactBeingProcessed.getVersion()); usage.setVersionUsed(dependency.getArtifact().getVersion()); usage.setScope(dependency.getScope()); return usage; } } return null; } }
package com.celements.web.plugin; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.velocity.VelocityContext; import com.celements.mandatory.CheckMandatoryDocuments; import com.celements.navigation.cmd.GetMappedMenuItemsForParentCommand; import com.celements.pagetype.IPageType; import com.celements.rendering.RenderCommand; import com.celements.web.plugin.api.CelementsWebPluginApi; import com.celements.web.plugin.cmd.AddTranslationCommand; import com.celements.web.plugin.cmd.CelSendMail; import com.celements.web.plugin.cmd.CheckClassesCommand; import com.celements.web.plugin.cmd.PasswordRecoveryAndEmailValidationCommand; import com.celements.web.plugin.cmd.PossibleLoginsCommand; import com.celements.web.plugin.cmd.SkinConfigObjCommand; import com.celements.web.plugin.cmd.TokenBasedUploadCommand; import com.celements.web.plugin.cmd.UserNameForUserDataCommand; import com.celements.web.service.IPrepareVelocityContext; import com.celements.web.service.IWebUtilsService; import com.celements.web.token.NewCelementsTokenForUserCommand; import com.celements.web.utils.IWebUtils; import com.celements.web.utils.WebUtils; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.api.Api; import com.xpn.xwiki.api.Attachment; import com.xpn.xwiki.api.Document; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.classes.PasswordClass; import com.xpn.xwiki.plugin.XWikiDefaultPlugin; import com.xpn.xwiki.plugin.XWikiPluginInterface; import com.xpn.xwiki.store.XWikiStoreInterface; import com.xpn.xwiki.user.api.XWikiUser; import com.xpn.xwiki.util.Util; import com.xpn.xwiki.web.Utils; import com.xpn.xwiki.web.XWikiResponse; public class CelementsWebPlugin extends XWikiDefaultPlugin { private static Log LOGGER = LogFactory.getFactory().getInstance( CelementsWebPlugin.class); private final static IWebUtils util = WebUtils.getInstance(); final String PARAM_XPAGE = "xpage"; final String PARAM_CONF = "conf"; final String PARAM_AJAX_MODE = "ajax_mode"; final String PARAM_SKIN = "skin"; final String PARAM_LANGUAGE = "language"; final String PARAM_XREDIRECT = "xredirect"; private List<String> supportedAdminLangList; private CelSendMail injectedCelSendMail; public CelementsWebPlugin( String name, String className, XWikiContext context) { super(name, className, context); } public Api getPluginApi(XWikiPluginInterface plugin, XWikiContext context) { return new CelementsWebPluginApi((CelementsWebPlugin) plugin, context); } public String getName() { return getPrepareVelocityContextService().getVelocityName(); } public void init(XWikiContext context) { //TODO check if this is really needed for main-wiki or if we get a virtualInit on the //TODO main wiki to. (if needed move to ApplicationStartedEvent listener) LOGGER.trace("init called database [" + context.getDatabase() + "]"); if ("1".equals(context.getWiki().Param("celements.classCollections.checkOnStart", "1"))) { new CheckClassesCommand().checkClasses(); } if ("1".equals(context.getWiki().Param("celements.mandatory.checkOnStart", "1"))) { new CheckMandatoryDocuments().checkMandatoryDocuments(); } super.init(context); } public void virtualInit(XWikiContext context) { //TODO move to WikiReadyEvent listener (after migration to xwiki > 4.1-M1 LOGGER.trace("virtualInit called database [" + context.getDatabase() + "]"); if ("1".equals(context.getWiki().Param("celements.classCollections.checkOnStart", "1"))) { new CheckClassesCommand().checkClasses(); } if ("1".equals(context.getWiki().Param("celements.mandatory.checkOnStart", "1"))) { new CheckMandatoryDocuments().checkMandatoryDocuments(); } super.virtualInit(context); } public int queryCount() { return util.queryCount(); } /** * getSubMenuItemsForParent * get all submenu items of given parent document (by fullname). * * @param parent * @param menuSpace (default: $doc.space) * @param menuPart * @return (array of menuitems) */ public List<com.xpn.xwiki.api.Object> getSubMenuItemsForParent( String parent, String menuSpace, String menuPart, XWikiContext context) { return util.getSubMenuItemsForParent(parent, menuSpace, menuPart, context); } public String getVersionMode(XWikiContext context) { String versionMode = context.getWiki().getSpacePreference("celements_version", context); if ("---".equals(versionMode)) { versionMode = context.getWiki().getXWikiPreference("celements_version", "celements2", context); if ("---".equals(versionMode)) { versionMode = "celements2"; } } return versionMode; } /** * getUsernameForUserData * * @param login * @param possibleLogins * @param context * @return * @throws XWikiException * * @deprecated since 2.14.0 use UserNameForUserDataCommand instead */ @Deprecated public String getUsernameForUserData(String login, String possibleLogins, XWikiContext context) throws XWikiException{ return new UserNameForUserDataCommand().getUsernameForUserData(login, possibleLogins, context); } /** * * @param userToken * @param context * @return * @throws XWikiException * * @deprecated since 2.14.0 use TokenLDAPAuthServiceImpl instead */ @Deprecated public String getUsernameForToken(String userToken, XWikiContext context ) throws XWikiException{ String hashedCode = encryptString("hash:SHA-512:", userToken); String userDoc = ""; if((userToken != null) && (userToken.trim().length() > 0)){ String hql = ", BaseObject as obj, Classes.TokenClass as token where "; hql += "doc.space='XWiki' "; hql += "and obj.name=doc.fullName "; hql += "and token.tokenvalue=? "; hql += "and token.validuntil>=? "; hql += "and obj.id=token.id "; List<Object> parameterList = new Vector<Object>(); parameterList.add(hashedCode); parameterList.add(new Date()); XWikiStoreInterface storage = context.getWiki().getStore(); List<String> users = storage.searchDocumentsNames(hql, 0, 0, parameterList, context); LOGGER.info("searching token and found " + users.size() + " with parameters " + Arrays.deepToString(parameterList.toArray())); if(users == null || users.size() == 0) { String db = context.getDatabase(); context.setDatabase("xwiki"); users = storage.searchDocumentsNames(hql, 0, 0, parameterList, context); if(users != null && users.size() == 1) { users.add("xwiki:" + users.remove(0)); } context.setDatabase(db); } int usersFound = 0; for (String tmpUserDoc : users) { if(!tmpUserDoc.trim().equals("")) { usersFound++; userDoc = tmpUserDoc; } } if(usersFound > 1){ LOGGER.warn("Found more than one user for token '" + userToken + "'"); return null; } } else { LOGGER.warn("No valid token given"); } return userDoc; } /** * @deprecated since 2.22.0 * instead use NewCelementsTokenForUserCommand.getNewCelementsTokenForUserWithAutentication */ @Deprecated public String getNewCelementsTokenForUser(String accountName, Boolean guestPlus, XWikiContext context) throws XWikiException { return new NewCelementsTokenForUserCommand( ).getNewCelementsTokenForUserWithAuthentication(accountName, guestPlus, context); } public String encryptString(String encoding, String str) { return new PasswordClass().getEquivalentPassword(encoding, str); } public Map<String, String> activateAccount(String activationCode, XWikiContext context) throws XWikiException{ Map<String, String> userAccount = new HashMap<String, String>(); String hashedCode = encryptString("hash:SHA-512:", activationCode); String username = new UserNameForUserDataCommand().getUsernameForUserData(hashedCode, "validkey", context); if((username != null) && !username.equals("")){ String password = context.getWiki().generateRandomString(24); XWikiDocument doc = context.getWiki().getDocument(username, context); BaseObject obj = doc.getObject("XWiki.XWikiUsers"); // obj.set("validkey", "", context); obj.set("active", "1", context); obj.set("force_pwd_change", "1", context); obj.set("password", password, context); context.getWiki().saveDocument(doc, context); userAccount.put("username", username); userAccount.put("password", password); } return userAccount; } public String getEmailAdressForUser(String username, XWikiContext context) { if (context.getWiki().exists(username, context)) { try { XWikiDocument doc = context.getWiki().getDocument(username, context); BaseObject obj = doc.getObject("XWiki.XWikiUsers"); return obj.getStringValue("email"); } catch (XWikiException e) { LOGGER.error(e); } } return null; } //TODO Delegation can be removed as soon as latin1 flag can be removed /** * @deprecated since 2.19.0 instead use CelSendMail class directly. */ @Deprecated public int sendMail( String from, String replyTo, String to, String cc, String bcc, String subject, String htmlContent, String textContent, List<Attachment> attachments, Map<String, String> others, XWikiContext context){ return sendMail(from, replyTo, to, cc, bcc, subject, htmlContent, textContent, attachments, others, false, context); } /** * @deprecated since 2.19.0 instead use CelSendMail class directly. */ @Deprecated public int sendMail( String from, String replyTo, String to, String cc, String bcc, String subject, String htmlContent, String textContent, List<Attachment> attachments, Map<String, String> others, boolean isLatin1, XWikiContext context){ CelSendMail sender = getCelSendMail(context); sender.setFrom(from); sender.setReplyTo(replyTo); sender.setTo(to); sender.setCc(cc); sender.setBcc(bcc); sender.setSubject(subject); sender.setHtmlContent(htmlContent, isLatin1); sender.setTextContent(textContent); sender.setAttachments(attachments); sender.setOthers(others); return sender.sendMail(); } void injectCelSendMail(CelSendMail celSendMail) { this.injectedCelSendMail = celSendMail; } CelSendMail getCelSendMail(XWikiContext context) { if(injectedCelSendMail != null) { return injectedCelSendMail; } return new CelSendMail(context); } public List<Attachment> getAttachmentsForDocs(List<String> docsFN, XWikiContext context) { List<Attachment> attachments = new ArrayList<Attachment>(); for(String docFN : docsFN) { try { LOGGER.info("getAttachmentsForDocs: processing doc " + docFN); for(XWikiAttachment xwikiAttachment : context.getWiki().getDocument( docFN, context).getAttachmentList()) { LOGGER.info("getAttachmentsForDocs: adding attachment " + xwikiAttachment.getFilename() + " to list."); attachments.add(new Attachment(context.getWiki().getDocument( docFN, context).newDocument(context), xwikiAttachment, context)); } } catch (XWikiException e) { LOGGER.error(e); } } return attachments; } /** * @deprecated since 2.11.7 instead use renderCelementsDocument * on celementsweb scriptService */ @Deprecated public String renderCelementsPageType(XWikiDocument doc, IPageType pageType, XWikiContext context) throws XWikiException{ XWikiDocument viewTemplate = context.getWiki().getDocument( pageType.getRenderTemplate("view"), context); return context.getWiki().getRenderingEngine( ).renderDocument(viewTemplate, doc, context); } /** * @deprecated since 2.29.0 use SkinConfigObjCommand instead. */ @Deprecated public BaseObject getSkinConfigObj(XWikiContext context) { return new SkinConfigObjCommand().getSkinConfigObj(); } @Override public void beginRendering(XWikiContext context) { LOGGER.debug("start beginRendering: language [" + context.getLanguage() + "]."); try { getPrepareVelocityContextService().prepareVelocityContext(context); } catch(RuntimeException exp) { LOGGER.error("beginRendering", exp); throw exp; } LOGGER.debug("end beginRendering: language [" + context.getLanguage() + "]."); } @Override public void beginParsing(XWikiContext context) { LOGGER.debug("start beginParsing: language [" + context.getLanguage() + "]."); try { getPrepareVelocityContextService().prepareVelocityContext(context); } catch(RuntimeException exp) { LOGGER.error("beginParsing", exp); throw exp; } LOGGER.debug("end beginParsing: language [" + context.getLanguage() + "]."); } IPrepareVelocityContext getPrepareVelocityContextService() { return Utils.getComponent(IPrepareVelocityContext.class); } @SuppressWarnings("unchecked") public Map<String, String> getUniqueNameValueRequestMap(XWikiContext context) { Map<String, String[]> params = context.getRequest().getParameterMap(); Map<String, String> resultMap = new HashMap<String, String>(); for (String key : params.keySet()) { if((params.get(key) != null) && (params.get(key).length > 0)) { resultMap.put(key, params.get(key)[0]); } else { resultMap.put(key, ""); } } return resultMap; } public int createUser(boolean validate, XWikiContext context) throws XWikiException{ String possibleLogins = getPossibleLogins(context); return createUser(getUniqueNameValueRequestMap(context), possibleLogins, validate, context); } /** * @deprecated since 2.33.0 instead use PossibleLoginsCommand */ @Deprecated public String getPossibleLogins(XWikiContext context) { return new PossibleLoginsCommand().getPossibleLogins(); } @SuppressWarnings("deprecation") public synchronized int createUser(Map<String, String> userData, String possibleLogins, boolean validate, XWikiContext context) throws XWikiException { String accountName = ""; if(userData.containsKey("xwikiname")) { accountName = userData.get("xwikiname"); userData.remove("xwikiname"); } else { while(accountName.equals("") || context.getWiki().exists("XWiki." + accountName, context)){ accountName = context.getWiki().generateRandomString(12); } } String validkey = ""; int success = -1; if(areIdentifiersUnique(userData, possibleLogins, context)) { if(!userData.containsKey("password")) { String password = context.getWiki().generateRandomString(8); userData.put("password", password); } if(!userData.containsKey("validkey")) { validkey = getUniqueValidationKey(context); userData.put("validkey", validkey); } else { validkey = userData.get("validkey"); } if(!userData.containsKey("active")) { userData.put("active", "0"); } String content = "#includeForm(\"XWiki.XWikiUserSheet\")"; //TODO as soon as all installations are on xwiki 1.8+ change to new method (using // XWikiDocument.XWIKI10_SYNTAXID as additional parameter success = context.getWiki().createUser(accountName, userData, "XWiki.XWikiUsers", content, "edit", context); } if(success == 1){ // Set rights on user doc XWikiDocument doc = context.getWiki().getDocument("XWiki." + accountName, context); List<BaseObject> rightsObjs = doc.getObjects("XWiki.XWikiRights"); for (BaseObject rightObj : rightsObjs) { if(rightObj.getStringValue("groups").equals("")){ rightObj.set("users", doc.getFullName(), context); rightObj.set("allow", "1", context); rightObj.set("levels", "view,edit,delete", context); rightObj.set("groups", "", context); } else{ rightObj.set("users", "", context); rightObj.set("allow", "1", context); rightObj.set("levels", "view,edit,delete", context); rightObj.set("groups", "XWiki.XWikiAdminGroup", context); } } context.getWiki().saveDocument(doc, context); if(validate) { LOGGER.info("send account validation mail with data: accountname='" + accountName + "', email='" + userData.get("email") + "', validkey='" + validkey + "'"); try{ new PasswordRecoveryAndEmailValidationCommand().sendValidationMessage( userData.get("email"), validkey, "Tools.AccountActivationMail", context); } catch(XWikiException e){ LOGGER.error("Exception while sending validation mail to '" + userData.get("email") + "'", e); } } } return success; } private boolean areIdentifiersUnique(Map<String, String> userData, String possibleLogins, XWikiContext context) throws XWikiException { boolean isUnique = true; for (String key : userData.keySet()) { if(!"".equals(key.trim()) && (("," + possibleLogins + ",").indexOf("," + key + ",") >= 0)) { String user = getUsernameForUserData(userData.get(key), possibleLogins, context); if((user == null) || (user.length() > 0)) { //user == "" means there is no such user isUnique = false; } } } return isUnique; } /** * getUniqueValidationKey * * @param context * @return * @throws XWikiException * * @deprecated since 2.14.0 use NewCelementsTokenForUserCommand instead */ @Deprecated public String getUniqueValidationKey(XWikiContext context) throws XWikiException { return new NewCelementsTokenForUserCommand().getUniqueValidationKey(context); } /** * * @param attachToDoc * @param fieldName * @param userToken * @param context * @return * @throws XWikiException * * @deprecated since 2.28.0 use TokenBasedUploadCommand instead */ @Deprecated public int tokenBasedUpload(Document attachToDoc, String fieldName, String userToken, XWikiContext context) throws XWikiException { return new TokenBasedUploadCommand().tokenBasedUpload(attachToDoc, fieldName, userToken, context); } /** * * @param attachToDocFN * @param fieldName * @param userToken * @param createIfNotExists * @param context * @return * @throws XWikiException * * @deprecated since 2.28.0 use TokenBasedUploadCommand instead */ @Deprecated public int tokenBasedUpload(String attachToDocFN, String fieldName, String userToken, Boolean createIfNotExists, XWikiContext context) throws XWikiException { return new TokenBasedUploadCommand().tokenBasedUpload(attachToDocFN, fieldName, userToken, createIfNotExists, context); } /** * * @param userToken * @param context * @return * @throws XWikiException * * @deprecated since 2.14.0 use TokenLDAPAuthServiceImpl instead */ @Deprecated public XWikiUser checkAuthByToken(String userToken, XWikiContext context ) throws XWikiException { String username = getUsernameForToken(userToken, context); if((username != null) && !username.equals("")){ LOGGER.info("checkAuthByToken: user " + username + " identified by userToken."); context.setUser(username); return context.getXWikiUser(); } else { LOGGER.warn("checkAuthByToken: username could not be identified by token"); } return null; } public XWikiUser checkAuth(String logincredential, String password, String rememberme, String possibleLogins, Boolean noRedirect, XWikiContext context ) throws XWikiException { String loginname = getUsernameForUserData(logincredential, possibleLogins, context); if ("".equals(loginname) && possibleLogins.matches("(.*,)?loginname(,.*)?")) { loginname = logincredential; } if (noRedirect != null) { context.put("ajax", noRedirect); } return context.getWiki().getAuthService().checkAuth(loginname, password, rememberme, context); } public void enableMappedMenuItems(XWikiContext context) { GetMappedMenuItemsForParentCommand cmd = new GetMappedMenuItemsForParentCommand(); cmd.set_isActive(true); context.put(GetMappedMenuItemsForParentCommand.CELEMENTS_MAPPED_MENU_ITEMS_KEY, cmd); } public boolean executeAction(Document actionDoc, Map<String, String[]> request, XWikiDocument includingDoc, XWikiContext context) { LOGGER.info("Executing action on doc '" + actionDoc.getFullName() + "'"); VelocityContext vcontext = ((VelocityContext) context.get("vcontext")); vcontext.put("theDoc", actionDoc); Boolean debug = (Boolean)vcontext.get("debug"); vcontext.put("debug", true); Boolean hasedit = (Boolean)vcontext.get("hasedit"); vcontext.put("hasedit", true); Object req = vcontext.get("request"); vcontext.put("request", getApiUsableMap(request)); XWikiDocument execAct = null; try { execAct = context.getWiki() .getDocument("celements2web:Macros.executeActions", context); } catch (XWikiException e) { LOGGER.error("Could not get action Macro", e); } String execContent = ""; String actionContent = ""; if(execAct != null) { execContent = execAct.getContent(); execContent = execContent.replaceAll("\\{(/?)pre\\}", ""); actionContent = context.getWiki().getRenderingEngine().interpretText( execContent, includingDoc, context); } Object successfulObj = vcontext.get("successful"); boolean successful = (successfulObj != null) && "true".equals(successfulObj.toString()); if(!successful) { LOGGER.error("executeAction: Error executing action. Output:" + vcontext.get( "actionScriptOutput")); LOGGER.error("executeAction: Rendered Action Script: " + actionContent); LOGGER.debug("executeAction: execAct == " + execAct); LOGGER.debug("executeAction: execContent length: " + execContent.length()); LOGGER.debug("executeAction: execContent length: " + actionContent.length()); } vcontext.put("debug", debug); vcontext.put("hasedit", hasedit); vcontext.put("request", req); return successful; } //FIXME Hack to get mail execution to work. The script is not expecting arrays in the // map, since it expects a request. Multiple values with the same name get lost // in this "quick and dirty" fix private Object getApiUsableMap(Map<String, String[]> request) { Map<String, String> apiConform = new HashMap<String, String>(); for (String key : request.keySet()) { if((request.get(key) != null) && (request.get(key).length > 0)) { apiConform.put(key, request.get(key)[0]); } else { apiConform.put(key, null); } } return apiConform; } public List<String> getSupportedAdminLanguages() { if (supportedAdminLangList == null) { setSupportedAdminLanguages(Arrays.asList(new String[] {"de","fr","en","it"})); } return supportedAdminLangList; } public void setSupportedAdminLanguages(List<String> newSupportedAdminLangList) { supportedAdminLangList = newSupportedAdminLangList; } public boolean writeUTF8Response(String filename, String renderDocFullName, XWikiContext context) { boolean success = false; if(context.getWiki().exists(renderDocFullName, context)) { XWikiDocument renderDoc; try { renderDoc = context.getWiki().getDocument(renderDocFullName, context); adjustResponseHeader(filename, context.getResponse(), context); setResponseContent(renderDoc, context.getResponse(), context); } catch (XWikiException e) { LOGGER.error(e); } context.setFinished(true); } return success; } void adjustResponseHeader(String filename, XWikiResponse response, XWikiContext context) { response.setContentType("text/plain"); String ofilename = Util.encodeURI(filename, context).replaceAll("\\+", " "); response.addHeader("Content-disposition", "attachment; filename=\"" + ofilename + "\"; charset='UTF-8'"); } void setResponseContent(XWikiDocument renderDoc, XWikiResponse response, XWikiContext context) throws XWikiException { String renderedContent = new RenderCommand().renderDocument(renderDoc); byte[] data = {}; try { data = renderedContent.getBytes("UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } response.setContentLength(data.length + 3); try { response.getOutputStream().write(new byte[]{(byte)0xEF, (byte)0xBB, (byte)0xBF}); response.getOutputStream().write(data); } catch (IOException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION, "Exception while sending response", e); } } public boolean isFormFilled(Map<String, String[]> parameterMap, Set<String> additionalFields) { boolean isFilled = false; if(parameterMap.size() > getIsFilledModifier(parameterMap, additionalFields)) { isFilled = true; } return isFilled; } short getIsFilledModifier(Map<String, String[]> parameterMap, Set<String> additionalFields) { List<String> standardParams = new ArrayList<String>(); standardParams.add(PARAM_XPAGE); standardParams.add(PARAM_CONF); standardParams.add(PARAM_AJAX_MODE); standardParams.add(PARAM_SKIN); standardParams.add(PARAM_LANGUAGE); standardParams.add(PARAM_XREDIRECT); short modifier = 0; if(parameterMap.containsKey(PARAM_XPAGE) && parameterMap.containsKey(PARAM_CONF) && arrayContains(parameterMap.get(PARAM_XPAGE), "overlay")) { modifier += 1; } if(parameterMap.containsKey(PARAM_XPAGE) && parameterMap.containsKey(PARAM_AJAX_MODE) && arrayContains(parameterMap.get(PARAM_XPAGE), "celements_ajax")) { modifier += 1; if(parameterMap.containsKey(PARAM_SKIN)) { modifier += 1; } } if(parameterMap.containsKey(PARAM_XPAGE)) { modifier += 1; } if(parameterMap.containsKey(PARAM_XREDIRECT)) { modifier += 1; } if(parameterMap.containsKey(PARAM_LANGUAGE)) { modifier += 1; } if((additionalFields != null) && additionalFields.size() > 0) { for (String param : additionalFields) { if(!standardParams.contains(param) && parameterMap.containsKey(param)) { modifier += 1; } } } return modifier; } boolean arrayContains(String[] array, String value) { Arrays.sort(array); return (Arrays.binarySearch(array, value) >= 0); } /** * @deprecated since 2.14.0 use IWebUtilsService instead */ @Deprecated public String getDefaultLanguage(XWikiContext context) { return getWebService().getDefaultLanguage(); } private IWebUtilsService getWebService() { return Utils.getComponent(IWebUtilsService.class); } /** * addTranslation * @param fullName * @param language * @param context * @return * * @deprecated since 2.14.0 please use the AddTranslationCommand directly */ @Deprecated public boolean addTranslation(String fullName, String language, XWikiContext context) { return new AddTranslationCommand().addTranslation(fullName, language, context); } }
package com.celements.web.plugin; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.Principal; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.velocity.VelocityContext; import com.celements.navigation.MenuItemNavigation; import com.celements.navigation.MenuTypeRepository; import com.celements.navigation.Navigation; import com.celements.navigation.cmd.GetMappedMenuItemsForParentCommand; import com.celements.web.pagetype.IPageType; import com.celements.web.pagetype.RenderCommand; import com.celements.web.plugin.api.CelementsWebPluginApi; import com.celements.web.plugin.cmd.AddTranslationCommand; import com.celements.web.plugin.cmd.CelSendMail; import com.celements.web.plugin.cmd.CheckClassesCommand; import com.celements.web.plugin.cmd.PasswordRecoveryAndEmailValidationCommand; import com.celements.web.plugin.cmd.UserNameForUserDataCommand; import com.celements.web.service.IPrepareVelocityContext; import com.celements.web.service.IWebUtilsService; import com.celements.web.token.NewCelementsTokenForUserCommand; import com.celements.web.utils.IWebUtils; import com.celements.web.utils.WebUtils; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.api.Api; import com.xpn.xwiki.api.Attachment; import com.xpn.xwiki.api.Document; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.classes.PasswordClass; import com.xpn.xwiki.plugin.XWikiDefaultPlugin; import com.xpn.xwiki.plugin.XWikiPluginInterface; import com.xpn.xwiki.store.XWikiStoreInterface; import com.xpn.xwiki.user.api.XWikiUser; import com.xpn.xwiki.util.Util; import com.xpn.xwiki.web.Utils; import com.xpn.xwiki.web.XWikiResponse; public class CelementsWebPlugin extends XWikiDefaultPlugin { private static Log LOGGER = LogFactory.getFactory().getInstance( CelementsWebPlugin.class); private final static IWebUtils util = WebUtils.getInstance(); final String PARAM_XPAGE = "xpage"; final String PARAM_CONF = "conf"; final String PARAM_AJAX_MODE = "ajax_mode"; final String PARAM_SKIN = "skin"; final String PARAM_LANGUAGE = "language"; final String PARAM_XREDIRECT = "xredirect"; private List<String> supportedAdminLangList; private CelSendMail injectedCelSendMail; public CelementsWebPlugin( String name, String className, XWikiContext context) { super(name, className, context); } public Api getPluginApi(XWikiPluginInterface plugin, XWikiContext context) { return new CelementsWebPluginApi((CelementsWebPlugin) plugin, context); } public String getName() { return getPrepareVelocityContextService().getVelocityName(); } public void flushCache() { //TODO: check if flushCache is called for changing a page MenuItem. LOGGER.debug("Entered method flushCache"); } public void flushCache(XWikiContext context) { util.flushMenuItemCache(context); } public void init(XWikiContext context) { LOGGER.trace("init called database [" + context.getDatabase() + "]"); addMenuTypeMenuItemToRepository(); new CheckClassesCommand().checkClasses(context); super.init(context); } public void virtualInit(XWikiContext context) { LOGGER.trace("virtualInit called database [" + context.getDatabase() + "]"); new CheckClassesCommand().checkClasses(context); super.virtualInit(context); } private void addMenuTypeMenuItemToRepository() { if (MenuTypeRepository.getInstance().put(Navigation.MENU_TYPE_MENUITEM, new MenuItemNavigation())) { LOGGER.debug("Added MenuItemNavigation with key '" + Navigation.MENU_TYPE_MENUITEM + "' to the " + "MenuTypeRepository"); } } public int queryCount() { return util.queryCount(); } /** * getSubMenuItemsForParent * get all submenu items of given parent document (by fullname). * * @param parent * @param menuSpace (default: $doc.space) * @param menuPart * @return (array of menuitems) */ public List<com.xpn.xwiki.api.Object> getSubMenuItemsForParent( String parent, String menuSpace, String menuPart, XWikiContext context) { return util.getSubMenuItemsForParent(parent, menuSpace, menuPart, context); } public String getVersionMode(XWikiContext context) { String versionMode = context.getWiki().getSpacePreference("celements_version", context); if ("---".equals(versionMode)) { versionMode = context.getWiki().getXWikiPreference("celements_version", "celements2", context); if ("---".equals(versionMode)) { versionMode = "celements2"; } } return versionMode; } /** * getUsernameForUserData * * @param login * @param possibleLogins * @param context * @return * @throws XWikiException * * @deprecated since 2.14.0 use UserNameForUserDataCommand instead */ @Deprecated public String getUsernameForUserData(String login, String possibleLogins, XWikiContext context) throws XWikiException{ return new UserNameForUserDataCommand().getUsernameForUserData(login, possibleLogins, context); } /** * * @param userToken * @param context * @return * @throws XWikiException * * @deprecated since 2.14.0 use TokenLDAPAuthServiceImpl instead */ @Deprecated public String getUsernameForToken(String userToken, XWikiContext context ) throws XWikiException{ String hashedCode = encryptString("hash:SHA-512:", userToken); String userDoc = ""; if((userToken != null) && (userToken.trim().length() > 0)){ String hql = ", BaseObject as obj, Classes.TokenClass as token where "; hql += "doc.space='XWiki' "; hql += "and obj.name=doc.fullName "; hql += "and token.tokenvalue=? "; hql += "and token.validuntil>=? "; hql += "and obj.id=token.id "; List<Object> parameterList = new Vector<Object>(); parameterList.add(hashedCode); parameterList.add(new Date()); XWikiStoreInterface storage = context.getWiki().getStore(); List<String> users = storage.searchDocumentsNames(hql, 0, 0, parameterList, context); LOGGER.info("searching token and found " + users.size() + " with parameters " + Arrays.deepToString(parameterList.toArray())); if(users == null || users.size() == 0) { String db = context.getDatabase(); context.setDatabase("xwiki"); users = storage.searchDocumentsNames(hql, 0, 0, parameterList, context); if(users != null && users.size() == 1) { users.add("xwiki:" + users.remove(0)); } context.setDatabase(db); } int usersFound = 0; for (String tmpUserDoc : users) { if(!tmpUserDoc.trim().equals("")) { usersFound++; userDoc = tmpUserDoc; } } if(usersFound > 1){ LOGGER.warn("Found more than one user for token '" + userToken + "'"); return null; } } else { LOGGER.warn("No valid token given"); } return userDoc; } /** * * @param accountName * @param guestPlus. if user is XWiki.XWikiGuest and guestPlus is true the account * XWiki.XWikiGuestPlus will be used to get the token. * @param context * @return token (or null if token can not be generated) * @throws XWikiException */ public String getNewCelementsTokenForUser(String accountName, Boolean guestPlus, XWikiContext context) throws XWikiException { if (!"".equals(context.getRequest().getParameter("j_username")) && !"".equals(context.getRequest().getParameter("j_password"))) { LOGGER.info("getNewCelementsTokenForUser: trying to authenticate " + context.getRequest().getParameter("j_username")); Principal principal = context.getWiki().getAuthService().authenticate( context.getRequest().getParameter("j_username"), context.getRequest().getParameter("j_password"), context); if(principal != null) { LOGGER.info("getNewCelementsTokenForUser: successfully autenthicated " + principal.getName()); context.setUser(principal.getName()); accountName = principal.getName(); } } return new NewCelementsTokenForUserCommand().getNewCelementsTokenForUser(accountName, guestPlus, context); } public String encryptString(String encoding, String str) { return new PasswordClass().getEquivalentPassword(encoding, str); } public Map<String, String> activateAccount(String activationCode, XWikiContext context) throws XWikiException{ Map<String, String> userAccount = new HashMap<String, String>(); String hashedCode = encryptString("hash:SHA-512:", activationCode); String username = new UserNameForUserDataCommand().getUsernameForUserData(hashedCode, "validkey", context); if((username != null) && !username.equals("")){ String password = context.getWiki().generateRandomString(24); XWikiDocument doc = context.getWiki().getDocument(username, context); BaseObject obj = doc.getObject("XWiki.XWikiUsers"); // obj.set("validkey", "", context); obj.set("active", "1", context); obj.set("force_pwd_change", "1", context); obj.set("password", password, context); context.getWiki().saveDocument(doc, context); userAccount.put("username", username); userAccount.put("password", password); } return userAccount; } public String getEmailAdressForUser(String username, XWikiContext context) { if (context.getWiki().exists(username, context)) { try { XWikiDocument doc = context.getWiki().getDocument(username, context); BaseObject obj = doc.getObject("XWiki.XWikiUsers"); return obj.getStringValue("email"); } catch (XWikiException e) { LOGGER.error(e); } } return null; } //TODO Delegation can be removed as soon as latin1 flag can be removed public int sendMail( String from, String replyTo, String to, String cc, String bcc, String subject, String htmlContent, String textContent, List<Attachment> attachments, Map<String, String> others, XWikiContext context){ return sendMail(from, replyTo, to, cc, bcc, subject, htmlContent, textContent, attachments, others, false, context); } public int sendMail( String from, String replyTo, String to, String cc, String bcc, String subject, String htmlContent, String textContent, List<Attachment> attachments, Map<String, String> others, boolean isLatin1, XWikiContext context){ CelSendMail sender = getCelSendMail(context); sender.setFrom(from); sender.setReplyTo(replyTo); sender.setTo(to); sender.setCc(cc); sender.setBcc(bcc); sender.setSubject(subject); sender.setHtmlContent(htmlContent, isLatin1); sender.setTextContent(textContent); sender.setAttachments(attachments); sender.setOthers(others); return sender.sendMail(); } void injectCelSendMail(CelSendMail celSendMail) { this.injectedCelSendMail = celSendMail; } CelSendMail getCelSendMail(XWikiContext context) { if(injectedCelSendMail != null) { return injectedCelSendMail; } return new CelSendMail(context); } public List<Attachment> getAttachmentsForDocs(List<String> docsFN, XWikiContext context) { List<Attachment> attachments = new ArrayList<Attachment>(); for(String docFN : docsFN) { try { LOGGER.info("getAttachmentsForDocs: processing doc " + docFN); for(XWikiAttachment xwikiAttachment : context.getWiki().getDocument( docFN, context).getAttachmentList()) { LOGGER.info("getAttachmentsForDocs: adding attachment " + xwikiAttachment.getFilename() + " to list."); attachments.add(new Attachment(context.getWiki().getDocument( docFN, context).newDocument(context), xwikiAttachment, context)); } } catch (XWikiException e) { LOGGER.error(e); } } return attachments; } /** * @deprecated since 2.11.7 instead use renderCelementsDocument * on celementsweb scriptService */ @Deprecated public String renderCelementsPageType(XWikiDocument doc, IPageType pageType, XWikiContext context) throws XWikiException{ XWikiDocument viewTemplate = context.getWiki().getDocument( pageType.getRenderTemplate("view"), context); return context.getWiki().getRenderingEngine( ).renderDocument(viewTemplate, doc, context); } public BaseObject getSkinConfigObj(XWikiContext context) { XWikiDocument doc = context.getDoc(); try { XWiki xwiki = context.getWiki(); XWikiDocument skinDoc = xwiki.getDocument( xwiki.getSpacePreference("skin", context), context); String className = skinDoc.getObject("XWiki.XWikiSkins").getStringValue( "skin_config_class_name"); BaseObject configObj = util.getConfigDocByInheritance(doc, className, context).getObject(className); return configObj; } catch(XWikiException e){ LOGGER.error(e); } return null; } @Override public void beginRendering(XWikiContext context) { LOGGER.debug("start beginRendering: language [" + context.getLanguage() + "]."); try { getPrepareVelocityContextService().prepareVelocityContext(context); } catch(RuntimeException exp) { LOGGER.error("beginRendering", exp); throw exp; } LOGGER.debug("end beginRendering: language [" + context.getLanguage() + "]."); } @Override public void beginParsing(XWikiContext context) { LOGGER.debug("start beginParsing: language [" + context.getLanguage() + "]."); try { getPrepareVelocityContextService().prepareVelocityContext(context); } catch(RuntimeException exp) { LOGGER.error("beginParsing", exp); throw exp; } LOGGER.debug("end beginParsing: language [" + context.getLanguage() + "]."); } IPrepareVelocityContext getPrepareVelocityContextService() { return Utils.getComponent(IPrepareVelocityContext.class); } @SuppressWarnings("unchecked") public Map<String, String> getUniqueNameValueRequestMap(XWikiContext context) { Map<String, String[]> params = context.getRequest().getParameterMap(); Map<String, String> resultMap = new HashMap<String, String>(); for (String key : params.keySet()) { if((params.get(key) != null) && (params.get(key).length > 0)) { resultMap.put(key, params.get(key)[0]); } else { resultMap.put(key, ""); } } return resultMap; } public int createUser(boolean validate, XWikiContext context) throws XWikiException{ String possibleLogins = context.getWiki().getXWikiPreference("cellogin", context); if((possibleLogins == null) || "".equals(possibleLogins)) { String db = context.getDatabase(); context.setDatabase("celements2web"); possibleLogins = context.getWiki().getXWikiPreference("cellogin", context); context.setDatabase(db); if((possibleLogins == null) || "".equals(possibleLogins)) { possibleLogins = "loginname"; } } return createUser(getUniqueNameValueRequestMap(context), possibleLogins, validate, context); } @SuppressWarnings("deprecation") public synchronized int createUser(Map<String, String> userData, String possibleLogins, boolean validate, XWikiContext context) throws XWikiException { String accountName = ""; if(userData.containsKey("xwikiname")) { accountName = userData.get("xwikiname"); userData.remove("xwikiname"); } else { while(accountName.equals("") || context.getWiki().exists("XWiki." + accountName, context)){ accountName = context.getWiki().generateRandomString(12); } } String validkey = ""; int success = -1; if(areIdentifiersUnique(userData, possibleLogins, context)) { if(!userData.containsKey("password")) { String password = context.getWiki().generateRandomString(8); userData.put("password", password); } if(!userData.containsKey("validkey")) { validkey = getUniqueValidationKey(context); userData.put("validkey", validkey); } else { validkey = userData.get("validkey"); } if(!userData.containsKey("active")) { userData.put("active", "0"); } String content = "#includeForm(\"XWiki.XWikiUserSheet\")"; //TODO as soon as all installations are on xwiki 1.8+ change to new method (using // XWikiDocument.XWIKI10_SYNTAXID as additional parameter success = context.getWiki().createUser(accountName, userData, "XWiki.XWikiUsers", content, "edit", context); } if(success == 1){ // Set rights on user doc XWikiDocument doc = context.getWiki().getDocument("XWiki." + accountName, context); List<BaseObject> rightsObjs = doc.getObjects("XWiki.XWikiRights"); for (BaseObject rightObj : rightsObjs) { if(rightObj.getStringValue("groups").equals("")){ rightObj.set("users", doc.getFullName(), context); rightObj.set("allow", "1", context); rightObj.set("levels", "view,edit,delete", context); rightObj.set("groups", "", context); } else{ rightObj.set("users", "", context); rightObj.set("allow", "1", context); rightObj.set("levels", "view,edit,delete", context); rightObj.set("groups", "XWiki.XWikiAdminGroup", context); } } context.getWiki().saveDocument(doc, context); if(validate) { LOGGER.info("send account validation mail with data: accountname='" + accountName + "', email='" + userData.get("email") + "', validkey='" + validkey + "'"); try{ new PasswordRecoveryAndEmailValidationCommand().sendValidationMessage( userData.get("email"), validkey, "Tools.AccountActivationMail", context); } catch(XWikiException e){ LOGGER.error("Exception while sending validation mail to '" + userData.get("email") + "'", e); } } } return success; } private boolean areIdentifiersUnique(Map<String, String> userData, String possibleLogins, XWikiContext context) throws XWikiException { boolean isUnique = true; for (String key : userData.keySet()) { if(!"".equals(key.trim()) && (("," + possibleLogins + ",").indexOf("," + key + ",") >= 0)) { String user = getUsernameForUserData(userData.get(key), possibleLogins, context); if((user == null) || (user.length() > 0)) { //user == "" means there is no such user isUnique = false; } } } return isUnique; } /** * getUniqueValidationKey * * @param context * @return * @throws XWikiException * * @deprecated since 2.14.0 use NewCelementsTokenForUserCommand instead */ @Deprecated public String getUniqueValidationKey(XWikiContext context) throws XWikiException { return new NewCelementsTokenForUserCommand().getUniqueValidationKey(context); } @Deprecated public int tokenBasedUpload(Document attachToDoc, String fieldName, String userToken, XWikiContext context) throws XWikiException { String username = getUsernameForToken(userToken, context); if((username != null) && !username.equals("")){ LOGGER.info("tokenBasedUpload: user " + username + " identified by userToken."); context.setUser(username); return attachToDoc.addAttachments(fieldName); } else { LOGGER.warn("tokenBasedUpload: username could not be identified by token"); } return 0; } public int tokenBasedUpload(String attachToDocFN, String fieldName, String userToken, Boolean createIfNotExists, XWikiContext context) throws XWikiException { String username = getUsernameForToken(userToken, context); if((username != null) && !username.equals("")){ LOGGER.info("tokenBasedUpload: user " + username + " identified by userToken."); context.setUser(username); XWikiDocument doc = context.getWiki().getDocument(attachToDocFN, context); if (createIfNotExists || context.getWiki().exists(attachToDocFN, context)) { LOGGER.info("tokenBasedUpload: add attachment."); return doc.newDocument(context).addAttachments(fieldName); } else { LOGGER.warn("tokenBasedUpload: document " + attachToDocFN + " does not exist."); } } else { LOGGER.warn("tokenBasedUpload: username could not be identified by token"); } return 0; } /** * * @param userToken * @param context * @return * @throws XWikiException * * @deprecated since 2.14.0 use TokenLDAPAuthServiceImpl instead */ @Deprecated public XWikiUser checkAuthByToken(String userToken, XWikiContext context ) throws XWikiException { String username = getUsernameForToken(userToken, context); if((username != null) && !username.equals("")){ LOGGER.info("checkAuthByToken: user " + username + " identified by userToken."); context.setUser(username); return context.getXWikiUser(); } else { LOGGER.warn("checkAuthByToken: username could not be identified by token"); } return null; } public XWikiUser checkAuth(String logincredential, String password, String rememberme, String possibleLogins, XWikiContext context ) throws XWikiException { String loginname = getUsernameForUserData(logincredential, possibleLogins, context); if ("".equals(loginname) && possibleLogins.matches("(.*,)?loginname(,.*)?")) { loginname = logincredential; } return context.getWiki().getAuthService().checkAuth(loginname, password, rememberme, context); } public void enableMappedMenuItems(XWikiContext context) { GetMappedMenuItemsForParentCommand cmd = new GetMappedMenuItemsForParentCommand(); cmd.set_isActive(true); context.put(GetMappedMenuItemsForParentCommand.CELEMENTS_MAPPED_MENU_ITEMS_KEY, cmd); } public boolean executeAction(Document actionDoc, Map<String, String[]> request, XWikiDocument includingDoc, XWikiContext context) { LOGGER.info("Executing action on doc '" + actionDoc.getFullName() + "'"); VelocityContext vcontext = ((VelocityContext) context.get("vcontext")); vcontext.put("theDoc", actionDoc); Boolean debug = (Boolean)vcontext.get("debug"); vcontext.put("debug", true); Boolean hasedit = (Boolean)vcontext.get("hasedit"); vcontext.put("hasedit", true); Object req = vcontext.get("request"); vcontext.put("request", getApiUsableMap(request)); XWikiDocument execAct = null; try { execAct = context.getWiki() .getDocument("celements2web:Macros.executeActions", context); } catch (XWikiException e) { LOGGER.error("Could not get action Macro", e); } String actionContent = ""; if(execAct != null) { String execContent = execAct.getContent(); execContent = execContent.replaceAll("\\{(/?)pre\\}", ""); actionContent = context.getWiki().getRenderingEngine().interpretText( execContent, includingDoc, context); } boolean successful = "true".equals(vcontext.get("successful")); if(!successful) { LOGGER.error("Error executing action. Output:" + vcontext.get("actionScriptOutput")); LOGGER.error("Rendered Action Script: " + actionContent); } vcontext.put("debug", debug); vcontext.put("hasedit", hasedit); vcontext.put("request", req); return successful; } //FIXME Hack to get mail execution to work. The script is not expecting arrays in the // map, since it expects a request. Multiple values with the same name get lost // in this "quick and dirty" fix private Object getApiUsableMap(Map<String, String[]> request) { Map<String, String> apiConform = new HashMap<String, String>(); for (String key : request.keySet()) { if((request.get(key) != null) && (request.get(key).length > 0)) { apiConform.put(key, request.get(key)[0]); } else { apiConform.put(key, null); } } return apiConform; } public List<String> getSupportedAdminLanguages() { if (supportedAdminLangList == null) { setSupportedAdminLanguages(Arrays.asList(new String[] {"de","fr","en","it"})); } return supportedAdminLangList; } public void setSupportedAdminLanguages(List<String> newSupportedAdminLangList) { supportedAdminLangList = newSupportedAdminLangList; } public boolean writeUTF8Response(String filename, String renderDocFullName, XWikiContext context) { boolean success = false; if(context.getWiki().exists(renderDocFullName, context)) { XWikiDocument renderDoc; try { renderDoc = context.getWiki().getDocument(renderDocFullName, context); adjustResponseHeader(filename, context.getResponse(), context); setResponseContent(renderDoc, context.getResponse(), context); } catch (XWikiException e) { LOGGER.error(e); } context.setFinished(true); } return success; } void adjustResponseHeader(String filename, XWikiResponse response, XWikiContext context) { response.setContentType("text/plain"); String ofilename = Util.encodeURI(filename, context).replaceAll("\\+", " "); response.addHeader("Content-disposition", "attachment; filename=\"" + ofilename + "\"; charset='UTF-8'"); } void setResponseContent(XWikiDocument renderDoc, XWikiResponse response, XWikiContext context) throws XWikiException { String renderedContent = new RenderCommand().renderDocument(renderDoc); byte[] data = {}; try { data = renderedContent.getBytes("UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } response.setContentLength(data.length + 3); try { response.getOutputStream().write(new byte[]{(byte)0xEF, (byte)0xBB, (byte)0xBF}); response.getOutputStream().write(data); } catch (IOException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION, "Exception while sending response", e); } } public boolean isFormFilled(Map<String, String[]> parameterMap, Set<String> additionalFields) { boolean isFilled = false; if(parameterMap.size() > getIsFilledModifier(parameterMap, additionalFields)) { isFilled = true; } return isFilled; } short getIsFilledModifier(Map<String, String[]> parameterMap, Set<String> additionalFields) { List<String> standardParams = new ArrayList<String>(); standardParams.add(PARAM_XPAGE); standardParams.add(PARAM_CONF); standardParams.add(PARAM_AJAX_MODE); standardParams.add(PARAM_SKIN); standardParams.add(PARAM_LANGUAGE); standardParams.add(PARAM_XREDIRECT); short modifier = 0; if(parameterMap.containsKey(PARAM_XPAGE) && parameterMap.containsKey(PARAM_CONF) && arrayContains(parameterMap.get(PARAM_XPAGE), "overlay")) { modifier += 1; } if(parameterMap.containsKey(PARAM_XPAGE) && parameterMap.containsKey(PARAM_AJAX_MODE) && arrayContains(parameterMap.get(PARAM_XPAGE), "celements_ajax")) { modifier += 1; if(parameterMap.containsKey(PARAM_SKIN)) { modifier += 1; } } if(parameterMap.containsKey(PARAM_XPAGE)) { modifier += 1; } if(parameterMap.containsKey(PARAM_XREDIRECT)) { modifier += 1; } if(parameterMap.containsKey(PARAM_LANGUAGE)) { modifier += 1; } if((additionalFields != null) && additionalFields.size() > 0) { for (String param : additionalFields) { if(!standardParams.contains(param) && parameterMap.containsKey(param)) { modifier += 1; } } } return modifier; } boolean arrayContains(String[] array, String value) { Arrays.sort(array); return (Arrays.binarySearch(array, value) >= 0); } /** * @deprecated since 2.14.0 use IWebUtilsService instead */ @Deprecated public String getDefaultLanguage(XWikiContext context) { return getWebService().getDefaultLanguage(); } private IWebUtilsService getWebService() { return Utils.getComponent(IWebUtilsService.class); } /** * addTranslation * @param fullName * @param language * @param context * @return * * @deprecated since 2.14.0 please use the AddTranslationCommand directly */ @Deprecated public boolean addTranslation(String fullName, String language, XWikiContext context) { return new AddTranslationCommand().addTranslation(fullName, language, context); } }
package com.epam.ta.reportportal.dao; import com.epam.ta.reportportal.entity.user.User; import com.epam.ta.reportportal.entity.user.UserRole; import com.epam.ta.reportportal.entity.user.UserType; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.Set; /** * @author Ivan Budayeu */ public interface UserRepository extends ReportPortalRepository<User, Long>, UserRepositoryCustom { Optional<User> findByDefaultProjectId(Long projectId); Optional<User> findByEmail(String email); /** * @param login user login for search * @return Optional<User> */ Optional<User> findByLogin(String login); List<User> findAllByEmailIn(Iterable<String> mails); List<User> findAllByLoginIn(Set<String> loginSet); List<User> findAllByRole(UserRole role); @Query(value = "SELECT u FROM User u WHERE u.userType = :userType AND u.isExpired = :isExpired") Page<User> findAllByUserTypeAndExpired(@Param("userType") UserType userType, @Param("isExpired") boolean isExpired, Pageable pageable); @Query(value = "UPDATE users SET users.expired = TRUE WHERE CAST(metadata->>'last_login' AS TIMESTAMP) < :lastLogin", nativeQuery = true) void expireUsersLoggedOlderThan(@Param("lastLogin") Date lastLogin); @Query(value = "UPDATE users SET metadata = jsonb_set(metadata, '{last_login}', to_jsonb(:lastLogin::text), true ) WHERE users.login = :username;", nativeQuery = true) void updateLastLoginDate(@Param("username") String username, @Param("lastLogin") Date date); }
package com.github.lunatrius.stackie.handler; import com.github.lunatrius.stackie.reference.Reference; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.item.EntityXPOrb; import net.minecraft.item.ItemStack; import net.minecraft.server.MinecraftServer; import net.minecraft.world.WorldServer; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; public class Ticker { public static final int MAXIMUM_STACKSIZE = 2048; public static final int MAXIMUM_EXPERIENCE = 1024; private enum EntityType { ITEM, EXPERIENCEORB, OTHER } private MinecraftServer server = null; private int ticks = -1; private double weightL = -1; private double weightR = -1; @SubscribeEvent public void tick(TickEvent.ServerTickEvent event) { if (event.phase == TickEvent.Phase.START) { return; } if (--this.ticks < 0) { if (this.server != null && this.server.worldServers != null) { processWorlds(this.server.worldServers); } this.ticks = ConfigurationHandler.interval; } } public void setServer(MinecraftServer server) { this.server = server; } private void processWorlds(WorldServer[] worldServers) { for (WorldServer world : worldServers) { List<Entity> entityList = new ArrayList<Entity>(); for (int i = 0; i < world.loadedEntityList.size(); i++) { if (getType((Entity) world.loadedEntityList.get(i)) != EntityType.OTHER) { entityList.add((Entity) world.loadedEntityList.get(i)); } } if (entityList.size() >= 2 && entityList.size() <= ConfigurationHandler.stackLimit) { try { stackEntities(entityList); } catch (Exception e) { Reference.logger.error("Could not stack entities!", e); } } } } private void stackEntities(List<Entity> entityList) { final ListIterator<Entity> iteratorL = entityList.listIterator(); while (iteratorL.hasNext()) { final Entity entityL = iteratorL.next(); if (entityL.isDead) { continue; } final ListIterator<Entity> iteratorR = entityList.listIterator(iteratorL.nextIndex()); while (iteratorR.hasNext()) { final Entity entityR = iteratorR.next(); if (entityR.isDead) { continue; } stackEntities(entityL, entityR); } } } private boolean stackEntities(Entity entityL, Entity entityR) { final EntityType typeL = getType(entityL); final EntityType typeR = getType(entityR); if (typeL == typeR && isEqualPosition(entityL, entityR)) { boolean merged = false; switch (typeL) { case ITEM: merged = stackItems((EntityItem) entityL, (EntityItem) entityR); break; case EXPERIENCEORB: merged = stackExperience((EntityXPOrb) entityL, (EntityXPOrb) entityR); break; default: return false; } if (merged) { entityR.setDead(); final double totalWeight = this.weightL + this.weightR; this.weightL /= totalWeight; this.weightR /= totalWeight; final double x = entityL.posX * this.weightL + entityR.posX * this.weightR; final double y = entityL.posY * this.weightL + entityR.posY * this.weightR; final double z = entityL.posZ * this.weightL + entityR.posZ * this.weightR; entityL.setPosition(x, y, z); entityL.motionX = entityL.motionX * this.weightL + entityR.motionX * this.weightR; entityL.motionY = entityL.motionY * this.weightL + entityR.motionY * this.weightR; entityL.motionZ = entityL.motionZ * this.weightL + entityR.motionZ * this.weightR; } return merged; } return false; } private boolean stackItems(EntityItem entityItemL, EntityItem entityItemR) { final ItemStack itemStackL = entityItemL.getEntityItem(); final ItemStack itemStackR = entityItemR.getEntityItem(); if (!areItemStacksValid(itemStackL, itemStackR)) { return false; } this.weightL = itemStackL.stackSize; this.weightR = itemStackR.stackSize; final int itemsIn = Math.min(MAXIMUM_STACKSIZE - itemStackL.stackSize, itemStackR.stackSize); itemStackL.stackSize += itemsIn; itemStackR.stackSize -= itemsIn; entityItemL.setEntityItemStack(itemStackL); entityItemR.setEntityItemStack(itemStackR); entityItemL.age = Math.min(entityItemL.age, entityItemR.age); return itemStackR.stackSize <= 0; } private boolean areItemStacksValid(ItemStack itemStackL, ItemStack itemStackR) { if (itemStackL == null || itemStackR == null) { return false; } if (!itemStackL.isStackable()) { return false; } if (itemStackL.stackSize <= 0 || itemStackR.stackSize <= 0) { return false; } if (itemStackL.getItem() != itemStackR.getItem()) { return false; } if (itemStackL.getItemDamage() != itemStackR.getItemDamage()) { return false; } if (itemStackL.stackTagCompound == null && itemStackR.stackTagCompound == null) { return true; } return itemStackL.stackTagCompound != null && itemStackL.stackTagCompound.equals(itemStackR.stackTagCompound); } private boolean stackExperience(EntityXPOrb entityExpOrbL, EntityXPOrb entityExpOrbR) { this.weightL = entityExpOrbL.getXpValue(); this.weightR = entityExpOrbR.getXpValue(); if (this.weightL + this.weightR > MAXIMUM_EXPERIENCE) { return false; } entityExpOrbL.xpValue += entityExpOrbR.xpValue; entityExpOrbR.xpValue = 0; entityExpOrbL.xpOrbAge = Math.min(entityExpOrbL.xpOrbAge, entityExpOrbR.xpOrbAge); return true; } private EntityType getType(Entity entity) { if (ConfigurationHandler.stackItems && entity instanceof EntityItem) { return EntityType.ITEM; } else if (ConfigurationHandler.stackExperience && entity instanceof EntityXPOrb) { return EntityType.EXPERIENCEORB; } return EntityType.OTHER; } private boolean isEqualPosition(Entity a, Entity b) { return isEqual(a.posX, b.posX) && isEqual(a.posY, b.posY) && isEqual(a.posZ, b.posZ); } private boolean isEqual(double a, double b) { return isEqual(a, b, ConfigurationHandler.distance); } private boolean isEqual(double a, double b, double epsilon) { return Math.abs(a - b) < epsilon; } }
package com.grosner.dbflow.structure; import com.grosner.dbflow.ReflectionUtils; import com.grosner.dbflow.config.FlowLog; import com.grosner.dbflow.config.FlowManager; import com.grosner.dbflow.sql.builder.QueryBuilder; import com.grosner.dbflow.sql.builder.TableCreationQueryBuilder; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; public class TableStructure<ModelType extends Model> { /** * The Model class this table connects to */ private Class<ModelType> mModelType; /** * The name of the table. Can be different from the class name */ private String mTableName; /** * The mapping between the fields of a {@link com.grosner.dbflow.structure.Model} * and the name of the columns */ private Map<Field, String> mColumnNames; private Map<String, Field> mFieldFromNames; /** * The primary keys of this table. They must not be empty. */ private LinkedHashMap<String, Field> mPrimaryKeys; /** * The foreign keys of this table. */ private LinkedHashMap<String, Field> mForeignKeys; /** * Holds the Creation Query in this table for reference when we create it */ private TableCreationQueryBuilder mCreationQuery; /** * Manages the DB that this structure is in */ private FlowManager mManager; /** * Builds the structure of this table based on the {@link com.grosner.dbflow.structure.Model} * class passed in. * * @param modelType */ public TableStructure(FlowManager flowManager, Class<ModelType> modelType) { mManager = flowManager; mColumnNames = new HashMap<Field, String>(); mFieldFromNames = new HashMap<String, Field>(); mPrimaryKeys = new LinkedHashMap<String, Field>(); mForeignKeys = new LinkedHashMap<String, Field>(); mModelType = modelType; Table table = mModelType.getAnnotation(Table.class); if (table != null) { mTableName = table.name(); } else { mTableName = mModelType.getSimpleName(); } List<Field> fields = new ArrayList<Field>(); fields = ReflectionUtils.getAllColumns(fields, mModelType); // Generating creation query on the fly to be processed later mCreationQuery = new TableCreationQueryBuilder(); mCreationQuery.appendCreateTableIfNotExists(mTableName); ArrayList<QueryBuilder> mColumnDefinitions = new ArrayList<QueryBuilder>(); // Loop through fields and store their corresponding field names // Also determine if its primary key or foreign key for (Field field : fields) { TableCreationQueryBuilder tableCreationQuery = new TableCreationQueryBuilder(); Class type = field.getType(); String columnName; Column column = field.getAnnotation(Column.class); if (column.name() != null && !column.name().equals("")) { columnName = column.name(); } else { columnName = field.getName(); } mColumnNames.put(field, columnName); mFieldFromNames.put(columnName, field); if (column.value().value() == ColumnType.PRIMARY_KEY || column.value().value() == ColumnType.PRIMARY_KEY_AUTO_INCREMENT) { mPrimaryKeys.put(columnName, field); } else if (column.value().value() == ColumnType.FOREIGN_KEY) { mForeignKeys.put(columnName, field); } if (SQLiteType.containsClass(type)) { tableCreationQuery.append(columnName) .appendSpace() .appendType(type); } else if (ReflectionUtils.isSubclassOf(type, Enum.class)) { tableCreationQuery.append(columnName) .appendSpace() .appendSQLiteType(SQLiteType.TEXT); } mColumnDefinitions.add(tableCreationQuery.appendColumn(column)); } // Views do not have primary keys if(!ReflectionUtils.implementsModelView(modelType)) { if (mPrimaryKeys.isEmpty()) { throw new PrimaryKeyNotFoundException("Table: " + mTableName + " must define a primary key"); } QueryBuilder primaryKeyQueryBuilder = new QueryBuilder().append("PRIMARY KEY("); Collection<Field> primaryKeys = getPrimaryKeys(); int count = 0; int index = 0; for (Field field : primaryKeys) { Column primaryKey = field.getAnnotation(Column.class); if (primaryKey.value().value() != ColumnType.PRIMARY_KEY_AUTO_INCREMENT) { count++; primaryKeyQueryBuilder.append(mColumnNames.get(field)); if (index < mPrimaryKeys.size() - 1) { primaryKeyQueryBuilder.append(", "); } } index++; } if (count > 0) { primaryKeyQueryBuilder.append(")"); mColumnDefinitions.add(primaryKeyQueryBuilder); } QueryBuilder foreignKeyQueryBuilder; Collection<Field> foreignKeys = getForeignKeys(); for (Field foreignKeyField : foreignKeys) { foreignKeyQueryBuilder = new QueryBuilder().append("FOREIGN KEY("); Column foreignKey = foreignKeyField.getAnnotation(Column.class); foreignKeyQueryBuilder.append(mColumnNames.get(foreignKeyField)) .append(")").appendSpaceSeparated("REFERENCES") .append(mTableName) .append("(").append(foreignKey.foreignColumn()).append(")"); mColumnDefinitions.add(foreignKeyQueryBuilder); } } else if (!mPrimaryKeys.isEmpty() || !mForeignKeys.isEmpty()) { // We do not crash here as to interfere with instantiation. We will display log in error FlowLog.log(FlowLog.Level.E, "MODEL VIEWS CANNOT HAVE PRIMARY KEYS OR FOREIGN KEYS"); } mCreationQuery.appendColumnDefinitions(mColumnDefinitions).append(");"); } /** * Returns the query that we use to create this table. * * @return */ public QueryBuilder getCreationQuery() { return mCreationQuery; } /** * Returns this table name * * @return */ public String getTableName() { return mTableName; } /** * Returns the column name for the specified field. * * @param field * @return */ public String getColumnName(Field field) { return mColumnNames.get(field); } /** * Returns all of the field columns for this table * * @return */ public Set<Field> getColumns() { return mColumnNames.keySet(); } /** * Returns all of the foreign keys for this table * * @return */ public Collection<Field> getForeignKeys() { return mForeignKeys.values(); } /** * Returns all of the primary keys for this table * * @return */ public Collection<Field> getPrimaryKeys() { return mPrimaryKeys.values(); } /** * Returns the list of primary column key names * * @return */ public Set<String> getPrimaryKeyNames() { return mPrimaryKeys.keySet(); } /** * Returns the field for the column name * * @param name * @return */ public Field getField(String name) { return mFieldFromNames.get(name); } /** * Returns the model that this table corresponds to * * @return */ public Class<ModelType> getModelType() { return mModelType; } /** * Returns the database manager for this table * * @return */ public FlowManager getManager() { return mManager; } }
package com.hankcs.hanlp.dictionary.other; import com.hankcs.hanlp.HanLP; import com.hankcs.hanlp.corpus.io.IOUtil; import com.hankcs.hanlp.utility.Predefine; import java.io.FileInputStream; import java.io.ObjectInputStream; import static com.hankcs.hanlp.utility.Predefine.logger; /** * * @author hankcs */ public class CharTable { public static char[] CONVERT; static { long start = System.currentTimeMillis(); if (!load(HanLP.Config.CharTablePath)) { throw new IllegalArgumentException(""); } logger.info("" + (System.currentTimeMillis() - start) + " ms"); } private static boolean load(String path) { String binPath = path + Predefine.BIN_EXT; if (loadBin(binPath)) return true; CONVERT = new char[Character.MAX_VALUE + 1]; for (int i = 0; i < CONVERT.length; i++) { CONVERT[i] = (char) i; } IOUtil.LineIterator iterator = new IOUtil.LineIterator(path); while (iterator.hasNext()) { String line = iterator.next(); if (line == null) return false; if (line.length() != 3) continue; CONVERT[line.charAt(0)] = CONVERT[line.charAt(2)]; } loadSpace(); logger.info("" + binPath); IOUtil.saveObjectTo(CONVERT, binPath); return true; } private static void loadSpace() { for (int i = Character.MIN_CODE_POINT; i <= Character.MAX_CODE_POINT; i++) { if (Character.isWhitespace(i) || Character.isSpaceChar(i)) { CONVERT[i] = ' '; } } } private static boolean loadBin(String path) { try { ObjectInputStream in = new ObjectInputStream(IOUtil.newInputStream(path)); CONVERT = (char[]) in.readObject(); in.close(); } catch (Exception e) { logger.warning("" + e); return false; } return true; } /** * * @param c * @return */ public static char convert(char c) { return CONVERT[c]; } public static char[] convert(char[] charArray) { char[] result = new char[charArray.length]; for (int i = 0; i < charArray.length; i++) { result[i] = CONVERT[charArray[i]]; } return result; } public static String convert(String sentence) { assert sentence != null; char[] result = new char[sentence.length()]; convert(sentence, result); return new String(result); } public static void convert(String charArray, char[] result) { for (int i = 0; i < charArray.length(); i++) { result[i] = CONVERT[charArray.charAt(i)]; } } /** * * @param charArray */ public static void normalization(char[] charArray) { assert charArray != null; for (int i = 0; i < charArray.length; i++) { charArray[i] = CONVERT[charArray[i]]; } } }
package com.lothrazar.cyclicmagic.module; import java.util.ArrayList; import java.util.Set; import com.google.common.collect.Sets; import com.lothrazar.cyclicmagic.ModCyclic; import com.lothrazar.cyclicmagic.config.IHasConfig; import com.lothrazar.cyclicmagic.core.item.BaseItemProjectile; import com.lothrazar.cyclicmagic.core.util.Const; import com.lothrazar.cyclicmagic.guide.GuideCategory; import com.lothrazar.cyclicmagic.guide.GuideItem; import com.lothrazar.cyclicmagic.guide.GuideRegistry; import com.lothrazar.cyclicmagic.item.ItemCaveFinder; import com.lothrazar.cyclicmagic.item.ItemEnderBag; import com.lothrazar.cyclicmagic.item.ItemEnderWing; import com.lothrazar.cyclicmagic.item.ItemFangs; import com.lothrazar.cyclicmagic.item.ItemFireExtinguish; import com.lothrazar.cyclicmagic.item.ItemIceWand; import com.lothrazar.cyclicmagic.item.ItemLeverRemote; import com.lothrazar.cyclicmagic.item.ItemMattock; import com.lothrazar.cyclicmagic.item.ItemPaperCarbon; import com.lothrazar.cyclicmagic.item.ItemPistonWand; import com.lothrazar.cyclicmagic.item.ItemPlayerLauncher; import com.lothrazar.cyclicmagic.item.ItemProspector; import com.lothrazar.cyclicmagic.item.ItemRotateBlock; import com.lothrazar.cyclicmagic.item.ItemSoulstone; import com.lothrazar.cyclicmagic.item.ItemSpawnInspect; import com.lothrazar.cyclicmagic.item.ItemStirrups; import com.lothrazar.cyclicmagic.item.ItemStirrupsReverse; import com.lothrazar.cyclicmagic.item.ItemWandHypno; import com.lothrazar.cyclicmagic.item.ItemWarpSurface; import com.lothrazar.cyclicmagic.item.ItemWaterRemoval; import com.lothrazar.cyclicmagic.item.ItemWaterSpreader; import com.lothrazar.cyclicmagic.item.buildswap.ItemBuildSwapper; import com.lothrazar.cyclicmagic.item.buildswap.ItemBuildSwapper.WandType; import com.lothrazar.cyclicmagic.item.cannon.EntityGolemLaser; import com.lothrazar.cyclicmagic.item.cannon.ItemProjectileCannon; import com.lothrazar.cyclicmagic.item.crashtestdummy.EntityRobot; import com.lothrazar.cyclicmagic.item.crashtestdummy.ItemCrashSpawner; import com.lothrazar.cyclicmagic.item.cyclicwand.ItemCyclicWand; import com.lothrazar.cyclicmagic.item.dynamite.EntityDynamite; import com.lothrazar.cyclicmagic.item.dynamite.EntityDynamiteBlockSafe; import com.lothrazar.cyclicmagic.item.dynamite.EntityDynamiteMining; import com.lothrazar.cyclicmagic.item.dynamite.ItemProjectileTNT; import com.lothrazar.cyclicmagic.item.dynamite.ItemProjectileTNT.ExplosionType; import com.lothrazar.cyclicmagic.item.enderbook.ItemEnderBook; import com.lothrazar.cyclicmagic.item.endereye.EntityEnderEyeUnbreakable; import com.lothrazar.cyclicmagic.item.endereye.ItemEnderEyeReuse; import com.lothrazar.cyclicmagic.item.enderpearl.ItemEnderPearlReuse; import com.lothrazar.cyclicmagic.item.equipbauble.ItemAutoTorch; import com.lothrazar.cyclicmagic.item.equipbauble.ItemCharmAir; import com.lothrazar.cyclicmagic.item.equipbauble.ItemCharmAntidote; import com.lothrazar.cyclicmagic.item.equipbauble.ItemCharmBoat; import com.lothrazar.cyclicmagic.item.equipbauble.ItemCharmFire; import com.lothrazar.cyclicmagic.item.equipbauble.ItemCharmSlowfall; import com.lothrazar.cyclicmagic.item.equipbauble.ItemCharmSpeed; import com.lothrazar.cyclicmagic.item.equipbauble.ItemCharmVoid; import com.lothrazar.cyclicmagic.item.equipbauble.ItemCharmWater; import com.lothrazar.cyclicmagic.item.equipbauble.ItemGloveClimb; import com.lothrazar.cyclicmagic.item.equipment.ItemGlowingHelmet; import com.lothrazar.cyclicmagic.item.equipment.crystal.ItemPowerArmor; import com.lothrazar.cyclicmagic.item.equipment.crystal.ItemPowerSword; import com.lothrazar.cyclicmagic.item.equipment.emerald.ItemEmeraldArmor; import com.lothrazar.cyclicmagic.item.equipment.emerald.ItemEmeraldAxe; import com.lothrazar.cyclicmagic.item.equipment.emerald.ItemEmeraldHoe; import com.lothrazar.cyclicmagic.item.equipment.emerald.ItemEmeraldPickaxe; import com.lothrazar.cyclicmagic.item.equipment.emerald.ItemEmeraldSpade; import com.lothrazar.cyclicmagic.item.equipment.emerald.ItemEmeraldSword; import com.lothrazar.cyclicmagic.item.equipment.nether.ItemNetherbrickAxe; import com.lothrazar.cyclicmagic.item.equipment.nether.ItemNetherbrickHoe; import com.lothrazar.cyclicmagic.item.equipment.nether.ItemNetherbrickPickaxe; import com.lothrazar.cyclicmagic.item.equipment.nether.ItemNetherbrickSpade; import com.lothrazar.cyclicmagic.item.equipment.sandstone.ItemSandstoneAxe; import com.lothrazar.cyclicmagic.item.equipment.sandstone.ItemSandstoneHoe; import com.lothrazar.cyclicmagic.item.equipment.sandstone.ItemSandstonePickaxe; import com.lothrazar.cyclicmagic.item.equipment.sandstone.ItemSandstoneSpade; import com.lothrazar.cyclicmagic.item.findspawner.EntityDungeonEye; import com.lothrazar.cyclicmagic.item.findspawner.ItemProjectileDungeon; import com.lothrazar.cyclicmagic.item.homingmissile.EntityHomingProjectile; import com.lothrazar.cyclicmagic.item.homingmissile.ItemMagicMissile; import com.lothrazar.cyclicmagic.item.lightningmagic.EntityLightningballBolt; import com.lothrazar.cyclicmagic.item.lightningmagic.ItemProjectileLightning; import com.lothrazar.cyclicmagic.item.merchant.ItemMerchantAlmanac; import com.lothrazar.cyclicmagic.item.minecart.EntityGoldFurnaceMinecart; import com.lothrazar.cyclicmagic.item.minecart.EntityGoldMinecart; import com.lothrazar.cyclicmagic.item.minecart.EntityGoldMinecartChest; import com.lothrazar.cyclicmagic.item.minecart.EntityGoldMinecartDispenser; import com.lothrazar.cyclicmagic.item.minecart.EntityMinecartDropper; import com.lothrazar.cyclicmagic.item.minecart.EntityMinecartTurret; import com.lothrazar.cyclicmagic.item.minecart.EntityStoneMinecart; import com.lothrazar.cyclicmagic.item.minecart.ItemDropperMinecart; import com.lothrazar.cyclicmagic.item.minecart.ItemGoldFurnaceMinecart; import com.lothrazar.cyclicmagic.item.minecart.ItemGoldMinecart; import com.lothrazar.cyclicmagic.item.minecart.ItemStoneMinecart; import com.lothrazar.cyclicmagic.item.minecart.ItemTurretMinecart; import com.lothrazar.cyclicmagic.item.mobcapture.EntityMagicNetEmpty; import com.lothrazar.cyclicmagic.item.mobcapture.EntityMagicNetFull; import com.lothrazar.cyclicmagic.item.mobcapture.ItemProjectileMagicNet; import com.lothrazar.cyclicmagic.item.mobs.ItemHorseTame; import com.lothrazar.cyclicmagic.item.mobs.ItemHorseUpgrade; import com.lothrazar.cyclicmagic.item.mobs.ItemHorseUpgrade.HorseUpgradeType; import com.lothrazar.cyclicmagic.item.mobs.ItemVillagerMagic; import com.lothrazar.cyclicmagic.item.random.ItemRandomizer; import com.lothrazar.cyclicmagic.item.scythe.ItemScythe; import com.lothrazar.cyclicmagic.item.shears.EntityShearingBolt; import com.lothrazar.cyclicmagic.item.shears.ItemShearsRanged; import com.lothrazar.cyclicmagic.item.signcolor.ItemSignEditor; import com.lothrazar.cyclicmagic.item.sleep.ItemSleepingMat; import com.lothrazar.cyclicmagic.item.snowmagic.EntitySnowballBolt; import com.lothrazar.cyclicmagic.item.snowmagic.ItemProjectileSnow; import com.lothrazar.cyclicmagic.item.storagesack.ItemStorageBag; import com.lothrazar.cyclicmagic.item.tiletransporter.ItemChestSack; import com.lothrazar.cyclicmagic.item.tiletransporter.ItemChestSackEmpty; import com.lothrazar.cyclicmagic.item.torchmagic.EntityTorchBolt; import com.lothrazar.cyclicmagic.item.torchmagic.ItemProjectileTorch; import com.lothrazar.cyclicmagic.item.torchmagic.ItemTorchThrower; import com.lothrazar.cyclicmagic.playerupgrade.ItemAppleStep; import com.lothrazar.cyclicmagic.playerupgrade.ItemCraftingUnlock; import com.lothrazar.cyclicmagic.playerupgrade.ItemFlight; import com.lothrazar.cyclicmagic.playerupgrade.ItemHeartContainer; import com.lothrazar.cyclicmagic.playerupgrade.ItemInventoryUnlock; import com.lothrazar.cyclicmagic.playerupgrade.ItemNoclipGhost; import com.lothrazar.cyclicmagic.registry.EntityProjectileRegistry; import com.lothrazar.cyclicmagic.registry.ItemRegistry; import com.lothrazar.cyclicmagic.registry.LootTableRegistry; import com.lothrazar.cyclicmagic.registry.LootTableRegistry.ChestType; import com.lothrazar.cyclicmagic.registry.MaterialRegistry; import com.lothrazar.cyclicmagic.registry.RecipeRegistry; import com.lothrazar.cyclicmagic.registry.SpellRegistry; import com.lothrazar.cyclicmagic.tweak.dispenser.BehaviorProjectileThrowable; import net.minecraft.block.Block; import net.minecraft.block.BlockDispenser; import net.minecraft.block.material.Material; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.EnumDyeColor; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.common.registry.EntityRegistry; public class ItemModule extends BaseModule implements IHasConfig { public static int intColor(int r, int g, int b) { return (r * 65536 + g * 256 + b); } private boolean goldMinecart; private boolean stoneMinecart; private boolean chestMinecart; private boolean dropperMinecart; private boolean dispenserMinecart; private boolean turretMinecart; private boolean enableEmeraldApple; private boolean enableHeartContainer; private boolean enableInventoryCrafting; private boolean enableInventoryUpgrade; private boolean enableCorruptedChorus; private boolean enableHorseFoodUpgrades; private boolean enableGlowingChorus; private boolean enableLapisApple; private boolean foodStep; private boolean mountInverse; private boolean enableFireCharm; private boolean enableSea; private boolean enableVoid; private boolean enableWater; private boolean antidoteCharm; private boolean slowfallCharm; private boolean autoTorch; private boolean enableSpeed; private boolean enableAir; private boolean enableEnderDungeonFinder; private boolean enderSnow; private boolean enderWool; private boolean enderTorch; private boolean enderWater; private boolean enderLightning; private boolean enderBombsEnabled; ArrayList<BaseItemProjectile> projectiles = new ArrayList<BaseItemProjectile>(); private boolean dynamiteSafe; private boolean dynamiteMining; private boolean magicNet; private boolean enableChaos; private boolean enableMissile; private boolean enableSleepingMat; private boolean enableToolPush; private boolean enableHarvestLeaves; private boolean enableToolHarvest; private boolean enableHarvestWeeds; private boolean enablePearlReuse; private boolean enableSpawnInspect; private boolean enableCyclicWand; private boolean enableProspector; private boolean enableCavefinder; private boolean enableWarpHomeTool; private boolean enableWarpSpawnTool; private boolean enableSwappers; private boolean enableRando; private boolean enableMattock; private boolean enablePearlReuseMounted; private boolean enableCarbonPaper; private boolean storageBagEnabled; private boolean enableEnderBook; private boolean enableChestSack; private boolean enableStirrups; private boolean enableTorchLauncher; private boolean enderSack; private boolean enablewaterSpread; private boolean enableFreezer; private boolean enableFireKiller; private boolean enableBlockRot; private boolean enableCGlove; private boolean enableElevate; private boolean enableLever; private boolean enableTrader; private boolean enableSoulstone; private boolean enablePlayerLauncher; private boolean evokerFang; private boolean enderEyeReuse; public static ItemStorageBag storage_bag = null;//ref by ContainerStorage private boolean enableEmeraldGear; private boolean enableSandstoneTools; private boolean enablePurpleGear; private boolean enablePurpleSwords; private boolean glowingHelmet; private boolean signEditor; private boolean robotSpawner; private boolean lasers; private boolean enableNetherbrickTools; private boolean enableHeartToxic; @Override public void onPreInit() { if (robotSpawner) { EntityRegistry.registerModEntity(new ResourceLocation(Const.MODID, EntityRobot.NAME), EntityRobot.class, EntityRobot.NAME, 1030, ModCyclic.instance, 64, 1, true); EntityRegistry.registerEgg(new ResourceLocation(Const.MODID, EntityRobot.NAME), intColor(159, 255, 222), intColor(222, 111, 51)); ItemCrashSpawner spawner = new ItemCrashSpawner(); ItemRegistry.register(spawner, "robot_spawner", GuideCategory.TRANSPORT); ModCyclic.instance.events.register(spawner); } if (lasers) { ItemRegistry.register(new ItemProjectileCannon(), "laser_cannon", GuideCategory.ITEMTHROW); EntityRegistry.registerModEntity(new ResourceLocation(Const.MODID, EntityGolemLaser.NAME), EntityGolemLaser.class, EntityGolemLaser.NAME, 1031, ModCyclic.instance, 64, 1, true); } if (goldMinecart) { ItemGoldMinecart gold_minecart = new ItemGoldMinecart(); ItemRegistry.register(gold_minecart, "gold_minecart", GuideCategory.TRANSPORT); EntityGoldMinecart.dropItem = gold_minecart; EntityProjectileRegistry.registerModEntity(EntityGoldMinecart.class, "goldminecart", 1100); ItemGoldFurnaceMinecart gold_furnace_minecart = new ItemGoldFurnaceMinecart(); ItemRegistry.register(gold_furnace_minecart, "gold_furnace_minecart", GuideCategory.TRANSPORT); EntityGoldFurnaceMinecart.dropItem = gold_furnace_minecart; EntityProjectileRegistry.registerModEntity(EntityGoldFurnaceMinecart.class, "goldfurnaceminecart", 1101); } if (stoneMinecart) { ItemStoneMinecart stone_minecart = new ItemStoneMinecart(); ItemRegistry.register(stone_minecart, "stone_minecart", GuideCategory.TRANSPORT); EntityStoneMinecart.dropItem = stone_minecart; EntityProjectileRegistry.registerModEntity(EntityStoneMinecart.class, "stoneminecart", 1102); } if (chestMinecart) { EntityProjectileRegistry.registerModEntity(EntityGoldMinecartChest.class, "goldchestminecart", 1103); } if (dropperMinecart) { ItemDropperMinecart dropper_minecart = new ItemDropperMinecart(); ItemRegistry.register(dropper_minecart, "dropper_minecart", GuideCategory.TRANSPORT); EntityMinecartDropper.dropItem = dropper_minecart; EntityProjectileRegistry.registerModEntity(EntityMinecartDropper.class, "golddropperminecart", 1104); } if (dispenserMinecart) { //BROKEN: //it spawns entity in the world. so like an arrow, it flies to the arget but then magically teleports back o teh cart position //stop for now EntityProjectileRegistry.registerModEntity(EntityGoldMinecartDispenser.class, "golddispenserminecart", 1105); } if (turretMinecart) { ItemTurretMinecart turret_minecart = new ItemTurretMinecart(); ItemRegistry.register(turret_minecart, "turret_minecart", GuideCategory.TRANSPORT); EntityMinecartTurret.dropItem = turret_minecart; EntityProjectileRegistry.registerModEntity(EntityMinecartTurret.class, "turretminecart", 1106); } //if i have a mob on a LEAD< i can put it in a minecart with thehit //maybe 2 passengers..?? idk //connect together?? //DISPENSERR minecart //??FLUID CART? //TURRET CART:? shoots arrows //ONE THAT CAN HOLD ANY ITEM if (enableEmeraldGear) { ItemEmeraldArmor emerald_head = new ItemEmeraldArmor(EntityEquipmentSlot.HEAD); ItemRegistry.register(emerald_head, "emerald_helmet", null); Item emerald_chest = new ItemEmeraldArmor(EntityEquipmentSlot.CHEST); ItemRegistry.register(emerald_chest, "emerald_chestplate", null); Item emerald_legs = new ItemEmeraldArmor(EntityEquipmentSlot.LEGS); ItemRegistry.register(emerald_legs, "emerald_leggings", null); Item emerald_boots = new ItemEmeraldArmor(EntityEquipmentSlot.FEET); ItemRegistry.register(emerald_boots, "emerald_boots", null); Item emerald_sword = new ItemEmeraldSword(); ItemRegistry.register(emerald_sword, "emerald_sword", null); Item emerald_pickaxe = new ItemEmeraldPickaxe(); ItemRegistry.register(emerald_pickaxe, "emerald_pickaxe", null); Item emerald_axe = new ItemEmeraldAxe(); ItemRegistry.register(emerald_axe, "emerald_axe", null); Item emerald_shovel = new ItemEmeraldSpade(); ItemRegistry.register(emerald_shovel, "emerald_spade", null); Item emerald_hoe = new ItemEmeraldHoe(); ItemRegistry.register(emerald_hoe, "emerald_hoe", null); LootTableRegistry.registerLoot(emerald_pickaxe); LootTableRegistry.registerLoot(emerald_sword); LootTableRegistry.registerLoot(emerald_chest); GuideRegistry.register(GuideCategory.GEAR, emerald_head, "item.emeraldgear.title", "item.emeraldgear.guide"); } if (enablePurpleGear) { Item purple_boots = new ItemPowerArmor(EntityEquipmentSlot.FEET); ItemRegistry.register(purple_boots, "purple_boots", GuideCategory.GEAR); Item purple_leggings = new ItemPowerArmor(EntityEquipmentSlot.LEGS); ItemRegistry.register(purple_leggings, "purple_leggings", GuideCategory.GEAR); Item purple_chestplate = new ItemPowerArmor(EntityEquipmentSlot.CHEST); ItemRegistry.register(purple_chestplate, "purple_chestplate", GuideCategory.GEAR); Item purple_helmet = new ItemPowerArmor(EntityEquipmentSlot.HEAD); ItemRegistry.register(purple_helmet, "purple_helmet", GuideCategory.GEAR); } if (glowingHelmet) { Item glowing_helmet = new ItemGlowingHelmet(EntityEquipmentSlot.HEAD); ItemRegistry.register(glowing_helmet, "glowing_helmet", GuideCategory.GEAR); ModCyclic.instance.events.register(glowing_helmet); } if (enablePurpleSwords) { ItemPowerSword sword_weakness = new ItemPowerSword(ItemPowerSword.SwordType.WEAK); ItemRegistry.register(sword_weakness, "sword_weakness", GuideCategory.GEAR); ItemPowerSword sword_slowness = new ItemPowerSword(ItemPowerSword.SwordType.SLOW); ItemRegistry.register(sword_slowness, "sword_slowness", GuideCategory.GEAR); ItemPowerSword sword_ender = new ItemPowerSword(ItemPowerSword.SwordType.ENDER); ItemRegistry.register(sword_ender, "sword_ender", GuideCategory.GEAR); } if (enableNetherbrickTools) { Item netherbrick_pickaxe = new ItemNetherbrickPickaxe(); ItemRegistry.register(netherbrick_pickaxe, "netherbrick_pickaxe", null); Item netherbrick_axe = new ItemNetherbrickAxe(); ItemRegistry.register(netherbrick_axe, "netherbrick_axe", null); Item netherbrick_spade = new ItemNetherbrickSpade(); ItemRegistry.register(netherbrick_spade, "netherbrick_spade", null); Item netherbrick_hoe = new ItemNetherbrickHoe(); ItemRegistry.register(netherbrick_hoe, "netherbrick_hoe", null); //NETHER CHESTYPE // LootTableRegistry.registerLoot(sandstone_pickaxe, ChestType.); // LootTableRegistry.registerLoot(sandstone_axe, ChestType.BONUS); // LootTableRegistry.registerLoot(sandstone_spade, ChestType.BONUS); GuideRegistry.register(GuideCategory.GEAR, netherbrick_axe, "item.netherbrick_axe.name", "item.netherbrick_axe.guide"); } if (enableSandstoneTools) { Item sandstone_pickaxe = new ItemSandstonePickaxe(); ItemRegistry.register(sandstone_pickaxe, "sandstone_pickaxe", null); Item sandstone_axe = new ItemSandstoneAxe(); ItemRegistry.register(sandstone_axe, "sandstone_axe", null); Item sandstone_spade = new ItemSandstoneSpade(); ItemRegistry.register(sandstone_spade, "sandstone_spade", null); Item sandstone_hoe = new ItemSandstoneHoe(); ItemRegistry.register(sandstone_hoe, "sandstone_hoe", null); LootTableRegistry.registerLoot(sandstone_pickaxe, ChestType.BONUS); LootTableRegistry.registerLoot(sandstone_axe, ChestType.BONUS); LootTableRegistry.registerLoot(sandstone_spade, ChestType.BONUS); GuideRegistry.register(GuideCategory.GEAR, sandstone_axe, "item.sandstonegear.title", "item.sandstonegear.guide"); } if (enableCGlove) { ItemGloveClimb glove_climb = new ItemGloveClimb(); ItemRegistry.register(glove_climb, "glove_climb", GuideCategory.ITEMBAUBLES); LootTableRegistry.registerLoot(glove_climb); } if (evokerFang) { ItemFangs evoker_fangs = new ItemFangs(); ItemRegistry.register(evoker_fangs, "evoker_fang", GuideCategory.ITEM); LootTableRegistry.registerLoot(evoker_fangs); ModCyclic.instance.events.register(evoker_fangs); } if (enablePlayerLauncher) { ItemPlayerLauncher tool_launcher = new ItemPlayerLauncher(); ItemRegistry.register(tool_launcher, "tool_launcher", GuideCategory.TRANSPORT); ModCyclic.instance.events.register(tool_launcher); } if (enableSoulstone) { ItemSoulstone soulstone = new ItemSoulstone(); ItemRegistry.register(soulstone, "soulstone"); ModCyclic.instance.events.register(soulstone); } if (enableTrader) { ItemMerchantAlmanac tool_trade = new ItemMerchantAlmanac(); ItemRegistry.register(tool_trade, "tool_trade"); ModCyclic.instance.events.register(tool_trade); } if (enableLever) { ItemLeverRemote password_remote = new ItemLeverRemote(); ItemRegistry.register(password_remote, "password_remote"); } if (enableElevate) { ItemWarpSurface tool_elevate = new ItemWarpSurface(); ItemRegistry.register(tool_elevate, "tool_elevate", GuideCategory.TRANSPORT); LootTableRegistry.registerLoot(tool_elevate); } if (enableBlockRot) { ItemRotateBlock tool_rotate = new ItemRotateBlock(); ItemRegistry.register(tool_rotate, "tool_rotate"); } if (enablewaterSpread) { ItemWaterSpreader water_spreader = new ItemWaterSpreader(); ItemRegistry.register(water_spreader, "water_spreader"); } if (enableFreezer) { ItemIceWand water_freezer = new ItemIceWand(); ItemRegistry.register(water_freezer, "water_freezer"); } if (enableFireKiller) { ItemFireExtinguish fire_killer = new ItemFireExtinguish(); ItemRegistry.register(fire_killer, "fire_killer"); } if (enderEyeReuse) { ItemEnderEyeReuse ender_eye_orb = new ItemEnderEyeReuse(); ItemRegistry.register(ender_eye_orb, "ender_eye_orb"); EntityProjectileRegistry.registerModEntity(EntityEnderEyeUnbreakable.class, "ender_eye_orb", 1029); } if (enderSack) { ItemEnderBag sack_ender = new ItemEnderBag(); ItemRegistry.register(sack_ender, "sack_ender"); LootTableRegistry.registerLoot(sack_ender); } if (enableTorchLauncher) { ItemTorchThrower tool_torch_launcher = new ItemTorchThrower(); ItemRegistry.register(tool_torch_launcher, "tool_torch_launcher"); } if (enableStirrups) { ItemStirrups tool_mount = new ItemStirrups(); ItemRegistry.register(tool_mount, "tool_mount"); } if (enableChestSack) { ItemChestSackEmpty chest_sack_empty = new ItemChestSackEmpty(); ItemChestSack chest_sack = new ItemChestSack(); chest_sack.setEmptySack(chest_sack_empty); chest_sack_empty.setFullSack(chest_sack); // ItemRegistry.registerWithJeiDescription(chest_sack); ItemRegistry.register(chest_sack, "chest_sack", null); ItemRegistry.register(chest_sack_empty, "chest_sack_empty"); // ItemRegistry.registerWithJeiDescription(chest_sack_empty); } if (enableEnderBook) { ItemEnderBook book_ender = new ItemEnderBook(); ItemRegistry.register(book_ender, "book_ender", GuideCategory.TRANSPORT); LootTableRegistry.registerLoot(book_ender); LootTableRegistry.registerLoot(book_ender); // ItemRegistry.registerWithJeiDescription(book_ender); } if (storageBagEnabled) { storage_bag = new ItemStorageBag(); ItemRegistry.register(storage_bag, "storage_bag"); ModCyclic.instance.events.register(storage_bag); LootTableRegistry.registerLoot(storage_bag, ChestType.BONUS); } if (enableCarbonPaper) { ItemPaperCarbon carbon_paper = new ItemPaperCarbon(); ItemRegistry.register(carbon_paper, "carbon_paper"); //ItemRegistry.registerWithJeiDescription(carbon_paper); } if (enableProspector) { ItemProspector tool_prospector = new ItemProspector(); ItemRegistry.register(tool_prospector, "tool_prospector"); LootTableRegistry.registerLoot(tool_prospector); //ItemRegistry.registerWithJeiDescription(tool_prospector); } if (enableCavefinder) { ItemCaveFinder tool_spelunker = new ItemCaveFinder(); ItemRegistry.register(tool_spelunker, "tool_spelunker"); // ItemRegistry.registerWithJeiDescription(tool_spelunker); } if (enableSpawnInspect) { ItemSpawnInspect tool_spawn_inspect = new ItemSpawnInspect(); ItemRegistry.register(tool_spawn_inspect, "tool_spawn_inspect"); // ItemRegistry.registerWithJeiDescription(tool_spawn_inspect); } if (enablePearlReuse) { ItemEnderPearlReuse ender_pearl_reuse = new ItemEnderPearlReuse(ItemEnderPearlReuse.OrbType.NORMAL); ItemRegistry.register(ender_pearl_reuse, "ender_pearl_reuse"); LootTableRegistry.registerLoot(ender_pearl_reuse); // ItemRegistry.registerWithJeiDescription(ender_pearl_reuse); } if (enablePearlReuseMounted) { ItemEnderPearlReuse ender_pearl_mounted = new ItemEnderPearlReuse(ItemEnderPearlReuse.OrbType.MOUNTED); ItemRegistry.register(ender_pearl_mounted, "ender_pearl_mounted"); LootTableRegistry.registerLoot(ender_pearl_mounted); // AchievementRegistry.registerItemAchievement(ender_pearl_mounted); // ItemRegistry.registerWithJeiDescription(ender_pearl_mounted); } if (enableHarvestWeeds) { ItemScythe tool_harvest_weeds = new ItemScythe(ItemScythe.ScytheType.WEEDS); ItemRegistry.register(tool_harvest_weeds, "tool_harvest_weeds"); LootTableRegistry.registerLoot(tool_harvest_weeds, ChestType.BONUS); // ItemRegistry.registerWithJeiDescription(tool_harvest_weeds); } if (enableToolHarvest) { ItemScythe tool_harvest_crops = new ItemScythe(ItemScythe.ScytheType.CROPS); ItemRegistry.register(tool_harvest_crops, "tool_harvest_crops"); LootTableRegistry.registerLoot(tool_harvest_crops); // AchievementRegistry.registerItemAchievement(tool_harvest_crops); // ItemRegistry.registerWithJeiDescription(tool_harvest_crops); } if (enableHarvestLeaves) { ItemScythe tool_harvest_leaves = new ItemScythe(ItemScythe.ScytheType.LEAVES); ItemRegistry.register(tool_harvest_leaves, "tool_harvest_leaves"); LootTableRegistry.registerLoot(tool_harvest_leaves, ChestType.BONUS); // ItemRegistry.registerWithJeiDescription(tool_harvest_leaves); } if (enableToolPush) { ItemPistonWand tool_push = new ItemPistonWand(); ItemRegistry.register(tool_push, "tool_push"); ModCyclic.instance.events.register(tool_push); LootTableRegistry.registerLoot(tool_push); // AchievementRegistry.registerItemAchievement(tool_push); // ItemRegistry.registerWithJeiDescription(tool_push); } if (enableSleepingMat) { ItemSleepingMat sleeping_mat = new ItemSleepingMat(); ItemRegistry.register(sleeping_mat, "sleeping_mat"); ModCyclic.instance.events.register(sleeping_mat); LootTableRegistry.registerLoot(sleeping_mat, ChestType.BONUS); } if (enableCyclicWand) { ItemCyclicWand cyclic_wand_build = new ItemCyclicWand(); ItemRegistry.register(cyclic_wand_build, "cyclic_wand_build"); SpellRegistry.register(cyclic_wand_build); ModCyclic.instance.events.register(this); LootTableRegistry.registerLoot(cyclic_wand_build, ChestType.ENDCITY, 15); LootTableRegistry.registerLoot(cyclic_wand_build, ChestType.GENERIC, 1); // AchievementRegistry.registerItemAchievement(cyclic_wand_build); ModCyclic.TAB.setTabItemIfNull(cyclic_wand_build); // ItemRegistry.registerWithJeiDescription(cyclic_wand_build); } if (enableWarpHomeTool) { ItemEnderWing tool_warp_home = new ItemEnderWing(ItemEnderWing.WarpType.BED); ItemRegistry.register(tool_warp_home, "tool_warp_home", GuideCategory.TRANSPORT); LootTableRegistry.registerLoot(tool_warp_home); // AchievementRegistry.registerItemAchievement(tool_warp_home); // ItemRegistry.registerWithJeiDescription(tool_warp_home); } if (enableWarpSpawnTool) { ItemEnderWing tool_warp_spawn = new ItemEnderWing(ItemEnderWing.WarpType.SPAWN); ItemRegistry.register(tool_warp_spawn, "tool_warp_spawn", GuideCategory.TRANSPORT); LootTableRegistry.registerLoot(tool_warp_spawn); // ItemRegistry.registerWithJeiDescription(tool_warp_spawn); } if (enableSwappers) { ItemBuildSwapper tool_swap = new ItemBuildSwapper(WandType.NORMAL); ItemRegistry.register(tool_swap, "tool_swap"); ModCyclic.instance.events.register(tool_swap); ItemBuildSwapper tool_swap_match = new ItemBuildSwapper(WandType.MATCH); ItemRegistry.register(tool_swap_match, "tool_swap_match"); ModCyclic.instance.events.register(tool_swap_match); } if (enableRando) { ItemRandomizer tool_randomize = new ItemRandomizer(); ItemRegistry.register(tool_randomize, "tool_randomize"); ModCyclic.instance.events.register(tool_randomize); // ItemRegistry.registerWithJeiDescription(tool_randomize); } if (enableMattock) { final Set<Block> blocks = Sets.newHashSet(Blocks.ACTIVATOR_RAIL, Blocks.COAL_ORE, Blocks.COBBLESTONE, Blocks.DETECTOR_RAIL, Blocks.DIAMOND_BLOCK, Blocks.DIAMOND_ORE, Blocks.DOUBLE_STONE_SLAB, Blocks.GOLDEN_RAIL, Blocks.GOLD_BLOCK, Blocks.GOLD_ORE, Blocks.ICE, Blocks.IRON_BLOCK, Blocks.IRON_ORE, Blocks.LAPIS_BLOCK, Blocks.LAPIS_ORE, Blocks.LIT_REDSTONE_ORE, Blocks.MOSSY_COBBLESTONE, Blocks.NETHERRACK, Blocks.PACKED_ICE, Blocks.RAIL, Blocks.REDSTONE_ORE, Blocks.SANDSTONE, Blocks.RED_SANDSTONE, Blocks.STONE, Blocks.STONE_SLAB, Blocks.STONE_BUTTON, Blocks.STONE_PRESSURE_PLATE, Blocks.CLAY, Blocks.DIRT, Blocks.FARMLAND, Blocks.GRASS, Blocks.GRAVEL, Blocks.MYCELIUM, Blocks.SAND, Blocks.SNOW, Blocks.SNOW_LAYER, Blocks.SOUL_SAND, Blocks.GRASS_PATH); final Set<Material> materials = Sets.newHashSet(Material.ANVIL, Material.GLASS, Material.ICE, Material.IRON, Material.PACKED_ICE, Material.PISTON, Material.ROCK, Material.GRASS, Material.GROUND, Material.SAND, Material.SNOW, Material.CRAFTED_SNOW, Material.CLAY); ItemMattock mattock = new ItemMattock(2, -1, MaterialRegistry.emeraldToolMaterial, blocks, materials); ItemRegistry.register(mattock, "mattock"); } if (enableChaos) { ItemWandHypno wand_hypno = new ItemWandHypno(); ItemRegistry.register(wand_hypno, "wand_hypno", GuideCategory.ITEMTHROW); } if (enableMissile) { ItemMagicMissile magic_missile = new ItemMagicMissile(); ItemRegistry.register(magic_missile, "wand_missile", GuideCategory.ITEMTHROW); EntityProjectileRegistry.registerModEntity(EntityHomingProjectile.class, "magic_missile", 1020); } if (enableEnderDungeonFinder) { ItemProjectileDungeon ender_dungeon = new ItemProjectileDungeon(); ItemRegistry.register(ender_dungeon, "ender_dungeon", GuideCategory.ITEMTHROW); EntityProjectileRegistry.registerModEntity(EntityDungeonEye.class, "dungeonbolt", 1006); LootTableRegistry.registerLoot(ender_dungeon); } if (enderWool) { ItemShearsRanged ender_wool = new ItemShearsRanged(); ItemRegistry.register(ender_wool, "ender_wool", GuideCategory.ITEMTHROW); EntityProjectileRegistry.registerModEntity(EntityShearingBolt.class, "woolbolt", 1003); } if (enderTorch) { ItemProjectileTorch ender_torch = new ItemProjectileTorch(); ItemRegistry.register(ender_torch, "ender_torch", GuideCategory.ITEMTHROW); EntityProjectileRegistry.registerModEntity(EntityTorchBolt.class, "torchbolt", 1002); } if (enderWater) { ItemWaterRemoval ender_water = new ItemWaterRemoval(); ItemRegistry.register(ender_water, "ender_water", GuideCategory.ITEMTHROW); ModCyclic.instance.events.register(ender_water); } if (enderSnow) { ItemProjectileSnow ender_snow = new ItemProjectileSnow(); ItemRegistry.register(ender_snow, "ender_snow", GuideCategory.ITEMTHROW); EntityProjectileRegistry.registerModEntity(EntitySnowballBolt.class, "frostbolt", 1001); ModCyclic.instance.events.register(ender_snow); } if (enderLightning) { ItemProjectileLightning ender_lightning = new ItemProjectileLightning(); ItemRegistry.register(ender_lightning, "ender_lightning", GuideCategory.ITEMTHROW); EntityProjectileRegistry.registerModEntity(EntityLightningballBolt.class, "lightningbolt", 999); LootTableRegistry.registerLoot(ender_lightning); ModCyclic.instance.events.register(ender_lightning); } if (dynamiteSafe) { ItemProjectileTNT dynamite_safe = new ItemProjectileTNT(6, ExplosionType.BLOCKSAFE); ItemRegistry.register(dynamite_safe, "dynamite_safe", GuideCategory.ITEMTHROW); GuideItem page = GuideRegistry.register(GuideCategory.ITEMTHROW, dynamite_safe); EntityProjectileRegistry.registerModEntity(EntityDynamiteBlockSafe.class, "tntblocksafebolt", 1009); EntityDynamiteBlockSafe.renderSnowball = dynamite_safe; projectiles.add(dynamite_safe); page.addRecipePage(RecipeRegistry.addShapelessRecipe(new ItemStack(dynamite_safe, 6), "gunpowder", new ItemStack(Items.SUGAR), "gunpowder", "paper", new ItemStack(Items.CLAY_BALL), new ItemStack(Blocks.BROWN_MUSHROOM), "feather", new ItemStack(Items.WHEAT_SEEDS), "cobblestone")); } if (magicNet) { ItemProjectileMagicNet magic_net = new ItemProjectileMagicNet(); ItemRegistry.register(magic_net, "magic_net", GuideCategory.ITEMTHROW); EntityMagicNetEmpty.renderSnowball = magic_net; EntityProjectileRegistry.registerModEntity(EntityMagicNetFull.class, "magicnetfull", 1011); EntityProjectileRegistry.registerModEntity(EntityMagicNetEmpty.class, "magicnetempty", 1012); projectiles.add(magic_net); } if (dynamiteMining) { ItemProjectileTNT dynamite_mining = new ItemProjectileTNT(6, ExplosionType.MINING); ItemRegistry.register(dynamite_mining, "dynamite_mining", GuideCategory.ITEMTHROW); GuideItem page = GuideRegistry.register(GuideCategory.ITEMTHROW, dynamite_mining); EntityProjectileRegistry.registerModEntity(EntityDynamiteMining.class, "tntminingbolt", 1010); EntityDynamiteMining.renderSnowball = dynamite_mining; projectiles.add(dynamite_mining); page.addRecipePage(RecipeRegistry.addShapelessRecipe(new ItemStack(dynamite_mining, 6), "gunpowder", "ingotIron", "gunpowder", "paper", new ItemStack(Items.CLAY_BALL), new ItemStack(Blocks.RED_MUSHROOM), "feather", new ItemStack(Items.WHEAT_SEEDS), "ingotBrickNether")); } if (enderBombsEnabled) { ItemProjectileTNT ender_tnt_1 = new ItemProjectileTNT(1, ExplosionType.NORMAL); ItemProjectileTNT ender_tnt_2 = new ItemProjectileTNT(2, ExplosionType.NORMAL); ItemProjectileTNT ender_tnt_3 = new ItemProjectileTNT(3, ExplosionType.NORMAL); ItemProjectileTNT ender_tnt_4 = new ItemProjectileTNT(4, ExplosionType.NORMAL); ItemProjectileTNT ender_tnt_5 = new ItemProjectileTNT(5, ExplosionType.NORMAL); ItemProjectileTNT ender_tnt_6 = new ItemProjectileTNT(6, ExplosionType.NORMAL); ItemRegistry.register(ender_tnt_1, "ender_tnt_1", null); ItemRegistry.register(ender_tnt_2, "ender_tnt_2", null); ItemRegistry.register(ender_tnt_3, "ender_tnt_3", null); ItemRegistry.register(ender_tnt_4, "ender_tnt_4", null); ItemRegistry.register(ender_tnt_5, "ender_tnt_5", null); ItemRegistry.register(ender_tnt_6, "ender_tnt_6", null); GuideItem page = GuideRegistry.register(GuideCategory.ITEMTHROW, ender_tnt_1); EntityProjectileRegistry.registerModEntity(EntityDynamite.class, "tntbolt", 1007); projectiles.add(ender_tnt_1); projectiles.add(ender_tnt_2); projectiles.add(ender_tnt_3); projectiles.add(ender_tnt_4); projectiles.add(ender_tnt_5); projectiles.add(ender_tnt_6); //first the basic recipes page.addRecipePage(RecipeRegistry.addShapelessRecipe(new ItemStack(ender_tnt_1, 12), new ItemStack(Blocks.TNT), "paper", new ItemStack(Items.CLAY_BALL), "enderpearl")); page.addRecipePage(RecipeRegistry.addShapelessRecipe(new ItemStack(ender_tnt_2), new ItemStack(ender_tnt_1), new ItemStack(ender_tnt_1), new ItemStack(Items.CLAY_BALL))); page.addRecipePage(RecipeRegistry.addShapelessRecipe(new ItemStack(ender_tnt_3), new ItemStack(ender_tnt_2), new ItemStack(ender_tnt_2), new ItemStack(Items.CLAY_BALL))); page.addRecipePage(RecipeRegistry.addShapelessRecipe(new ItemStack(ender_tnt_4), new ItemStack(ender_tnt_3), new ItemStack(ender_tnt_3), new ItemStack(Items.CLAY_BALL))); page.addRecipePage(RecipeRegistry.addShapelessRecipe(new ItemStack(ender_tnt_5), new ItemStack(ender_tnt_4), new ItemStack(ender_tnt_4), new ItemStack(Items.CLAY_BALL))); page.addRecipePage(RecipeRegistry.addShapelessRecipe(new ItemStack(ender_tnt_6), new ItemStack(ender_tnt_5), new ItemStack(ender_tnt_5), new ItemStack(Items.CLAY_BALL))); //default recipes are added already insice the IRecipe page.addRecipePage(RecipeRegistry.addShapelessRecipe(new ItemStack(ender_tnt_3), new ItemStack(ender_tnt_1), new ItemStack(ender_tnt_1), new ItemStack(ender_tnt_1), new ItemStack(ender_tnt_1), new ItemStack(Items.CLAY_BALL))); //two 3s is four 2s page.addRecipePage(RecipeRegistry.addShapelessRecipe(new ItemStack(ender_tnt_4), new ItemStack(ender_tnt_2), new ItemStack(ender_tnt_2), new ItemStack(ender_tnt_2), new ItemStack(ender_tnt_2), new ItemStack(Items.CLAY_BALL))); //four 3s is two 4s is one 5 page.addRecipePage(RecipeRegistry.addShapelessRecipe(new ItemStack(ender_tnt_5), new ItemStack(ender_tnt_3), new ItemStack(ender_tnt_3), new ItemStack(ender_tnt_3), new ItemStack(ender_tnt_3), new ItemStack(Items.CLAY_BALL))); page.addRecipePage(RecipeRegistry.addShapelessRecipe(new ItemStack(ender_tnt_6), new ItemStack(ender_tnt_4), new ItemStack(ender_tnt_4), new ItemStack(ender_tnt_4), new ItemStack(ender_tnt_4), new ItemStack(Items.CLAY_BALL))); LootTableRegistry.registerLoot(ender_tnt_6); } if (enableAir) { ItemCharmAir charm_air = new ItemCharmAir(); ItemRegistry.register(charm_air, "charm_air", GuideCategory.ITEMBAUBLES); ModCyclic.instance.events.register(charm_air); LootTableRegistry.registerLoot(charm_air); } if (enableFireCharm) { ItemCharmFire charm_fire = new ItemCharmFire(); ItemRegistry.register(charm_fire, "charm_fire", GuideCategory.ITEMBAUBLES); LootTableRegistry.registerLoot(charm_fire); } if (enableSea) { ItemCharmBoat charm_boat = new ItemCharmBoat(); ItemRegistry.register(charm_boat, "charm_boat", GuideCategory.ITEMBAUBLES); } if (enableVoid) { ItemCharmVoid charm_void = new ItemCharmVoid(); ItemRegistry.register(charm_void, "charm_void", GuideCategory.ITEMBAUBLES); LootTableRegistry.registerLoot(charm_void); } if (enableWater) { ItemCharmWater charm_water = new ItemCharmWater(); ItemRegistry.register(charm_water, "charm_water", GuideCategory.ITEMBAUBLES); } if (antidoteCharm) { ItemCharmAntidote charm_antidote = new ItemCharmAntidote(); ItemRegistry.register(charm_antidote, "charm_antidote", GuideCategory.ITEMBAUBLES); LootTableRegistry.registerLoot(charm_antidote); } if (slowfallCharm) { ItemCharmSlowfall charm_wing = new ItemCharmSlowfall(); ItemRegistry.register(charm_wing, "charm_wing", GuideCategory.ITEMBAUBLES); LootTableRegistry.registerLoot(charm_wing); } if (autoTorch) { ItemAutoTorch tool_auto_torch = new ItemAutoTorch(); ItemRegistry.register(tool_auto_torch, "tool_auto_torch", GuideCategory.ITEMBAUBLES); ModCyclic.instance.events.register(tool_auto_torch); LootTableRegistry.registerLoot(tool_auto_torch); } if (enableSpeed) { ItemCharmSpeed charm_speed = new ItemCharmSpeed(); ItemRegistry.register(charm_speed, "charm_speed", GuideCategory.ITEMBAUBLES); } if (foodStep) { ItemAppleStep food_step = new ItemAppleStep(); ItemRegistry.register(food_step, "food_step"); ModCyclic.instance.events.register(food_step); } if (mountInverse) { ItemStirrupsReverse stirrup_inverse = new ItemStirrupsReverse(); ItemRegistry.register(stirrup_inverse, "tool_mount_inverse"); } if (enableHorseFoodUpgrades) { Item emerald_carrot = new ItemHorseUpgrade(HorseUpgradeType.TYPE, new ItemStack(Items.FERMENTED_SPIDER_EYE)); Item lapis_carrot = new ItemHorseUpgrade(HorseUpgradeType.VARIANT, new ItemStack(Items.DYE, 1, EnumDyeColor.BLUE.getDyeDamage())); Item diamond_carrot = new ItemHorseUpgrade(HorseUpgradeType.HEALTH, new ItemStack(Items.DIAMOND)); Item redstone_carrot = new ItemHorseUpgrade(HorseUpgradeType.SPEED, new ItemStack(Items.REDSTONE)); Item ender_carrot = new ItemHorseUpgrade(HorseUpgradeType.JUMP, new ItemStack(Items.ENDER_EYE)); ItemRegistry.register(emerald_carrot, "horse_upgrade_type"); ItemRegistry.register(lapis_carrot, "horse_upgrade_variant"); ItemRegistry.register(diamond_carrot, "horse_upgrade_health"); ItemRegistry.register(redstone_carrot, "horse_upgrade_speed"); ItemRegistry.register(ender_carrot, "horse_upgrade_jump"); ModCyclic.instance.events.register(this);//for SubcribeEvent hooks } if (enableLapisApple) { ItemHorseTame apple_lapis = new ItemHorseTame(); ItemRegistry.register(apple_lapis, "apple_lapis"); ModCyclic.instance.events.register(apple_lapis); } if (enableEmeraldApple) { ItemVillagerMagic apple_emerald = new ItemVillagerMagic(); ItemRegistry.register(apple_emerald, "apple_emerald"); LootTableRegistry.registerLoot(apple_emerald); ModCyclic.instance.events.register(apple_emerald); } if (enableHeartContainer) { ItemHeartContainer heart_food = new ItemHeartContainer(1); ItemRegistry.register(heart_food, "heart_food"); ModCyclic.instance.events.register(heart_food); LootTableRegistry.registerLoot(heart_food); LootTableRegistry.registerLoot(heart_food, ChestType.ENDCITY); LootTableRegistry.registerLoot(heart_food, ChestType.IGLOO); } if (enableHeartToxic) { ItemHeartContainer heart_toxic = new ItemHeartContainer(-1); ItemRegistry.register(heart_toxic, "heart_toxic"); } if (enableInventoryCrafting) { ItemCraftingUnlock crafting_food = new ItemCraftingUnlock(); ItemRegistry.register(crafting_food, "crafting_food"); LootTableRegistry.registerLoot(crafting_food); } if (enableInventoryUpgrade) { ItemInventoryUnlock inventory_food = new ItemInventoryUnlock(); ItemRegistry.register(inventory_food, "inventory_food"); LootTableRegistry.registerLoot(inventory_food); } if (enableCorruptedChorus) { ItemNoclipGhost corrupted_chorus = new ItemNoclipGhost(); ItemRegistry.register(corrupted_chorus, "corrupted_chorus"); ModCyclic.instance.events.register(corrupted_chorus); LootTableRegistry.registerLoot(corrupted_chorus); LootTableRegistry.registerLoot(corrupted_chorus, ChestType.ENDCITY); } if (enableGlowingChorus) { ItemFlight glowing_chorus = new ItemFlight(); ItemRegistry.register(glowing_chorus, "glowing_chorus"); ModCyclic.instance.events.register(glowing_chorus); } if (signEditor) { ItemRegistry.register(new ItemSignEditor(), "sign_editor", GuideCategory.ITEM); } } @Override public void onInit() { ModCyclic.proxy.initColors(); } @Override public void onPostInit() { for (BaseItemProjectile item : projectiles) { BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(item, new BehaviorProjectileThrowable(item)); } } @Override public void syncConfig(Configuration config) { enableHeartToxic = config.getBoolean("heart_toxic", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); lasers = config.getBoolean("laser_cannon", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); robotSpawner = config.getBoolean("robot_spawner", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); signEditor = config.getBoolean("sign_editor", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); chestMinecart = false;// config.getBoolean("GoldChestMinecart", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); dispenserMinecart = false;//config.getBoolean("GoldDispenserMinecart", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); dropperMinecart = config.getBoolean("GoldDropperMinecart", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); turretMinecart = config.getBoolean("GoldTurretMinecart", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); goldMinecart = config.getBoolean("GoldMinecart", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); stoneMinecart = config.getBoolean("StoneMinecart", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableChaos = config.getBoolean("ChaosSiren", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableMissile = config.getBoolean("MagicMissile", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); magicNet = config.getBoolean("MonsterBall", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); dynamiteSafe = config.getBoolean("DynamiteSafe", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); dynamiteMining = config.getBoolean("DynamiteMining", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableEnderDungeonFinder = config.getBoolean("EnderDungeonFinder", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); // enderFishing = config.getBoolean("EnderFishing", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enderSnow = config.getBoolean("EnderSnow", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enderWool = config.getBoolean("EnderWool", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enderTorch = config.getBoolean("EnderTorch", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enderLightning = config.getBoolean("EnderLightning", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enderWater = config.getBoolean("EnderWater", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enderBombsEnabled = config.getBoolean("EnderBombs", "Dynamite I-IV" + Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableAir = config.getBoolean("AirCharm", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableSpeed = config.getBoolean("SpeedCharm", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); slowfallCharm = config.getBoolean("WingCharm", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableFireCharm = config.getBoolean("FireCharm", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableSea = config.getBoolean("SailorCharm", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableVoid = config.getBoolean("VoidCharm", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableWater = config.getBoolean("WaterCharm", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); antidoteCharm = config.getBoolean("AntidoteCharm", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); autoTorch = config.getBoolean("AutomaticTorch", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); foodStep = config.getBoolean("AppleStature", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); mountInverse = config.getBoolean("StirrupInverse", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableLapisApple = config.getBoolean("LapisApple", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableGlowingChorus = config.getBoolean("GlowingChorus(Food)", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableEmeraldApple = config.getBoolean("EmeraldApple", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableHeartContainer = config.getBoolean("HeartContainer(food)", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableInventoryCrafting = config.getBoolean("InventoryCrafting(Food)", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableInventoryUpgrade = config.getBoolean("InventoryUpgrade(Food)", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableCorruptedChorus = config.getBoolean("CorruptedChorus(Food)", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableHorseFoodUpgrades = config.getBoolean("HorseFood", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); String category = Const.ConfigCategory.modpackMisc; ItemHorseUpgrade.HEARTS_MAX = config.getInt("HorseFood Max Hearts", category, 20, 1, 100, "Maximum number of upgraded hearts"); ItemHorseUpgrade.JUMP_MAX = config.getInt("HorseFood Max Jump", category, 6, 1, 20, "Maximum value of jump. Naturally spawned/bred horses seem to max out at 5.5"); ItemHorseUpgrade.SPEED_MAX = config.getInt("HorseFood Max Speed", category, 50, 1, 99, "Maximum value of speed (this is NOT blocks/per second or anything like that)"); enderEyeReuse = config.getBoolean("item.ender_eye_orb", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); evokerFang = config.getBoolean("EvokerFang", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enablePlayerLauncher = config.getBoolean("PlayerLauncher", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableSoulstone = config.getBoolean("Soulstone", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableTrader = config.getBoolean("Merchant Almanac", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableLever = config.getBoolean("Remote Lever", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableElevate = config.getBoolean("RodElevation", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableCGlove = config.getBoolean("ClimbingGlove", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableBlockRot = config.getBoolean("BlockRotator", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enablewaterSpread = config.getBoolean("WaterSpreader", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableFreezer = config.getBoolean("WaterFroster", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableFireKiller = config.getBoolean("WaterSplasher", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enderSack = config.getBoolean("EnderSack", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableTorchLauncher = config.getBoolean("TorchLauncher", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); storageBagEnabled = config.getBoolean("StorageBag", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableEnderBook = config.getBoolean("EnderBook", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableWarpHomeTool = config.getBoolean("EnderWingPrime", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableWarpSpawnTool = config.getBoolean("EnderWing", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableSpawnInspect = config.getBoolean("SpawnDetector", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enablePearlReuse = config.getBoolean("EnderOrb", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableHarvestWeeds = config.getBoolean("BrushScythe", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableToolHarvest = config.getBoolean("HarvestScythe", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableHarvestLeaves = config.getBoolean("TreeScythe", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableToolPush = config.getBoolean("PistonScepter", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableSleepingMat = config.getBoolean("SleepingMat", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableCyclicWand = config.getBoolean("CyclicWand", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableProspector = config.getBoolean("Prospector", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableCavefinder = config.getBoolean("Cavefinder", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableSwappers = config.getBoolean("ExchangeScepters", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableRando = config.getBoolean("BlockRandomizer", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enablePearlReuseMounted = config.getBoolean("EnderOrbMounted", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableCarbonPaper = config.getBoolean("CarbonPaper", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableChestSack = config.getBoolean("ChestSack", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableStirrups = config.getBoolean("Stirrups", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); String[] deflist = new String[] { "minecraft:mob_spawner", "minecraft:obsidian" }; ItemBuildSwapper.swapBlacklist = config.getStringList("ExchangeSceptersBlacklist", Const.ConfigCategory.items, deflist, "Blocks that will not be broken by the exchange scepters. It will also not break anything that is unbreakable (such as bedrock), regardless of if its in this list or not. "); enableMattock = config.getBoolean("Mattock", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); glowingHelmet = config.getBoolean("GlowingHelmet", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enablePurpleGear = config.getBoolean("PurpleArmor", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); enableSandstoneTools = config.getBoolean("SandstoneTools", Const.ConfigCategory.content, true, "Sandstone tools are between wood and stone. " + Const.ConfigCategory.contentDefaultText); enableEmeraldGear = config.getBoolean("Emerald Gear", Const.ConfigCategory.content, true, "Emerald armor and tools that are slightly weaker than diamond. " + Const.ConfigCategory.contentDefaultText); enablePurpleSwords = config.getBoolean("SwordsFrostEnder", Const.ConfigCategory.content, true, "Enable the epic swords. " + Const.ConfigCategory.contentDefaultText); enableEmeraldGear = config.getBoolean("Emerald Gear", Const.ConfigCategory.content, true, "Emerald armor and tools that are slightly weaker than diamond. " + Const.ConfigCategory.contentDefaultText); enableNetherbrickTools = config.getBoolean("NetherbrickTools", Const.ConfigCategory.content, true, "Netherbrick tools have mining level of stone but improved stats. " + Const.ConfigCategory.contentDefaultText); } }
package com.tang.intellij.lua.psi; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.ProjectAndLibrariesScope; import com.intellij.psi.util.PsiTreeUtil; import com.tang.intellij.lua.comment.LuaCommentUtil; import com.tang.intellij.lua.comment.psi.LuaDocGlobalDef; import com.tang.intellij.lua.comment.psi.LuaDocParamDef; import com.tang.intellij.lua.comment.psi.api.LuaComment; import com.tang.intellij.lua.lang.type.LuaAnonymousType; import com.tang.intellij.lua.lang.type.LuaType; import com.tang.intellij.lua.lang.type.LuaTypeSet; import com.tang.intellij.lua.lang.type.LuaTypeTable; import com.tang.intellij.lua.stubs.index.LuaGlobalFieldIndex; import com.tang.intellij.lua.stubs.index.LuaGlobalFuncIndex; import org.jetbrains.annotations.NotNull; import java.util.List; public class LuaPsiResolveUtil { private static LuaFuncBodyOwner funcBodyOwner = null; static LuaFuncBodyOwner resolveFuncBodyOwner(@NotNull LuaNameRef ref) { String refName = ref.getName(); //local if (funcBodyOwner == null) { LuaPsiTreeUtil.walkUpLocalFuncDef(ref, localFuncDef -> { if (refName.equals(localFuncDef.getName())) { funcBodyOwner = localFuncDef; return false; } return true; }); } //global function if (funcBodyOwner == null) { Project project = ref.getProject(); funcBodyOwner = LuaGlobalFuncIndex.find(refName, project, new ProjectAndLibrariesScope(project)); } LuaFuncBodyOwner temp = funcBodyOwner; funcBodyOwner = null; return temp; } private static PsiElement resolveResult; public static PsiElement resolve(LuaNameRef ref) { String refName = ref.getName(); if (refName.equals("self")) { LuaClassMethodDef classMethodFuncDef = PsiTreeUtil.getParentOfType(ref, LuaClassMethodDef.class); if (classMethodFuncDef != null) { LuaNameRef nameRef = classMethodFuncDef.getClassMethodName().getNameRef(); if (nameRef != null) return nameRef.resolve(); } return null; } //local , LuaPsiTreeUtil.walkUpLocalNameDef(ref, nameDef -> { if (refName.equals(nameDef.getName())) { resolveResult = nameDef; return false; } return true; }); //local if (resolveResult == null) { LuaPsiTreeUtil.walkUpLocalFuncDef(ref, nameDef -> { String name= nameDef.getName(); if (refName.equals(name)) { resolveResult = nameDef; return false; } return true; }); } //global field if (resolveResult == null) { Project project = ref.getProject(); LuaDocGlobalDef globalDef = LuaGlobalFieldIndex.find(refName, project, new ProjectAndLibrariesScope(project)); if (globalDef != null) { LuaCommentOwner owner = LuaCommentUtil.findOwner(globalDef); if (owner instanceof LuaAssignStat) { LuaAssignStat assignStat = (LuaAssignStat) owner; List<LuaVar> varList = assignStat.getVarList().getVarList(); for (LuaVar var : varList) { LuaNameRef nameRef = var.getNameRef(); if (nameRef != null && nameRef.getText().equals(refName)) { resolveResult = nameRef; break; } } } } } //global function if (resolveResult == null) { Project project = ref.getProject(); resolveResult = LuaGlobalFuncIndex.find(refName, project, new ProjectAndLibrariesScope(project)); } PsiElement result = resolveResult; resolveResult = null; return result; } public static PsiElement resolve(LuaIndexExpr myElement) { PsiElement id = myElement.getId(); if (id == null) return null; LuaTypeSet typeSet = myElement.guessPrefixType(); if (typeSet != null) { String idString = id.getText(); Project project = myElement.getProject(); GlobalSearchScope scope = new ProjectAndLibrariesScope(project); for (LuaType type : typeSet.getTypes()) { if (type instanceof LuaTypeTable) { // table LuaTypeTable tableType = (LuaTypeTable) type; LuaTableField field = tableType.tableConstructor.findField(idString); if (field != null) { return field; } } else { LuaClassField fieldDef = type.findField(idString, project, scope); if (fieldDef != null) return fieldDef; LuaClassMethodDef methodDef = type.findMethod(idString, project, scope); if (methodDef != null) return methodDef; } } } return null; } static LuaTypeSet resolveType(LuaNameDef nameDef) { if (nameDef instanceof LuaParamNameDef) { LuaCommentOwner owner = PsiTreeUtil.getParentOfType(nameDef, LuaCommentOwner.class); if (owner != null) { LuaComment comment = owner.getComment(); if (comment != null) { LuaDocParamDef paramDef = comment.getParamDef(nameDef.getText()); if (paramDef != null) { return paramDef.resolveType(); } } } } //Table else if (nameDef.getParent() instanceof LuaTableField) { LuaTableField field = (LuaTableField) nameDef.getParent(); LuaExpr expr = PsiTreeUtil.findChildOfType(field, LuaExpr.class); if (expr != null) return expr.guessType(); } //local x = 0 else { LuaLocalDef localDef = PsiTreeUtil.getParentOfType(nameDef, LuaLocalDef.class); if (localDef != null) { LuaTypeSet typeSet = null; LuaComment comment = localDef.getComment(); if (comment != null) { typeSet = comment.guessType(); } // expr if (typeSet == null || typeSet.isEmpty()) { LuaNameList nameList = localDef.getNameList(); LuaExprList exprList = localDef.getExprList(); if (nameList != null && exprList != null) { int index = nameList.getNameDefList().indexOf(nameDef); if (index != -1) { List<LuaExpr> exprs = exprList.getExprList(); if (index < exprs.size()) { LuaExpr expr = exprs.get(index); typeSet = expr.guessType(); } } } } //anonymous if (typeSet == null ||typeSet.isEmpty()) typeSet = LuaTypeSet.create(LuaAnonymousType.create(nameDef)); return typeSet; } } return null; } /** * require * @param pathString require "aa.bb.cc" * @param project MyProject * @return PsiFile */ public static LuaFile resolveRequireFile(String pathString, Project project) { if (pathString == null) return null; int lastDot = pathString.lastIndexOf('.'); String packagePath = ""; String fileName = pathString; if (lastDot != -1) { fileName = pathString.substring(lastDot + 1); packagePath = pathString.substring(0, lastDot); } fileName += ".lua"; PsiPackage psiPackage = JavaPsiFacade.getInstance(project).findPackage(packagePath); if (psiPackage != null) { PsiDirectory[] directories = psiPackage.getDirectories(); for (PsiDirectory directory : directories) { PsiFile file = directory.findFile(fileName); if (file instanceof LuaFile) return (LuaFile) file; } } return null; } public static String getAnonymousType(LuaNameDef nameDef) { return nameDef.getName(); } }
package com.tencent.java.collections; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import org.apache.logging.log4j.core.lookup.MainMapLookup; public class ConsistentHash<T> { private final HashFunction hashFunction; private final int numberOfReplicas;// , * numberOfReplicas = private final SortedMap<Long, T> circle = new TreeMap<Long, T>();// hash public static void main(String[] args) { HashFunction hashFunction = new HashFunction(); System.out.println(hashFunction.hash("hello")); } public ConsistentHash(HashFunction hashFunction, int numberOfReplicas, Collection<T> nodes) { super(); this.hashFunction = hashFunction; this.numberOfReplicas = numberOfReplicas; for (T node : nodes) add(node); } public void add(T node) { for (int i = 0; i < numberOfReplicas; i++) // node, numberOfReplicas /* * (i)hash,node * node,node */ circle.put(hashFunction.hash(node.toString() + i), node); } public void remove(T node) { for(int i=0; i<numberOfReplicas; i++) { circle.remove(hashFunction.hash(node.toString()+i)); } } /* * ,key Hash * * */ public T get(Object key) { if (circle.isEmpty()) return null; long hash = hashFunction.hash((String) key);// node String,nodehashCode if (!circle.containsKey(hash)) { SortedMap<Long, T> tailMap = circle.tailMap(hash); hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey(); } return circle.get(hash); } public long getSize() { return circle.size(); } public void testBalance(){ Set<Long> sets = circle.keySet();//TreeMapKey SortedSet<Long> sortedSets= new TreeSet<Long>(sets);//Key for(Long hashCode : sortedSets){ System.out.println(hashCode); } System.out.println(" /* * MD5long hashCode hashCode */ Iterator<Long> it = sortedSets.iterator(); Iterator<Long> it2 = sortedSets.iterator(); if(it2.hasNext()) it2.next(); long keyPre, keyAfter; while(it.hasNext() && it2.hasNext()){ keyPre = it.next(); keyAfter = it2.next(); System.out.println(keyAfter - keyPre); } } } class HashFunction { private MessageDigest md5 = null; /** * keyMD5 * * @param key */ public long hash(String key) { if (md5 == null) { try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } } md5.reset(); md5.update(key.getBytes()); byte[] bkey = md5.digest(); long result = ((bkey[3] & 0xFF) << 24) + ((bkey[2] & 0xFF) << 16) + ((bkey[1] & 0xFF) << 8) + (bkey[0] & 0xFF); return result; } public static void main(String[] args) { } }
package com.thed.service.impl; import com.thed.model.Attachment; import com.thed.model.GenericAttachmentDTO; import com.thed.service.AttachmentService; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; public class AttachmentServiceImpl extends BaseServiceImpl implements AttachmentService { public AttachmentServiceImpl() { super(); } @Override public void addAttachments(ItemType itemType, Map<Long, List<String>> itemIdFilePathMap, Map<Long, GenericAttachmentDTO> statusAttachmentMap) throws IOException, URISyntaxException { for (Long itemId : itemIdFilePathMap.keySet()) { List<String> attachmentFilePaths = itemIdFilePathMap.get(itemId); List<GenericAttachmentDTO> attachmentDTOs = new ArrayList<>(); for (String filePath : attachmentFilePaths) { Path path = Paths.get(filePath); // remove special character from filename String fileName = path.getFileName().toString().replaceAll("[\\\\/:*?\"<>|]", ""); int length = fileName.substring(0,fileName.lastIndexOf(".")).length(); if(length > 240) { String extension = fileName.substring(fileName.lastIndexOf(".")); fileName = fileName.substring(0, 240); fileName += extension; } String mimeType = Files.probeContentType(path); byte[] bytes = Files.readAllBytes(Paths.get(filePath)); GenericAttachmentDTO attachmentDTO = new GenericAttachmentDTO(); attachmentDTO.setFieldName(itemType.toString()); attachmentDTO.setFileName(fileName); attachmentDTO.setContentType(mimeType); attachmentDTO.setByteData(bytes); attachmentDTOs.add(attachmentDTO); } if(statusAttachmentMap.containsKey(itemId)) { attachmentDTOs.add(statusAttachmentMap.get(itemId)); } List<GenericAttachmentDTO> newAttachmentDTOs = zephyrRestService.uploadAttachments(attachmentDTOs); List<Attachment> attachments = new ArrayList<>(); for (GenericAttachmentDTO genericAttachmentDTO : newAttachmentDTOs) { Attachment attachment = new Attachment(); attachment.setContentType(genericAttachmentDTO.getContentType()); GenericAttachmentDTO oldAttachment = attachmentDTOs.stream().filter(attachmentDTO -> genericAttachmentDTO.getFileName().equals(attachmentDTO.getFileName())).findAny().orElse(null); attachment.setFileSize(oldAttachment != null ? (long)oldAttachment.getByteData().length : 0); attachment.setItemId(itemId); attachment.setItemType(itemType.toString()); attachment.setName(genericAttachmentDTO.getFileName()); attachment.setTempPath(genericAttachmentDTO.getTempFilePath()); attachment.setCreatedBy(zephyrRestService.getCurrentUser().getId()); attachment.setTimeStamp(System.currentTimeMillis()); attachments.add(attachment); } zephyrRestService.addAttachment(attachments); } } }
package com.vaguehope.onosendai.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.util.AttributeSet; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.ProgressBar; import android.widget.TextView; import com.vaguehope.onosendai.R; import com.vaguehope.onosendai.images.ImageLoadRequest; import com.vaguehope.onosendai.images.ImageLoadRequest.ImageLoadListener; public class PendingImage extends FrameLayout { private final FixedWidthImageView image; private final ProgressBar prg; private final TextView status; public PendingImage (final Context context, final AttributeSet attrs) { this(context, attrs, 0); } public PendingImage (final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PendingImage); final int maxHeightPixels = a.getDimensionPixelSize(R.styleable.PendingImage_maxHeight, -1); a.recycle(); this.prg = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal); this.imageLoadListener.imageFetchProgress(0, 0); addView(this.prg); this.status = new TextView(context); this.status.setLayoutParams(new FrameLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM)); this.status.setPadding( this.status.getPaddingLeft() + dipToPixels(context, 10), this.status.getPaddingTop(), this.status.getPaddingRight() + dipToPixels(context, 10), this.status.getPaddingBottom() + dipToPixels(context, 20)); addView(this.status); this.image = new ProgressAwareFixedWidthImageView(context, this.prg, this.status, maxHeightPixels); setupImageView(this.image, maxHeightPixels); this.image.setVisibility(View.GONE); addView(this.image); } public ImageView getImage () { return this.image; } public ImageLoadListener getImageLoadListener () { return this.imageLoadListener; } private static void setupImageView (final FixedWidthImageView image, final int maxHeightPixels) { if (maxHeightPixels > 0) { setImageLimitedHeight(image, maxHeightPixels); } else { setImageFullHeight(image); } } protected static void resetImageView (final FixedWidthImageView image, final int maxHeightPixels) { if (maxHeightPixels > 0) setImageLimitedHeight(image, maxHeightPixels); } private static void setImageLimitedHeight (final FixedWidthImageView image, final int maxHeightPixels) { image.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, maxHeightPixels)); image.setScaleType(ScaleType.CENTER_CROP); image.setMaxHeight(maxHeightPixels); image.setClickable(true); image.setOnClickListener(new GoFullHeightListener(image)); } protected static void setImageFullHeight (final FixedWidthImageView image) { image.setMaxHeight(-1); image.setOnClickListener(null); image.setClickable(false); image.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); image.setScaleType(ScaleType.FIT_CENTER); image.setAdjustViewBounds(true); } private final ImageLoadListener imageLoadListener = new ImageLoadListener() { @Override public void imageLoadProgress (final String msg) { PendingImage.this.status.setText(msg); } @Override public void imageFetchProgress (final int progress, final int total) { if (total > 0) { if (PendingImage.this.prg.isIndeterminate()) { PendingImage.this.prg.setIndeterminate(false); PendingImage.this.prg.setLayoutParams(new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER)); } PendingImage.this.prg.setMax(total); PendingImage.this.prg.setProgress(progress); } else { if (!PendingImage.this.prg.isIndeterminate()) { PendingImage.this.prg.setIndeterminate(true); PendingImage.this.prg.setLayoutParams(new FrameLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER)); } } } @Override public void imageLoaded (final ImageLoadRequest req) {} }; private static class ProgressAwareFixedWidthImageView extends FixedWidthImageView { private final ProgressBar prg; private final TextView status; private final int maxHeightPixels; public ProgressAwareFixedWidthImageView (final Context context, final ProgressBar prg, final TextView status, final int maxHeightPixels) { super(context); this.status = status; this.maxHeightPixels = maxHeightPixels; this.prg = prg; } // XXX these are icky hacks to get 'show pending' and 'show image' events. @Override public void setImageResource (final int resId) { if (resId == R.drawable.question_blue) { super.setImageDrawable(null); setVisibility(View.GONE); this.prg.setVisibility(View.VISIBLE); this.status.setVisibility(View.VISIBLE); } else if (resId == R.drawable.exclamation_red) { super.setImageDrawable(null); setVisibility(View.GONE); this.prg.setVisibility(View.GONE); this.status.setVisibility(View.VISIBLE); } else { resetImageView(this, this.maxHeightPixels); super.setImageResource(resId); setVisibility(View.VISIBLE); this.prg.setVisibility(View.GONE); this.status.setVisibility(View.GONE); } } @Override public void setImageBitmap (final Bitmap bm) { resetImageView(this, this.maxHeightPixels); super.setImageBitmap(bm); setVisibility(View.VISIBLE); this.prg.setVisibility(View.GONE); this.status.setVisibility(View.GONE); } } private static class GoFullHeightListener implements OnClickListener { private final FixedWidthImageView image; public GoFullHeightListener (final FixedWidthImageView image) { this.image = image; } @Override public void onClick (final View v) { setImageFullHeight(this.image); } } private static int dipToPixels (final Context context, final int a) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, a, context.getResources().getDisplayMetrics()); } }
package de.synaxon.graphitereceiver; import com.vmware.ee.statsfeeder.ExecutionContext; import com.vmware.ee.statsfeeder.PerfMetricSet; import com.vmware.ee.statsfeeder.PerfMetricSet.PerfMetric; import com.vmware.ee.statsfeeder.StatsExecutionContextAware; import com.vmware.ee.statsfeeder.StatsFeederListener; import com.vmware.ee.statsfeeder.StatsListReceiver; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.net.Socket; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Iterator; import java.util.Properties; import java.util.TimeZone; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * * @author karl spies */ public class MetricsReceiver implements StatsListReceiver, StatsFeederListener, StatsExecutionContextAware { Log logger = LogFactory.getLog(MetricsReceiver.class); private String name = "SampleStatsReceiver"; private String graphite_prefix = "vmware"; //set to true for backwards compatibility private Boolean use_fqdn = true; //set to true for backwards compatibility private Boolean use_entity_type_prefix = false; private ExecutionContext context; private PrintStream writer; private Socket client; PrintWriter out; private Properties props; /** * This constructor will be called by StatsFeeder to load this receiver. The props object passed is built * from the content in the XML configuration for the receiver. * <pre> * {@code * <receiver> * <name>sample</name> * <class>com.vmware.ee.statsfeeder.SampleStatsReceiver</class> * <!-- If you need some properties specify them like this * <properties> * <property> * <name>some_property</name> * <value>some_value</value> * </property> * </properties> * --> * </receiver> * } * </pre> * * @param name * @param props */ public MetricsReceiver(String name, Properties props) { this.name = name; this.props = props; } /** * * @param name */ public void setName(String name) { this.name = name; } /** * * @return */ public String getName() { return name; } /** * This method is called when the receiver is initialized and passes the StatsFeeder execution context * which can be used to look up properties or other configuration data. * * It can also be used to retrieve the vCenter connection information * * @param context - The current execution context */ @Override public void setExecutionContext(ExecutionContext context) { this.context = context; String prefix=this.props.getProperty("prefix"); String use_fqdn=this.props.getProperty("use_fqdn"); String use_entity_type_prefix=this.props.getProperty("use_entity_type_prefix"); if(prefix != null && !prefix.isEmpty()) this.graphite_prefix=prefix; if(use_fqdn != null && !use_fqdn.isEmpty()) this.use_fqdn=Boolean.valueOf(use_fqdn); if(use_entity_type_prefix != null && !use_entity_type_prefix.isEmpty()) this.use_entity_type_prefix=Boolean.valueOf(use_entity_type_prefix); } private String[] splitCounterName(String counterName) { //should split string in a 3 componet array // [0] = groupName // [1] = metricName // [2] = rollup String[] result=new String[3]; String[] tmp=counterName.split("[.]"); //group Name result[0]=tmp[0]; //rollup result[2]=tmp[tmp.length-1]; result[1]=tmp[1]; if ( tmp.length > 3){ for(int i=2;i<tmp.length-1;++i) { result[1]=result[1]+"."+tmp[i]; } } return result; } /** * Main receiver entry point. This will be called for each entity and each metric which were retrieved by * StatsFeeder. * * @param entityName - The name of the statsfeeder entity being retrieved * @param metricSet - The set of metrics retrieved for the entity */ @Override public void receiveStats(String entityName, PerfMetricSet metricSet) { if (metricSet != null) { //-- Samples come with the following date format final DateFormat SDF = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'"); SDF.setTimeZone(TimeZone.getTimeZone("UTC")); String node; String eName=null; String counterName=metricSet.getCounterName(); //Get Instance Name String instanceName=metricSet.getInstanceId() .replace('.','_') .replace('-','_') .replace('/','.') .replace(' ','_'); String statType=metricSet.getStatType(); if(use_entity_type_prefix) { if(entityName.contains("[VirtualMachine]")) { eName="vm." +entityName.replace("[vCenter]", "").replace("[VirtualMachine]", "").replace('.', '_'); }else if (entityName.contains("[HostSystem]")) { //for ESX only hostname if(!use_fqdn) { eName="esx." +entityName.replace("[vCenter]", "").replace("[HostSystem]", "").split("[.]",2)[0]; }else { eName="esx." +entityName.replace("[vCenter]", "").replace("[HostSystem]", "").replace('.', '_'); } }else if (entityName.contains("[Datastore]")) { eName="dts." +entityName.replace("[vCenter]", "").replace("[Datastore]", "").replace('.', '_'); }else if (entityName.contains("[ResourcePool]")) { eName="rp." +entityName.replace("[vCenter]", "").replace("[ResourcePool]", "").replace('.', '_'); } } else { eName=entityName.replace("[vCenter]", "") .replace("[VirtualMachine]", "") .replace("[HostSystem]", "") .replace("[Datastore]", "") .replace("[ResourcePool]", ""); if(!use_fqdn && entityName.contains("[HostSystem]")){ eName=eName.split("[.]",2)[0]; } eName=eName.replace('.', '_'); } eName=eName.replace(' ','_').replace('-','_'); if (instanceName.equals("")) { String[] counterInfo=splitCounterName(counterName); String groupName =counterInfo[0]; String metricName =counterInfo[1]; String rollup =counterInfo[2]; node = String.format("%s.%s.%s.%s_%s_%s",graphite_prefix,eName,groupName,metricName,rollup,statType); logger.debug("GP :" +graphite_prefix+ " EN: "+eName+" CN :"+ counterName +" ST :"+statType); } else { //Get group name (xxxx) metric name (yyyy) and rollup (zzzz) // from "xxxx.yyyyyy.xxxxx" on the metricName String[] counterInfo=splitCounterName(counterName); String groupName =counterInfo[0]; String metricName =counterInfo[1]; String rollup =counterInfo[2]; node = String.format("%s.%s.%s.%s.%s_%s_%s",graphite_prefix,eName,groupName,instanceName,metricName,rollup,statType); logger.debug("GP :" +graphite_prefix+ " EN: "+eName+" GN :"+ groupName +" IN :"+instanceName+" MN :"+metricName+" RU"+rollup +"ST :"+statType); } //logger.debug("ENTITY NAME : " + entityName +" ENTITY NAME2: "+metricSet.getEntityName()+ " COUNTER NAME: " + metricSet.getCounterName()); //logger.debug("MOREF : "+metricSet.getMoRef()+ " INSTANCE ID :"+ metricSet.getInstanceId()+" string :"+metricSet.toString()); try { Iterator<PerfMetric> metrics = metricSet.getMetrics(); while (metrics.hasNext()) { PerfMetric sample = metrics.next(); out.printf("%s %s %s%n", node, sample.getValue(), SDF.parse(sample.getTimestamp()).getTime() / 1000); } } catch (Throwable t) { logger.error("Error processing entity stats ", t); } } } /** * This method is guaranteed to be called at the start of each retrieval in single or feeder mode. * Receivers can place initialization code here that should be executed before retrieval is started. */ @Override public void onStartRetrieval() { try { this.client = new Socket( this.props.getProperty("host"), Integer.parseInt(this.props.getProperty("port", "2003")) ); OutputStream s = this.client.getOutputStream(); this.out = new PrintWriter(s, true); } catch (IOException ex) { logger.error("Can't connect to graphite.", ex); } } /** * This method is guaranteed to be called, just once, at the end of each retrieval in single or feeder * mode. Receivers can place termination code here that should be executed after the retrieval is * completed. */ @Override public void onEndRetrieval() { try { this.out.close(); this.client.close(); } catch (IOException ex) { logger.error("Can't close resources.", ex); } } }
package edu.harvard.iq.dataverse; import edu.harvard.iq.dataverse.authorization.Permission; import edu.harvard.iq.dataverse.authorization.users.User; import edu.harvard.iq.dataverse.engine.command.Command; import edu.harvard.iq.dataverse.engine.command.impl.*; import java.util.HashMap; import java.util.Map; import javax.ejb.EJB; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; /** * * @author gdurand */ @ViewScoped @Named public class PermissionsWrapper implements java.io.Serializable { @EJB PermissionServiceBean permissionService; @Inject DataverseSession session; private Map<Long, Map<Class<? extends Command>, Boolean>> commandMap = new HashMap<>(); /** * Check if the current Dataset can Issue Commands * * @param commandName */ private boolean canIssueCommand(DvObject dvo, Class<? extends Command> command) { if ((dvo == null) || (command == null)) { return false; } if (commandMap.containsKey(dvo.getId())) { Map<Class<? extends Command>, Boolean> dvoCommandMap = this.commandMap.get(dvo.getId()); if (dvoCommandMap.containsKey(command)) { return dvoCommandMap.get(command); } else { return addCommandtoDvoCommandMap(dvo, command, dvoCommandMap); } } else { Map newDvoCommandMap = new HashMap(); commandMap.put(dvo.getId(), newDvoCommandMap); return addCommandtoDvoCommandMap(dvo, command, newDvoCommandMap); } } private boolean addCommandtoDvoCommandMap(DvObject dvo, Class<? extends Command> command, Map<Class<? extends Command>, Boolean> dvoCommandMap) { boolean canIssueCommand; canIssueCommand = permissionService.on(dvo).canIssue(command); dvoCommandMap.put(command, canIssueCommand); return canIssueCommand; } public boolean canManageDataversePermissions(User u, Dataverse dv) { return permissionService.userOn(u, dv).has(Permission.ManageDataversePermissions); } public boolean CanIssueUpdateDataverseCommand(DvObject dvo) { return canIssueCommand(dvo, UpdateDataverseCommand.class); } public boolean CanIssuePublishDataverseCommand(DvObject dvo) { return canIssueCommand(dvo, PublishDataverseCommand.class); } public boolean CanIssueDeleteataverseCommand(DvObject dvo) { return canIssueCommand(dvo, DeleteDataverseCommand.class); } public boolean canManagePermissions(DvObject dvo) { User u = session.getUser(); return dvo instanceof Dataverse ? canManageDataversePermissions(u, (Dataverse) dvo) : canManageDatasetPermissions(u, (Dataset) dvo); } public boolean canManageDatasetPermissions(User u, Dataset ds) { return permissionService.userOn(u, ds).has(Permission.ManageDatasetPermissions); } }
package edu.jhu.pacaya.gm.data; import java.io.File; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.jhu.pacaya.util.Prm; import edu.jhu.prim.util.Timer; /** * Factory for FgExamples. * * This neatly packages up several important features: (1) feature count cutoffs * and (2) caching of examples. * * These two are intertwined in that both features affect the growth of the * feature template alphabets. * * @author mgormley * @author mmitchell */ public class FgExampleListBuilder { public enum CacheType { MEMORY_STORE, CACHE, DISK_STORE, NONE } /** Parameters for FgExamplesBuilder. */ public static class FgExamplesBuilderPrm extends Prm { private static final long serialVersionUID = 1L; /** The type of FgExamples object to wrap the factory in. */ public CacheType cacheType = CacheType.NONE; /** * The maximum number of entries to keep in a memory-cache, or -1 to use * a SoftReference cache. */ public int maxEntriesInMemory = -1; /** Whether to GZip the disk cache. */ public boolean gzipped = false; /** The directory in which the disk store file should be created. */ public File cacheDir = new File("."); } private static final Logger log = LoggerFactory.getLogger(FgExampleListBuilder.class); private FgExamplesBuilderPrm prm; public FgExampleListBuilder(FgExamplesBuilderPrm prm) { this.prm = prm; } public FgExampleList getInstance(FgExampleList data) { if (prm.cacheType == CacheType.CACHE) { data = new FgExampleCache(data, prm.maxEntriesInMemory, prm.gzipped); } else if (prm.cacheType == CacheType.MEMORY_STORE) { FgExampleStore store = new FgExampleMemoryStore(); constructAndStoreAll(data, store); data = store; } else if (prm.cacheType == CacheType.DISK_STORE) { FgExampleStore store = new FgExampleDiskStore(prm.cacheDir, prm.gzipped, prm.maxEntriesInMemory); constructAndStoreAll(data, store); data = store; } else if (prm.cacheType == CacheType.NONE) { // Do nothing. } else { throw new IllegalStateException("Unsupported cache type: " + prm.cacheType); } return data; } public static void constructAndStoreAll(FgExampleList examples, FgExampleStore store) { Timer fgTimer = new Timer(); for (int i = 0; i < examples.size(); i++) { if (i % 1000 == 0 && i > 0) { log.debug("Preprocessed " + i + " examples..."); } // Construct the example to update counter, and then discard it. fgTimer.start(); LFgExample ex = examples.get(i); if (store != null) { store.add(ex); } fgTimer.stop(); } log.info("Time (ms) to construct factor graph: " + fgTimer.totMs()); } }
package edu.kit.ipd.crowdcontrol.objectservice; import edu.kit.ipd.crowdcontrol.objectservice.crowdworking.PlatformManager; import edu.kit.ipd.crowdcontrol.objectservice.database.DatabaseManager; import edu.kit.ipd.crowdcontrol.objectservice.database.operations.*; import edu.kit.ipd.crowdcontrol.objectservice.rest.Router; import edu.kit.ipd.crowdcontrol.objectservice.rest.resources.*; import org.jooq.SQLDialect; import javax.naming.NamingException; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.util.Properties; import java.util.function.Function; /** * @author Niklas Keller */ public class Main { public static void main(String[] args) throws IOException { Properties properties = new Properties(); try (InputStream in = Main.class.getResourceAsStream("/config.properties")) { properties.load(in); } catch (IOException e) { e.printStackTrace(); System.exit(1); } Function<String, String> trimIfNotNull = s -> { if (s != null) { return s.trim(); } else { return null; } }; String url = trimIfNotNull.apply(properties.getProperty("database.url")); String username = trimIfNotNull.apply(properties.getProperty("database.username")); String password = trimIfNotNull.apply(properties.getProperty("database.password")); String databasePool = trimIfNotNull.apply(properties.getProperty("database.poolName")); String readOnlyUsername = trimIfNotNull.apply(properties.getProperty("database.readonly.username")); String readOnlyPassword = trimIfNotNull.apply(properties.getProperty("database.readonly.password")); SQLDialect dialect = SQLDialect.valueOf(properties.getProperty("database.dialect").trim()); DatabaseManager databaseManager = null; try { databaseManager = new DatabaseManager(username, password, url, databasePool, dialect); databaseManager.initDatabase(); boot(databaseManager, readOnlyUsername, readOnlyPassword); } catch (NamingException | SQLException e) { System.err.println("Unable to establish database connection."); e.printStackTrace(); System.exit(-1); } } private static void boot(DatabaseManager databaseManager, String readOnlyDBUser, String readOnlyDBPassword) throws SQLException { PlatformManager platformManager = null; // TODO TemplateOperations templateOperations = new TemplateOperations(databaseManager.getContext()); NotificationOperations notificationRestOperations = new NotificationOperations(databaseManager, readOnlyDBUser, readOnlyDBPassword); PlatformOperations platformOperations = new PlatformOperations(databaseManager.getContext()); WorkerOperations workerOperations = new WorkerOperations(databaseManager.getContext()); CalibrationOperations calibrationOperations = new CalibrationOperations(databaseManager.getContext()); ExperimentOperations experimentOperations = new ExperimentOperations(databaseManager.getContext()); AnswerRatingOperations answerRatingOperations = new AnswerRatingOperations(databaseManager.getContext()); TagConstraintsOperations tagConstraintsOperations = new TagConstraintsOperations(databaseManager.getContext()); AlgorithmOperations algorithmsOperations = new AlgorithmOperations(databaseManager.getContext()); new Router( new TemplateResource(templateOperations), new NotificationResource(notificationRestOperations), new PlatformResource(platformOperations), new WorkerResource(workerOperations, platformManager), new CalibrationResource(calibrationOperations), new ExperimentResource(experimentOperations, answerRatingOperations, calibrationOperations, tagConstraintsOperations, workerOperations, algorithmsOperations), new AlgorithmResources(algorithmsOperations)).init(); } }
package eme.generator.saving; import java.io.IOException; import java.util.Collections; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Path; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; /** * This is the abstract super class for all saving strategies. * @author Timur Saglam */ public abstract class AbstractSavingStrategy { private boolean saveInProject; /** * Basic constructor. Takes the name of the project. * @param saveInProject determines whether the folder where the file is saved should be * refreshed in the Eclipse IDE. Set this true if the file is saved in a project in the IDE. */ public AbstractSavingStrategy(boolean saveInProject) { this.saveInProject = saveInProject; } /** * Saves an EPackage as an Ecore file. The method calls the methods filePath() and fileName() to * get the information it needs to save the metamodel. If the default saving behavior is not * wanted, this method has to be overridden in the strategy class that overrides this class. * @param ePackage is the EPackage to save. * @param projectName is the name of the project the EPAckage was generated from. */ public void save(EPackage ePackage, String projectName) { beforeSaving(projectName); ePackage.eClass(); // Initialize the EPackage: ResourceSet resourceSet = new ResourceSetImpl(); // get new resource set Resource resource = null; // create a resource: try { resource = resourceSet.createResource(URI.createFileURI(filePath() + fileName() + ".ecore")); } catch (IllegalArgumentException exception) { exception.printStackTrace(); } resource.getContents().add(ePackage); // add the EPackage as root. try { // save the content: resource.save(Collections.EMPTY_MAP); } catch (IOException exception) { exception.printStackTrace(); } if (saveInProject) { refreshFolder(filePath()); } System.out.println("The extracted metamodel was saved under: " + filePath()); } /** * Refreshes a specific folder in the Eclipse IDE * @param folderPath is the path of the folder. */ private void refreshFolder(String folderPath) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IContainer folder = root.getContainerForLocation(new Path(folderPath)); try { folder.refreshLocal(IResource.DEPTH_INFINITE, null); } catch (CoreException exception) { System.err.println("Could not refresh output folder. Try that manually."); exception.printStackTrace(); } } /** * Can be used to prepare the saving itself. * @param projectName is the name of the project where the metamodel was extracted. */ protected abstract void beforeSaving(String projectName); /** * Determines the path where the ecore file is saved. * @return the file path. */ protected abstract String filePath(); /** * Determines the name of the ecore file. * @return the file name. */ protected abstract String fileName(); }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package eu.socialsensor.trendslabeler; import edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation; import edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation; import edu.stanford.nlp.ling.CoreLabel; import edu.stanford.nlp.ling.HasWord; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import edu.stanford.nlp.process.DocumentPreprocessor; import edu.stanford.nlp.process.PTBTokenizer.PTBTokenizerFactory; import edu.stanford.nlp.util.CoreMap; import eu.socialsensor.documentpivot.preprocessing.StopWords; import eu.socialsensor.framework.client.dao.ItemDAO; import eu.socialsensor.framework.client.dao.DyscoDAO; import eu.socialsensor.framework.client.dao.impl.ItemDAOImpl; import eu.socialsensor.framework.client.dao.impl.DyscoDAOImpl; import eu.socialsensor.framework.common.domain.Item; import eu.socialsensor.framework.common.domain.WebPage; import eu.socialsensor.framework.common.domain.dysco.Dysco; import eu.socialsensor.framework.common.domain.dysco.Entity; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.lang.String; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.Map.Entry; import org.apache.log4j.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringEscapeUtils; import org.htmlparser.Node; import org.htmlparser.Parser; import org.htmlparser.filters.OrFilter; import org.htmlparser.filters.TagNameFilter; import org.htmlparser.util.NodeList; import org.htmlparser.util.ParserException; import org.htmlparser.util.SimpleNodeIterator; import uk.ac.shef.wit.simmetrics.similaritymetrics.AbstractStringMetric; import uk.ac.shef.wit.simmetrics.similaritymetrics.Levenshtein; public class TrendsLabeler { public static final String[] BREAKING_ARRAY = new String[] { "6017542", "5402612","428333","23484039","15108702","18767649","18424289","87416722","384438102", "87416722","7587032","361501426","612473","14138785","15012486","11014272","14569869","354267800", "48833593","807095","7587032", "113050195","15110357","7905122", "16672510","788524","10977192","14138785","138387125","19656220","19536881"}; static{ System.setProperty ("sun.net.client.defaultReadTimeout", "7000"); System.setProperty ("sun.net.client.defaultConnectTimeout", "7000"); } /* public static final String[] BREAKING_ARRAY = new String[] {"BreakingNews", "BBCBreaking","cnnbrk","WSJbreakingnews","ReutersLive","CBSTopNews","AJELive", "SkyNewsBreak","ABCNewsLive","SkyNewsBreak","SkyNews","BreakingNewsUK","BBCNews","TelegraphNews", "CBSNews","ftfinancenews","Channel4News","5_News","24HOfNews","nytimes", "SkyNews","skynewsbiz","ReutersBiz","guardiantech","mediaguardian", "guardiannews","fttechnews","telegraphnews","telegraphsport","telegraphbooks","telefinance" }; */ public static final String titleSeparators="[|-]"; public static final double thresholdMediaName=0.3; public static final Set<String> BREAKING_ACCOUNTS = new HashSet<String>(Arrays.asList(BREAKING_ARRAY)); public static double url_threshold_similarity=0.2; public static void main(String[] args) { DyscoDAO dyscoDAO = new DyscoDAOImpl("social1.atc.gr","dyscos","items","MediaItems"); try{ BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\topicTitlesChanges.txt")); int n_to_process=1; // int n_to_process=dyscoIds.length; String title=null; for(int i=0;i<n_to_process;i++){ Dysco dysco=dyscoDAO.findDysco(dyscoIds[i]); List<Entity> ents=dysco.getEntities(); bw.append(""); bw.append(" bw.append("Dysco ID :\n\t"+dyscoIds[i]); bw.newLine(); bw.append("Old title is: \n\t"+dysco.getTitle()); bw.newLine(); System.out.println(" System.out.println("Old title is: \n"+dysco.getTitle()); String new_title_no_urls=findPopularTitle(dysco); title=new_title_no_urls; String new_title_urls=findPopularTitleCERTHIncludeURLs(dysco); dysco.setTitle(new_title_no_urls); dyscoDAO.updateDysco(dysco); System.out.println("New title (no URLS):\n"+new_title_no_urls); System.out.println("New title (with URLS):\n"+new_title_urls); System.out.println(""); bw.append("New title (no URLS):\n\t"+new_title_no_urls); bw.newLine(); bw.append("New title (with URLS):\n\t"+new_title_urls); bw.newLine(); bw.newLine(); List<Item> items=dysco.getItems(); System.out.println(" for(Item tmp_item:items){ System.out.println(tmp_item.getTitle()); } bw.append("List of tweets: \n"); for(Item tmp_item:items){ bw.append("\t"+tmp_item.getTitle()+"\n"); } bw.newLine(); System.out.println("Entities : "); if(ents!=null){ for(Entity ent:ents) System.out.println(ent.getName()+" "+ent.getType()); } else{ System.out.println("IS NULL"); } bw.append("Entities: \n"); if(ents!=null){ for(Entity ent:ents) bw.append("\t"+ent.getName()+" - "+ent.getType()+"\n"); } else{ bw.append("\tNULL"); } } bw.close(); } catch(Exception e){ e.printStackTrace(); } } static Extractor extr = new Extractor(); private final static Integer MAX_TOKEN_LENGTH = 20; public static double bestJaccard(ArrayList<Set<String>> sentences,Set<String> newSentence){ double best_sim=Double.MIN_VALUE; for(Set<String> next_sentence:sentences){ double sim=Jaccard(next_sentence,newSentence); if(sim>best_sim) best_sim=sim; } return best_sim; } public static double Jaccard(Set<String> terms1,Set<String> terms2){ Set<String> intersection = new HashSet<String>(terms1); intersection.retainAll(terms2); Set<String> union = new HashSet<String>(terms1); union.addAll(terms2); if(union.size()>0) return ((double) intersection.size())/((double) union.size()); else return 0.0; } public static String findPopularTitleCERTHIncludeURLs(Dysco dysco){ List<Item> items=dysco.getItems(); Set<String> entities=new HashSet<String>(); List<Entity> ents=dysco.getEntities(); for(Entity ent:ents) entities.add(ent.getName()); List<String> textItems=new ArrayList<String>(); Map<String,List<String>> perURLitems=new HashMap<String,List<String>>(); ArrayList<Set<String>> cleanedTokens=new ArrayList<Set<String>>(); for(Item item_tmp:items){ List<String> sentences=getSentences1(item_tmp.getTitle(),entities); textItems.addAll(sentences); for(String sentence:sentences){ cleanedTokens.add(tokenizeClean(sentence)); } URL[] tmp_urls=item_tmp.getLinks(); if(tmp_urls!=null){ for(int i=0;i<tmp_urls.length;i++){ String tmp_url_str=tmp_urls[i].toString(); if(!perURLitems.containsKey(tmp_url_str)){ List<String> key_elements=grabKeyElementsFromURL(tmp_url_str); perURLitems.put(tmp_url_str, key_elements); } } } List<WebPage> webpages=item_tmp.getWebPages(); if(webpages!=null){ for(WebPage tmp_webpage:webpages){ String tmp_url_str=tmp_webpage.getUrl(); if(!perURLitems.containsKey(tmp_url_str)){ List<String> key_elements=grabKeyElementsFromURL(tmp_url_str); List<String> new_cands=new ArrayList<String>(); for(String tmp_cand:key_elements){ List<String> tmp_sentences=getSentences1(tmp_cand,entities); new_cands.addAll(tmp_sentences); } perURLitems.put(tmp_url_str, new_cands); } } } } for(List<String> tmp_key_elements:perURLitems.values()){ for(String nextSentence:tmp_key_elements){ Set<String> next_cand=tokenizeClean(nextSentence); double best_similarity=bestJaccard(cleanedTokens,next_cand); if(best_similarity>url_threshold_similarity){ String cleanedSentence=extractor.cleanText(nextSentence); textItems.add(cleanedSentence); } } } String title=findPopularTitleNew(textItems); if(((title==null)||(title.trim().length()==0))&&(textItems.size()>0)){ System.out.println("NULL CASE 1 : "+title+" title=extractor.cleanText(textItems.get(0)); } if(((title==null)||(title.trim().length()==0))&&(textItems.size()>0)){ System.out.println("NULL CASE 2"); title=textItems.get(0); } if(((title==null)||(title.trim().length()==0))&&(items.size()>0)){ System.out.println("NULL CASE 3"); title=items.get(0).getTitle(); } return title; } public static Set<String> tokenizeClean(String sentence){ HashSet<String> tokens=new HashSet<String>(); String cleanedSentence=extractor.cleanText(sentence); String[] parts=cleanedSentence.split("\\s"); for(int i=0;i<parts.length;i++) if(!StopWords.isStopWord(parts[i])) tokens.add(parts[i].toLowerCase()); return tokens; } //THIS IS THE NEWEST VERSION public static String findPopularTitle(Dysco dysco){ List<Item> items=dysco.getItems(); Logger.getRootLogger().info("Title extractor : Examining case 1 (getting title from most popular url)"); //Case 1, there are urls that point to a webpage that has a title // pick the title of the most popular page. Map<String,Integer> url_counts=new HashMap<String,Integer>(); Logger.getRootLogger().info("Title extractor (case 1) : finding most popular URL"); for(Item item_tmp:items){ URL[] tmp_urls=item_tmp.getLinks(); Logger.getRootLogger().info("Title extractor (case 1) : got list of urls will now expand"); if(tmp_urls!=null){ for(int i=0;i<tmp_urls.length;i++){ String resolved=null; Logger.getRootLogger().info("Title extractor (case 1) : will now expand" + tmp_urls[i].toString()); resolved = URLDeshortener.expandFast(tmp_urls[i].toString()); Logger.getRootLogger().info("Title extractor (case 1) : expanded"+tmp_urls[i].toString()); if(resolved!=null){ Integer count=url_counts.get(resolved); if(count == null) url_counts.put(resolved,1); else url_counts.put(resolved,count+1); } } } Logger.getRootLogger().info("Title extractor (case 1) : expanded, will now count"); } Logger.getRootLogger().info("Title extractor (case 1) : found most popular URL"); if (url_counts.size()>0){ int maximum=Integer.MIN_VALUE; String most_popular_url=null; for(Entry<String,Integer> tmp_entry:url_counts.entrySet()){ if(tmp_entry.getValue()>maximum){ maximum=tmp_entry.getValue(); most_popular_url=tmp_entry.getKey(); } } if(most_popular_url!=null){ Logger.getRootLogger().info("Title extractor (case 1) : fetching title from most popular url"); String candidate_title=grabTitleFromURL(most_popular_url); candidate_title=StringEscapeUtils.unescapeHtml(candidate_title); if ((candidate_title!=null)&&(!candidate_title.equals(""))){ String[] parts1=candidate_title.split("\\|"); int max_length=parts1[0].length(); candidate_title=parts1[0]; for(int p=1;p<parts1.length;p++) if(parts1[p].length()>max_length){ max_length=parts1[p].length(); candidate_title=parts1[p]; } Logger.getRootLogger().info("Title extractor (case 1) : cleaning candidate title"); candidate_title=cleanTitleFromCommonMediaNames(candidate_title); Logger.getRootLogger().info("Title extractor (case 1) : getting site name"); String mediaName=getSiteNameFromURL(most_popular_url).toLowerCase(); String[] titleParts=candidate_title.split(titleSeparators); candidate_title=""; AbstractStringMetric metric = new Levenshtein(); for(int i=0;i<titleParts.length;i++){ String next_part=titleParts[i].trim(); float mediaNameSimilarity=metric.getSimilarity(mediaName, next_part.replace(" ", "").toLowerCase()); if(mediaNameSimilarity<thresholdMediaName){ candidate_title=candidate_title+next_part+" "; } } candidate_title=candidate_title.trim(); if ((candidate_title!=null)&&(!candidate_title.equals(""))&&(!candidate_title.toLowerCase().equals("home"))) return candidate_title; } } } Logger.getRootLogger().info("Title extractor : Examining case 2 (message posted by listed user)"); Set<String> entities=new HashSet<String>(); List<Entity> ents=dysco.getEntities(); for(Entity ent:ents) entities.add(ent.getName()); for(Item item_tmp:items){ if(BREAKING_ACCOUNTS.contains(item_tmp.getAuthorScreenName())){ String candidate_title=item_tmp.getTitle(); List<String> parts=getSentences1(candidate_title,entities); candidate_title=""; for(String part:parts) candidate_title=candidate_title+" "+part; candidate_title=candidate_title.trim(); candidate_title=StringEscapeUtils.unescapeHtml(candidate_title); if(candidate_title.endsWith(":")) candidate_title=candidate_title.substring(0,candidate_title.length()-2)+"."; if ((candidate_title!=null)&&(!candidate_title.equals(""))) return candidate_title; } } //Case 3, default certh procedure: finding most popular sentence in all tweets Logger.getRootLogger().info("Title extractor : Examining case 3 (most popular sentence)"); String candidate_title=findPopularTitleCERTH(dysco); candidate_title=StringEscapeUtils.unescapeHtml(candidate_title); if(candidate_title.endsWith(":")) candidate_title=candidate_title.substring(0,candidate_title.length()-1)+"."; return candidate_title; } public static String findPopularTitleCERTH(Dysco dysco){ List<Item> items=dysco.getItems(); List<String> textItems=new ArrayList<String>(); Set<String> entities=new HashSet<String>(); List<Entity> ents=dysco.getEntities(); for(Entity ent:ents) entities.add(ent.getName()); Logger.getRootLogger().info("Title extractor (case 3): Getting candidate sentences"); for(Item item_tmp:items){ List<String> sentences=getSentences1(item_tmp.getTitle(),entities); textItems.addAll(sentences); } Logger.getRootLogger().info("Title extractor (case 3): Finding most popular sentence"); String title=findPopularTitleNew(textItems); if(((title==null)||(title.trim().length()==0))&&(textItems.size()>0)) title=extractor.cleanText(textItems.get(0)); if(((title==null)||(title.trim().length()==0))&&(textItems.size()>0)) title=textItems.get(0); if(((title==null)||(title.trim().length()==0))&&(items.size()>0)) title=items.get(0).getTitle(); return title; } private static String findPopularTitleNew(List<String> textItems) { List<String> titles = textItems; List<String> filteredTitles = getFilteredTitles(titles); if(filteredTitles.size() == 0) { return null; } // List<String> combinations = new ArrayList<String>(); HashMap<String,Integer> combinationsCounts = new HashMap<String,Integer>(); List<String> filteredTitlesFinal = new ArrayList<String>(); for(String title : filteredTitles) { String[] titleTokens = title.trim().split("[\\s]+"); List<String> tokens = Arrays.asList(titleTokens); String str_concat=""; for(String tmp_str:tokens) str_concat=str_concat+tmp_str+" "; str_concat=str_concat.trim(); filteredTitlesFinal.add(str_concat); addCombinationsCounts(str_concat,combinationsCounts); } if(combinationsCounts.size() == 0){ return null; } Map<String, RankedTitle> titlesFrequencies = new HashMap<String, RankedTitle>(); for(Entry<String,Integer> combination : combinationsCounts.entrySet()){ // for(String combination : combinations){ RankedTitle rankTitle = titlesFrequencies.get(combination.getKey()); if (rankTitle == null){ titlesFrequencies.put(combination.getKey(), new RankedTitle(combination.getKey(), combination.getValue())); }else{ rankTitle.setFrequency(rankTitle.getFrequency()+combination.getValue()); } } List<RankedTitle> listOfRankedTitles = new ArrayList<RankedTitle>(); for (Entry<String, RankedTitle> entry2 : titlesFrequencies.entrySet()){ listOfRankedTitles.add(entry2.getValue()); } //candidates and final selection List<String> finalSelectedTitles = getFinalTitles(listOfRankedTitles, filteredTitles.size()); if(finalSelectedTitles.size()>0){ String best_phrase=finalSelectedTitles.get(0); // System.out.println("Best phrase : "+best_phrase); Map<String,Integer> counts=new HashMap<String,Integer>(); for(String tmp_str:textItems){ if((tmp_str.contains(best_phrase.trim()))){ Integer cc=counts.get(tmp_str); if(cc==null) counts.put(tmp_str,1); else counts.put(tmp_str,cc+1); } } String best_sentence=""; int best_count=-1; for(Entry<String,Integer> tmp_entry:counts.entrySet()) if(tmp_entry.getValue()>best_count){ best_count=tmp_entry.getValue(); best_sentence=tmp_entry.getKey(); } best_sentence=extractor.cleanText(best_sentence); return best_sentence; } else { return null; } } public static void addCountsToCounts(HashMap<String,Integer> addIt,HashMap<String,Integer> addTarget){ for(Entry<String,Integer> entry_tmp:addIt.entrySet()){ Integer count_tmp=addTarget.get(entry_tmp.getKey()); if(count_tmp==null) addTarget.put(entry_tmp.getKey(), entry_tmp.getValue()); else addTarget.put(entry_tmp.getKey(), count_tmp+entry_tmp.getValue()); } } private static Extractor extractor = new Extractor(); public static List<String> getClusterTitles(List<String> textItems) { List<String> titles = new ArrayList<String>(); for(String tmp_text : textItems) { String title = extractor.cleanText(tmp_text); titles.add(title); } return titles; } public static List<String> getFilteredTitles(List<String> titles) { List<String> filteredTitles = new ArrayList<String>(); for(String title : titles){ int numberOfLetters = 0; if(title == null){ continue; } for(int i = 0; i < title.length(); i++){ if(Character.isLetter(title.charAt(i))){ numberOfLetters++; } } //more than 4 letters if(numberOfLetters <= 4){ continue; } if(hasHighDigitToletterRatio(title, 0.5)){ continue; } filteredTitles.add(title); } return filteredTitles; } public static List<String> getFinalTitles(List<RankedTitle> listOfRankedTitles, int numberOfPhotos) { for(RankedTitle title : listOfRankedTitles){ int titleLength = title.getTitle().split(" ").length; title.setFrequency(title.getFrequency() * titleLength); } rerankTitlesByNumberOfPhotos(listOfRankedTitles, numberOfPhotos); rerankRedundantSingleTokenTitles(listOfRankedTitles); rerankMaximumTokenLengthWithinATitle(listOfRankedTitles); Collections.sort(listOfRankedTitles, Collections.reverseOrder()); List<RankedTitle> highRankedTokens = filterLowRankTokens(listOfRankedTitles); if(highRankedTokens.size() > 0){ return filterByLevensteinSimilarity(highRankedTokens); }else{ return new ArrayList<String>(); } } public static void rerankMaximumTokenLengthWithinATitle(List<RankedTitle> titles) { for(RankedTitle title : titles){ int maxLength = 0; String[] parts = title.getTitle().split(" "); for(String token : parts){ if(token.length() > maxLength){ maxLength = token.length(); } } if(maxLength < 4){ title.setFrequency(-2); } } } public static List<String> filterByLevensteinSimilarity(List<RankedTitle> tokenTitles) { if(tokenTitles.size() == 0){ throw new IllegalArgumentException("Cannot process an empty list"); } List<String> finalTitles = new ArrayList<String>(); finalTitles.add(tokenTitles.get(0).getTitle()); if(tokenTitles.size() < 2){ return finalTitles; } AbstractStringMetric metric = new Levenshtein(); for(int i = 1; i < tokenTitles.size(); i++){ boolean reject = false; for(String title : finalTitles){ float result = metric.getSimilarity(title, tokenTitles.get(i).getTitle()); if (result >= 0.7){ reject = true; break; } } if(!reject){ finalTitles.add(tokenTitles.get(i).getTitle()); } } return finalTitles; } public static List<RankedTitle> filterLowRankTokens(List<RankedTitle> tokenTitles){ List<RankedTitle> filteredTitles = new ArrayList<RankedTitle>(); for(RankedTitle title : tokenTitles){ if(title.getFrequency() < 0){ continue; } filteredTitles.add(title); } return filteredTitles; } public static void rerankRedundantSingleTokenTitles(List<RankedTitle> tokens) { for(int i = 0; i < tokens.size(); i++){ for(int j = 0; j < tokens.size(); j++){ if(i == j){ continue; } if(tokens.get(i).getTitle().contains(tokens.get(j).getTitle())){ int freq1 = tokens.get(i).getFrequency(); int freq2 = tokens.get(j).getFrequency(); if(freq2 < 3 * freq1){ tokens.get(j).setFrequency(-1); } } } } } public static void rerankTitlesByNumberOfPhotos(List<RankedTitle> listOfRankedTitles, int numberOfPhotos) { int threshold = Math.max( (int) Math.floor((double)numberOfPhotos / (double)8) , 3); for(RankedTitle title : listOfRankedTitles){ if(title.getFrequency() < threshold){ title.setFrequency(0); } } } public static String upperCaseWords(String line) { // line = line.trim().toLowerCase(); String data[] = line.split("\\s"); line = ""; for(int i =0;i< data.length;i++) { if(data[i].length()>1) line = line + data[i].substring(0,1).toUpperCase()+data[i].substring(1)+" "; else line = line + data[i].toUpperCase(); } return line.trim(); } public static void addCombinationsCounts(String sentence,HashMap<String,Integer> combinationsCounts) { String[] parts = sentence.split("\\s"); String nextSentence=""; int length = 2; while( length <= MAX_TOKEN_LENGTH && length <= parts.length ){ for(int i = 0; i < (parts.length - length) + 1 ; i++){ nextSentence=getOneCombination(parts, i, length); Integer count=combinationsCounts.get(nextSentence); if(count==null) combinationsCounts.put(nextSentence, 1); else combinationsCounts.put(nextSentence, count+1); } length++; } } public static String getOneCombination(String[] parts, int start, int length) { StringBuffer buf = new StringBuffer(); for(int i = 0; i < length; i++){ buf.append(parts[start + i] + " "); } return buf.substring(0, buf.length()-1).toString(); } public static List<String> extractTokens(String[] titleTokens, List<Integer> uselessWordsIndexes) { List<String> tokens = new ArrayList<String>(); if(titleTokens.length == 0){ return tokens; } if(uselessWordsIndexes.size() == 0){ tokens.add(extractTitleFromTokens(titleTokens, 0, titleTokens.length-1)); return tokens; } for (int i = 1; i < uselessWordsIndexes.size(); i++){ int index1 = uselessWordsIndexes.get(i-1)+1; int index2 = uselessWordsIndexes.get(i)-1; if (index1 > index2){ continue; } tokens.add(extractTitleFromTokens(titleTokens, index1, index2)); } return tokens; } protected static String extractTitleFromTokens(String[] tokens, int index0, int index1) { if (index0 < 0 || index1 > tokens.length || index1 < index0){ throw new IllegalArgumentException("Inappropriate input arguments: " + index0 + ", " + index1); } StringBuffer buf = new StringBuffer(); for (int i = index0; i < index1; i++){ buf.append(tokens[i] + " "); } buf.append(tokens[index1]); return buf.toString(); } public static List<Integer> findUselessWordsInTitle(String[] titleTokens) { List<Integer> indexes = new ArrayList<Integer>(); indexes.add(-1); for(int i = 0; i < titleTokens.length; i++){ if(!acceptTag(titleTokens[i])){ indexes.add(i); } } indexes.add(titleTokens.length); return indexes; } public static boolean acceptTag(String tag){ if (isNumeric(tag)){ return false; } if(isOneLetterLength(tag)){ return false; } if(containsStrangeCharacterSequences(tag)){ return false; } if(hasMoreNumbersThanLetters(tag)){ return false; } if(isScreenname(tag)) { return false; } return true; } public static boolean isOneLetterLength(String tag) { if(tag.length() > 1){ return false; } return true; } public static boolean isScreenname(String tag) { if(tag.startsWith("@")){ return true; } return false; } public static boolean isNumeric(String tag){ for (int x = 0; x < tag.length(); x++){ if (!Character.isDigit(tag.charAt(x))){ return false; } } return true; } public static boolean containsStrangeCharacterSequences(String tag){ for(int i = 0; i < strangeSequencesIntoTags.length; i++){ if(tag.startsWith(strangeSequencesIntoTags[i])){ return true; } } return false; } private static final String[] strangeSequencesIntoTags = { "img_", "img-", "dmc-", "dmc", "img", "finepix", "dsc", "jpg", "jpeg" }; public static boolean hasMoreNumbersThanLetters(String tag){ int numberOfDigits = 0; int numberOfLetters = 0; for(int i = 0; i < tag.length(); i++){ if(Character.isDigit(tag.charAt(i))){ numberOfDigits++; }else{ numberOfLetters++; } } if(numberOfDigits > numberOfLetters){ return true; } return false; } public static boolean hasHighDigitToletterRatio(String tag, double threshold){ int numberOfDigits = 0; int numberOfLetters = 0; for(int i = 0; i < tag.length(); i++){ if(Character.isDigit(tag.charAt(i))){ numberOfDigits++; }else if (Character.isLetter(tag.charAt(i))){ numberOfLetters++; } } if(numberOfDigits > threshold * numberOfLetters){ return true; } return false; } public static String grabTitleFromURL(String url){ Parser parser; String result=null; try { parser = new Parser(url); // TagNameFilter[] tagNamesFilter = { new TagNameFilter("title"), new TagNameFilter("h1"), new TagNameFilter("h2"), new TagNameFilter("h3") }; TagNameFilter[] tagNamesFilter = { new TagNameFilter("title") }; OrFilter orTagNameFilter = new OrFilter(tagNamesFilter); NodeList list = parser.parse(orTagNameFilter); SimpleNodeIterator nodeElements = list.elements(); Node node; if(nodeElements.hasMoreNodes()){ node = nodeElements.nextNode(); result=node.toPlainTextString().trim(); } } catch (ParserException ex) { } return result; } public static List<String> grabKeyElementsFromURL(String url){ Parser parser; List<String> result=new ArrayList<String>(); try { parser = new Parser(url); // TagNameFilter[] tagNamesFilter = { new TagNameFilter("title"), new TagNameFilter("h1"), new TagNameFilter("h2"), new TagNameFilter("h3") }; TagNameFilter[] tagNamesFilter = { new TagNameFilter("title"), new TagNameFilter("h1"), new TagNameFilter("h2") }; OrFilter orTagNameFilter = new OrFilter(tagNamesFilter); NodeList list = parser.parse(orTagNameFilter); SimpleNodeIterator nodeElements = list.elements(); Node node; while (nodeElements.hasMoreNodes()) { node = nodeElements.nextNode(); result.add(node.toPlainTextString().trim()); } } catch (ParserException ex) { } return result; } public static List<String> getSentences1(String text, Set<String> entities){ text=text.trim(); text=StringEscapeUtils.escapeHtml(text); text=text.replaceAll("http:.*&hellip;\\z",""); String[] toMatch={"\\ART\\s+@\\S+","\\AMT\\s+@\\S+"}; for(String t:toMatch){ Pattern pattern = Pattern.compile(t, Pattern.CASE_INSENSITIVE); String newTweet = text.trim(); text=""; while(!newTweet.equals(text)){ //each loop will cut off one "RT @XXX" or "#XXX"; may need a few calls to cut all hashtags etc. text=newTweet; Matcher matcher = pattern.matcher(text); newTweet = matcher.replaceAll(""); newTweet =newTweet.trim(); } } text=text.replaceAll("-\\s*\\z",""); text=text.replaceAll("&hellip;\\z",""); text=StringEscapeUtils.unescapeHtml(text); text=text.trim(); String[] parts=text.split(Extractor.urlRegExp); List<String> sentences=new ArrayList<String>(); for(int i=0;i<parts.length;i++){
package focusedCrawler.link.frontier; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.Gauge; import com.codahale.metrics.Timer; import com.codahale.metrics.Timer.Context; import focusedCrawler.link.PolitenessScheduler; import focusedCrawler.link.frontier.selector.LinkSelector; import focusedCrawler.util.MetricsManager; import focusedCrawler.util.persistence.TupleIterator; public class CrawlScheduler { private static final Logger logger = LoggerFactory.getLogger(CrawlScheduler.class); private final LinkSelector linkSelector; private final LinkSelector recrawlSelector; private final Frontier frontier; private final PolitenessScheduler scheduler; private final MetricsManager metricsManager; private final int linksToLoad; private boolean hasUncrawledLinks = true; private int availableLinksDuringLoad = -1; private int rejectedLinksDuringLoad = -1; private int uncrawledLinksDuringLoad = -1; private Timer frontierLoadTimer; private AtomicBoolean loadIsRunning = new AtomicBoolean(false); public CrawlScheduler(LinkSelector linkSelector, LinkSelector recrawlSelector, Frontier frontier, MetricsManager metricsManager, int minAccessTime, int linksToLoad) { this.linkSelector = linkSelector; this.recrawlSelector = recrawlSelector; this.frontier = frontier; this.metricsManager = metricsManager; this.linksToLoad = linksToLoad; this.scheduler = new PolitenessScheduler(minAccessTime, linksToLoad); this.setupMetrics(); this.loadQueue(this.linksToLoad); } private void setupMetrics() { Gauge<Integer> numberOfLinksGauge = () -> scheduler.numberOfLinks(); metricsManager.register("frontier_manager.scheduler.number_of_links", numberOfLinksGauge); Gauge<Integer> nonExpiredDomainsGauge = () -> scheduler.numberOfNonExpiredDomains(); metricsManager.register("frontier_manager.scheduler.non_expired_domains", nonExpiredDomainsGauge); Gauge<Integer> emptyDomainsGauge = () -> scheduler.numberOfEmptyDomains(); metricsManager.register("frontier_manager.scheduler.empty_domains", emptyDomainsGauge); Gauge<Integer> availableLinksGauge = () -> availableLinksDuringLoad; metricsManager.register("frontier_manager.last_load.available", availableLinksGauge); Gauge<Integer> rejectedLinksGauge = () -> rejectedLinksDuringLoad; metricsManager.register("frontier_manager.last_load.rejected", rejectedLinksGauge); Gauge<Integer> uncrawledLinksGauge = () -> uncrawledLinksDuringLoad; metricsManager.register("frontier_manager.last_load.uncrawled", uncrawledLinksGauge); frontierLoadTimer = metricsManager.getTimer("frontier_manager.load.time"); } private synchronized void loadQueue(int numberOfLinks) { logger.info("Loading more links from frontier into the scheduler..."); frontier.commit(); Context timerContext = frontierLoadTimer.time(); try (TupleIterator<LinkRelevance> it = frontier.iterator()) { int rejectedLinks = 0; int uncrawledLinks = 0; int linksAvailable = 0; this.startSelection(numberOfLinks); while (it.hasNext()) { try { LinkRelevance link = it.next().getValue(); // Links already downloaded or not relevant if (link.getRelevance() <= 0) { if (recrawlSelector != null) { recrawlSelector.evaluateLink(link); } continue; } uncrawledLinks++; // check whether link can be download now according to politeness constraints if (scheduler.canDownloadNow(link)) { // consider link to be downloaded linkSelector.evaluateLink(link); linksAvailable++; } else { rejectedLinks++; } } catch (Exception e) { // just log the exception and continue the load even when some link fails logger.error("Failed to load link in frontier.", e); } } this.addSelectedLinksToScheduler(recrawlSelector); rejectedLinks += this.addSelectedLinksToScheduler(linkSelector); this.uncrawledLinksDuringLoad = uncrawledLinks; this.rejectedLinksDuringLoad = rejectedLinks; this.availableLinksDuringLoad = linksAvailable; this.hasUncrawledLinks = rejectedLinks != 0 || uncrawledLinks != 0; } catch (Exception e) { logger.error("Failed to read items from the frontier.", e); } finally { timerContext.stop(); } } public void notifyLinkInserted() { this.hasUncrawledLinks = true; } private void startSelection(int numberOfLinks) { if (linkSelector != null) { linkSelector.startSelection(numberOfLinks); } if (recrawlSelector != null) { recrawlSelector.startSelection(numberOfLinks); } } private int addSelectedLinksToScheduler(LinkSelector selector) { int rejectedLinks = 0; int linksAdded = 0; if (selector != null) { List<LinkRelevance> links = selector.getSelectedLinks(); for (LinkRelevance link : links) { if (scheduler.addLink(link)) { linksAdded++; } else { rejectedLinks++; } } logger.info("Loaded {} links.", linksAdded); } return rejectedLinks; } public boolean hasPendingLinks() { return hasUncrawledLinks || recrawlSelector != null || loadIsRunning.get() || scheduler.hasPendingLinks(); } public LinkRelevance nextLink(boolean asyncLoad) { if (!scheduler.hasLinksAvailable()) { maybeLoadQueue(asyncLoad); } return scheduler.nextLink(); } private void maybeLoadQueue(boolean asyncLoad) { if (!hasUncrawledLinks) { return; } if (!asyncLoad) { reload(); return; } if (loadIsRunning.compareAndSet(false, true)) { Thread loaderThread = new Thread(() -> { try { logger.info("Starting scheduler queues reload..."); reload(); } finally { loadIsRunning.set(false); logger.info("Reload done."); } }); loaderThread.setName("FrontierLinkLoader"); loaderThread.start(); } } public void reload() { loadQueue(linksToLoad); } }
package foodtruck.server.dashboard; import java.io.IOException; import java.util.List; import javax.annotation.Nullable; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.repackaged.com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.inject.Inject; import com.google.inject.Singleton; import org.codehaus.jettison.json.JSONArray; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.LocalTime; import org.joda.time.format.DateTimeFormatter; import foodtruck.dao.ConfigurationDAO; import foodtruck.dao.LocationDAO; import foodtruck.dao.TruckDAO; import foodtruck.dao.TruckStopDAO; import foodtruck.geolocation.GeoLocator; import foodtruck.geolocation.GeolocationGranularity; import foodtruck.model.Location; import foodtruck.model.ModelEntity; import foodtruck.model.Truck; import foodtruck.model.TruckStop; import foodtruck.util.Clock; import foodtruck.util.TimeOnlyFormatter; /** * @author aviolette * @since 11/26/12 */ @Singleton public class TruckStopServlet extends HttpServlet { private final TruckStopDAO truckStopDAO; private final TruckDAO truckDAO; private final Clock clock; private final ConfigurationDAO configDAO; private final DateTimeFormatter timeFormatter; private final GeoLocator geolocator; private final LocationDAO locationDAO; @Inject public TruckStopServlet(TruckDAO truckDAO, TruckStopDAO truckStopDAO, Clock clock, ConfigurationDAO configDAO, LocationDAO locationDAO, @TimeOnlyFormatter DateTimeFormatter timeFormatter, GeoLocator geolocator) { this.truckDAO = truckDAO; this.truckStopDAO = truckStopDAO; this.clock = clock; this.configDAO = configDAO; this.timeFormatter = timeFormatter; this.geolocator = geolocator; this.locationDAO = locationDAO; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String truckId = getTruckId(req); String eventId = req.getParameter("event"); Truck truck = truckDAO.findById(truckId); TruckStop truckStop; if (!Strings.isNullOrEmpty(eventId)) { truckStop = truckStopDAO.findById(Long.parseLong(eventId)); // TODO: 404 if null } else { DateTime start = clock.now(); if (start.toLocalTime().isBefore(new LocalTime(11, 30))) { start = start.withTime(11, 30, 0, 0); } DateTime end = start.plusHours(2); truckStop = new TruckStop(truck, start, end, configDAO.find().getCenter(), null, false); } req.setAttribute("nav", "trucks"); req.setAttribute("truckStop", truckStop); List<String> locationNames = ImmutableList.copyOf( Iterables.transform(locationDAO.findAutocompleteLocations(), Location.TO_NAME)); req.setAttribute("locations", new JSONArray(locationNames).toString()); req.getRequestDispatcher("/WEB-INF/jsp/dashboard/event.jsp").forward(req, resp); } private String getTruckId(HttpServletRequest req) { String requestURI = req.getRequestURI(); String truckId = requestURI.substring(14); truckId = truckId.substring(0, truckId.indexOf('/')); return truckId; } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String truckID = getTruckId(req); Truck truck = truckDAO.findById(truckID); DateTime startTime = parseTime(req.getParameter("startTime"), null); DateTime endTime = parseTime(req.getParameter("endTime"), startTime); Location location = geolocator.locate(req.getParameter("location"), GeolocationGranularity.NARROW); long locationId = ModelEntity.UNINITIALIZED; if (req.getParameter("entityId") != null) { locationId = Long.parseLong(req.getParameter("entityId")); } boolean locked = false; TruckStop stop = new TruckStop(truck, startTime, endTime, location, locationId, locked); truckStopDAO.save(stop); resp.sendRedirect("/admin/trucks/" + truckID); } private DateTime parseTime(String time, @Nullable DateTime context) { DateTime dt = timeFormatter.parseDateTime(time.trim().toLowerCase()); DateTimeZone zone = dt.getZone(); DateTime theTime = clock.currentDay().toDateTime(dt.toLocalTime(), zone); if (context == null) { return theTime; } return theTime.isBefore(context) ? theTime.plusDays(1) : theTime; } }
package info.faceland.strife.listeners; import com.tealcube.minecraft.bukkit.facecore.utilities.MessageUtils; import info.faceland.strife.StrifePlugin; import info.faceland.strife.data.champion.Champion; import info.faceland.strife.data.champion.ChampionSaveData; import info.faceland.strife.stats.StrifeStat; import org.bukkit.Bukkit; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.world.ChunkUnloadEvent; public class DataListener implements Listener { private final StrifePlugin plugin; private final static String RESET_MESSAGE = "&a&lYour Levelpoints have been automatically reset due to an update!"; private final static String UNUSED_MESSAGE_1 = "&6&lLevelup! You have &f&l{0} &6&lunused Levelpoints!"; private final static String UNUSED_MESSAGE_2 = "&6&lOpen your inventory or use &f&l/levelup &6&lto spend them!"; public DataListener(StrifePlugin plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.LOWEST) public void onPlayerJoinChampionStuff(final PlayerJoinEvent event) { ChampionSaveData championSaveData; if (!plugin.getChampionManager().championExists(event.getPlayer().getUniqueId())) { championSaveData = plugin.getStorage().load(event.getPlayer().getUniqueId()); if (getChampionLevelpoints(championSaveData) != event.getPlayer().getLevel()) { notifyResetPoints(event.getPlayer()); for (StrifeStat stat : plugin.getStatManager().getStats()) { championSaveData.setLevel(stat, 0); } championSaveData.setHighestReachedLevel(event.getPlayer().getLevel()); championSaveData.setUnusedStatPoints(event.getPlayer().getLevel()); } } else { championSaveData = plugin.getChampionManager().getChampion(event.getPlayer()).getSaveData(); } Champion champion = new Champion(event.getPlayer(), championSaveData); plugin.getChampionManager().addChampion(champion); if (champion.getUnusedStatPoints() > 0) { notifyUnusedPoints(event.getPlayer(), champion.getUnusedStatPoints()); } } @EventHandler(priority = EventPriority.MONITOR) public void onPlayerJoinUpdateAttributes(final PlayerJoinEvent event) { event.getPlayer().setHealthScaled(false); plugin.getAttributeUpdateManager().updateAttributes(event.getPlayer()); } @EventHandler(priority = EventPriority.MONITOR) public void onEntityDeath(final EntityDeathEvent event) { plugin.getBossBarManager().doBarDeath(event.getEntity()); plugin.getUniqueEntityManager().removeEntity(event.getEntity(), false, true); plugin.getBarrierManager().removeEntity(event.getEntity()); } @EventHandler(priority = EventPriority.MONITOR) public void onPlayerQuit(final PlayerQuitEvent event) { plugin.getBossBarManager().removeBar(event.getPlayer().getUniqueId()); } @EventHandler(priority = EventPriority.MONITOR) public void onPlayerKick(final PlayerKickEvent event) { plugin.getBossBarManager().removeBar(event.getPlayer().getUniqueId()); } @EventHandler(priority = EventPriority.LOWEST) public void onPlayerRespawn(final PlayerRespawnEvent event) { plugin.getBossBarManager().removeBar(event.getPlayer().getUniqueId()); plugin.getBarrierManager() .createBarrierEntry(plugin.getAttributedEntityManager().getAttributedEntity(event.getPlayer())); } @EventHandler(priority = EventPriority.LOWEST) public void onInteract(final PlayerInteractEntityEvent event) { if (event.getRightClicked() == null) { return; } if (!(event.getRightClicked() instanceof LivingEntity) || event .getRightClicked() instanceof ArmorStand) { return; } if (!event.getRightClicked().isValid() || event.getRightClicked().hasMetadata("NPC")) { return; } final Player player = event.getPlayer(); final LivingEntity entity = (LivingEntity) event.getRightClicked(); plugin.getAttributedEntityManager().getAttributedEntity(entity); plugin.getBossBarManager() .pushBar(player, plugin.getAttributedEntityManager().getAttributedEntity(entity)); } @EventHandler(priority = EventPriority.NORMAL) public void onChunkUnload(ChunkUnloadEvent e) { for (Entity ent : e.getChunk().getEntities()) { if (!(ent instanceof LivingEntity)) { continue; } if (plugin.getUniqueEntityManager().getLiveUniquesMap().containsKey(ent)) { plugin.getUniqueEntityManager().removeEntity((LivingEntity) ent, true, false); ent.remove(); } } } private void notifyUnusedPoints(final Player player, final int unused) { Bukkit.getScheduler().runTaskLater(plugin, () -> { MessageUtils.sendMessage(player, UNUSED_MESSAGE_1.replace("{0}", String.valueOf(unused))); MessageUtils.sendMessage(player, UNUSED_MESSAGE_2); }, 20L * 5); } private void notifyResetPoints(final Player player) { Bukkit.getScheduler().runTaskLater(plugin, () -> MessageUtils.sendMessage(player, RESET_MESSAGE), 20L * 3); } private int getChampionLevelpoints(ChampionSaveData championSaveData) { int total = championSaveData.getUnusedStatPoints(); for (StrifeStat stat : championSaveData.getLevelMap().keySet()) { total += championSaveData.getLevel(stat); } return total; } }
package info.u_team.u_team_core.data; import java.util.function.*; import net.minecraft.data.*; import net.minecraftforge.common.data.ExistingFileHelper; import net.minecraftforge.fml.event.lifecycle.GatherDataEvent; public class GenerationData { private final String modid; private final DataGenerator generator; private final ExistingFileHelper existingFileHelper; private CommonBlockTagsProvider blockTagsProvider; public GenerationData(String modid, GatherDataEvent event) { this(modid, event.getGenerator(), new ExistingFileHelperWithForge(event.getExistingFileHelper())); } public GenerationData(String modid, DataGenerator generator, ExistingFileHelper existingFileHelper) { this.modid = modid; this.generator = generator; this.existingFileHelper = existingFileHelper; } public String getModid() { return modid; } public DataGenerator getGenerator() { return generator; } public ExistingFileHelper getExistingFileHelper() { return existingFileHelper; } public void addProvider(Function<GenerationData, IDataProvider> function) { final IDataProvider provider = function.apply(this); if (provider instanceof CommonBlockTagsProvider) { blockTagsProvider = (CommonBlockTagsProvider) provider; } generator.addProvider(provider); } public void addProvider(BiFunction<GenerationData, CommonBlockTagsProvider, IDataProvider> function) { generator.addProvider(function.apply(this, blockTagsProvider)); } }
package innovimax.mixthem.io; import java.io.IOException; import java.util.ArrayList; //import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.stream.IntStream; public class MultiChannelCharReader implements IMultiChannelCharInput { private final List<ICharInput> readers = new ArrayList<ICharInput>(); /** * Constructor * @param inputs The list of inputs as InputResource * @param selection The input index selection (maybe empty) * @see innovimax.mixthem.io.InputResource */ public MultiChannelCharReader(final List<InputResource> inputs, final Set<Integer> selection) { IntStream.rangeClosed(1, inputs.size()) .filter(index -> selection.isEmpty() || selection.contains(Integer.valueOf(index))) .mapToObj(index -> inputs.get(index-1)) .forEachOrdered(input -> { try { this.readers.add(new DefaultCharReader(input)); } catch (IOException e) { throw new RuntimeException(e); } }); } @Override public boolean hasCharacter() throws IOException { return this.readers.stream() .anyMatch(reader -> { try { return reader.hasCharacter(); } catch (IOException e) { throw new RuntimeException(e); } }); } @Override public int[] nextCharacterRange() throws IOException { /*final int[] chars = new int[this.readers.size()]; IntStream.range(0, readers.size()) .forEachOrdered(index -> { try { chars[index] = readers.get(index).nextCharacter(); } catch (IOException e) { throw new RuntimeException(e); } }); return chars;*/ return readers.stream() .mapToInt(reader -> { try { return reader.nextCharacter(); } catch (IOException e) { throw new RuntimeException(e); } }) .toArray(); } @Override public void close() throws IOException { this.readers.forEach(reader -> { try { reader.close(); } catch (IOException e) { throw new RuntimeException(e); } }); } }
package io.github.mzmine.util.files; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import javafx.stage.FileChooser.ExtensionFilter; import org.apache.commons.io.FilenameUtils; /** * Simple file operations * * @author Robin Schmid (robinschmid@uni-muenster.de) */ public class FileAndPathUtil { /** * Returns the real file path as path/filename.fileformat * * @param name * @param format a format starting with a dot for example: .pdf ; or without a dot: pdf * @return */ public static File getRealFilePath(File path, String name, String format) { return new File(getFolderOfFile(path), getRealFileName(name, format)); } /** * Returns the real file path as path/filename.fileformat * * @param format a format starting with a dot for example: .pdf ; or without a dot: pdf * @return * @throws Exception if there is no filname (selected path = folder) */ public static File getRealFilePath(File filepath, String format) { return new File(filepath.getParentFile(), getRealFileName(filepath.getName(), format)); } /** * Returns the real file name as filename.fileformat * * @param name * @param format a format starting with a dot for example .pdf * @return */ public static String getRealFileName(String name, String format) { String result = FilenameUtils.removeExtension(name); result = addFormat(result, format); return result; } /** * Returns the real file name as filename.fileformat * * @param name * @param format a format starting with a dot for example .pdf * @return */ public static String getRealFileName(File name, String format) { return getRealFileName(name.getAbsolutePath(), format); } /** * @param f * @return The file extension or null. */ public static String getExtension(File f) { int lastDot = f.getName().lastIndexOf("."); if (lastDot != -1) { return f.getName().substring(lastDot + 1); } return null; } /** * erases the format. "image.png" will be returned as "image" this method is used by * getRealFilePath and getRealFileName * * @return */ public static File eraseFormat(File f) { int lastDot = f.getName().lastIndexOf("."); if (lastDot != -1) { return new File(f.getParent(), f.getName().substring(0, lastDot)); } else { return f; } } /** * Adds the format. "image" will be returned as "image.format" Maybe use erase format first. this * method is used by getRealFilePath and getRealFileName * * @param name * @param format * @return */ public static String addFormat(String name, String format) { if (format.startsWith(".")) { return name + format; } else { return name + "." + format; } } /** * Returns the file if it is already a folder. Or the parent folder if the file is a data file * * @param file * @return */ public static File getFolderOfFile(File file) { if (!isOnlyAFolder(file)) { return file.getParentFile(); } else { return file; } } /** * Returns the file name from a given file. If file is a folder an empty String is returned * * @param file * @return */ public static String getFileNameFromPath(File file) { if (!isOnlyAFolder(file)) { return file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf("\\") + 1); } else { return ""; } } /** * Returns the file name from a given file. If the file is a folder an empty String is returned * * @param file * @return */ public static String getFileNameFromPath(String file) { return getFileNameFromPath(new File(file)); } /** * Checks if a given File is a folder or a data file */ public static boolean isOnlyAFolder(File file) { return file.isDirectory(); } /** * Creates a new directory. * * @param theDir * @return false if directory was not created */ public static boolean createDirectory(File theDir) { // if the directory does not exist, create it if (!theDir.exists()) { boolean result = false; try { theDir.mkdirs(); result = true; } catch (SecurityException se) { // handle it } return result; } else { return true; } } /** * Sort an array of files These files have to start or end with a number * * @param files * @return */ public static File[] sortFilesByNumber(File[] files) { Arrays.sort(files, new Comparator<File>() { private Boolean endsWithNumber = null; @Override public int compare(File o1, File o2) { try { if (endsWithNumber == null) { checkEndsWithNumber(o1.getName()); } int n1 = extractNumber(o1.getName()); int n2 = extractNumber(o2.getName()); return n1 - n2; } catch (Exception e) { return o1.compareTo(o2); } } private int extractNumber(String name) throws Exception { int i = 0; try { if (endsWithNumber) { // ends with number? int e = name.lastIndexOf('.'); e = e == -1 ? name.length() : e; int f = e - 1; for (; f > 0; f if (!isNumber(name.charAt(f))) { f++; break; } } if (f < 0) { f = 0; } String number = name.substring(f, e); i = Integer.parseInt(number); } else { int f = 0; for (; f < name.length(); f++) { if (!isNumber(name.charAt(f))) { break; } } String number = name.substring(0, f); i = Integer.parseInt(number); } } catch (Exception e) { i = 0; // if filename does not match the format throw e; // then default to 0 } return i; } private void checkEndsWithNumber(String name) { // ends with number? int e = name.lastIndexOf('.'); e = e == -1 ? name.length() : e; endsWithNumber = isNumber(name.charAt(e - 1)); } }); return files; } private static boolean isNumber(char c) { return (c >= '0' && c <= '9'); } /** * Lists all directories in directory f * * @param f * @return */ public static File[] getSubDirectories(File f) { return f.listFiles(new FilenameFilter() { @Override public boolean accept(File current, String name) { return new File(current, name).isDirectory(); } }); } // // search for files public static List<File[]> findFilesInDir(File dir, ExtensionFilter fileFilter) { String ext = fileFilter.getExtensions().get(0); if (ext.startsWith("*.")) { ext = ext.substring(2); } return findFilesInDir(dir, new FileNameExtFilter("", ext), true, false); } public static List<File[]> findFilesInDir(File dir, ExtensionFilter fileFilter, boolean searchSubdir) { String ext = fileFilter.getExtensions().get(0); if (ext.startsWith("*.")) { ext = ext.substring(2); } return findFilesInDir(dir, new FileNameExtFilter("", ext), searchSubdir, false); } /** * @param dir * @param fileFilter * @return */ public static List<File[]> findFilesInDir(File dir, FileNameExtFilter fileFilter) { return findFilesInDir(dir, fileFilter, true, false); } public static List<File[]> findFilesInDir(File dir, FileNameExtFilter fileFilter, boolean searchSubdir) { return findFilesInDir(dir, fileFilter, searchSubdir, false); } public static List<File[]> findFilesInDir(File dir, FileNameExtFilter fileFilter, boolean searchSubdir, boolean filesInSeparateFolders) { File[] subDir = FileAndPathUtil.getSubDirectories(dir); // result: each vector element stands for one img ArrayList<File[]> list = new ArrayList<File[]>(); // add all files as first image // sort all files and return them File[] files = dir.listFiles(fileFilter); files = FileAndPathUtil.sortFilesByNumber(files); if (files != null && files.length > 0) { list.add(files); } if (subDir == null || subDir.length <= 0 || !searchSubdir) { // no subdir end directly return list; } else { // sort dirs subDir = FileAndPathUtil.sortFilesByNumber(subDir); // go in all sub and subsub... folders to find files if (filesInSeparateFolders) { findFilesInSubDirSeparatedFolders(dir, subDir, list, fileFilter); } else { findFilesInSubDir(subDir, list, fileFilter); } // return as array (unsorted because they are sorted folder wise) return list; } } /** * go into all subfolders and find all files and go in further subfolders files stored in separate * folders. one line in one folder * * @param dirs musst be sorted! * @param list * @return */ private static void findFilesInSubDirSeparatedFolders(File parent, File[] dirs, ArrayList<File[]> list, FileNameExtFilter fileFilter) { // go into folder and find files ArrayList<File> img = null; // each file in one folder for (int i = 0; i < dirs.length; i++) { // find all suiting files File[] subFiles = FileAndPathUtil.sortFilesByNumber(dirs[i].listFiles(fileFilter)); // if there are some suiting files in here directory has been found! // create image of these // dirs if (subFiles.length > 0) { if (img == null) { img = new ArrayList<File>(); } // put them into the list for (int f = 0; f < subFiles.length; f++) { img.add(subFiles[f]); } } else { // search in subfolders for data // find all subfolders, sort them and do the same iterative File[] subDir = FileAndPathUtil.sortFilesByNumber(FileAndPathUtil.getSubDirectories(dirs[i])); // call this method findFilesInSubDirSeparatedFolders(dirs[i], subDir, list, fileFilter); } } // add to list if (img != null && img.size() > 0) { list.add(img.toArray(new File[img.size()])); } } /** * Go into all sub-folders and find all files files stored one image in one folder! * * @param dirs musst be sorted! * @param list * @return */ private static void findFilesInSubDir(File[] dirs, ArrayList<File[]> list, FileNameExtFilter fileFilter) { // All files in one folder for (int i = 0; i < dirs.length; i++) { // find all suiting files File[] subFiles = FileAndPathUtil.sortFilesByNumber(dirs[i].listFiles(fileFilter)); // put them into the list if (subFiles != null && subFiles.length > 0) { list.add(subFiles); } // find all subfolders, sort them and do the same iterative File[] subDir = FileAndPathUtil.sortFilesByNumber(FileAndPathUtil.getSubDirectories(dirs[i])); // call this method findFilesInSubDir(subDir, list, fileFilter); } } /** * The Path of the Jar. * * @return */ public static File getPathOfJar() { /* * File f = new File(System.getProperty("java.class.path")); File dir = * f.getAbsoluteFile().getParentFile(); return dir; */ try { File jar = new File(FileAndPathUtil.class.getProtectionDomain().getCodeSource().getLocation() .toURI().getPath()); return jar.getParentFile(); } catch (Exception ex) { return new File(""); } } public static File getUniqueFilename(final File parent, final String fileName) { final File dir = parent.isDirectory() ? parent : parent.getParentFile(); final File file = new File(dir + File.separator + fileName); if (!file.exists()) { return file; } final String extension = getExtension(file); final File noExtension = eraseFormat(file); int i = 1; File uniqueFile = new File( noExtension.getAbsolutePath() + "(" + i + ")." + extension); while (uniqueFile.exists()) { i++; uniqueFile = new File( noExtension.getAbsolutePath() + "(" + i + ")." + extension); } return uniqueFile; } /** * Remove all symbols not allowed in path. Replaces with _ * * @param name source name (filename or path) * @return path safe string */ public static String safePathEncode(String name) { return safePathEncode(name, "_"); } /** * Remove all symbols not allowed in path * * @param name source name (filename or path) * @param replaceStr replace all restricted characters by this str * @return path safe string */ public static String safePathEncode(String name, String replaceStr) { return name.replaceAll("[^a-zA-Z0-9-_()\\.\\s]", replaceStr); } }
package lemming.context.inbound; import lemming.context.BaseContext; import lemming.context.Context; import org.apache.wicket.extensions.markup.html.repeater.tree.ITreeProvider; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import java.util.*; /** * A tree provider for contexts. */ public class ContextTreeProvider implements ITreeProvider<BaseContext> { /** * List of contexts. */ private List<Context> contexts; /** * A map of contexts. */ private MultivaluedMap<Context, InboundContext> map; /** * Creates a tree provider for contexts. * * @param matchingTriples matching triples */ public ContextTreeProvider(List<Triple> matchingTriples, List<Context> contextsWithoutComplement) { this.contexts = new ArrayList<>(); map = new MultivaluedHashMap<>(); applyTriples(matchingTriples); applyContexts(contextsWithoutComplement); } /** * Applies contexts of triples to a map of contexts. * * @param triples list of triples */ private void applyTriples(List<Triple> triples) { for (Triple triple : triples) { contexts.add(triple.getContext()); map.putSingle(triple.getContext(), triple.getInboundContext()); } contexts.sort(new ContextComparator()); } /** * Applies contexts to list of contexts. * * @param contexts list of contexts */ private void applyContexts(List<Context> contexts) { this.contexts.addAll(contexts); this.contexts.sort(new ContextComparator()); } /** * Returns the roots of the tree. * * @return An iterator for the roots of a tree. */ @Override public Iterator<? extends BaseContext> getRoots() { return contexts.iterator(); } /** * Checks if the given context has children. * * @param context a context * @return True if a triple for the given context exists. */ @Override public boolean hasChildren(BaseContext context) { if (context instanceof Context) { return map.containsKey(context); } return false; } /** * Returns an iterator for the children of a context. * * @param context a context * @return An iterator for the children of a context. */ @Override public Iterator<? extends BaseContext> getChildren(BaseContext context) { List<BaseContext> children = new ArrayList<>(); if (context instanceof Context && hasChildren(context)) { children.addAll(map.get(context)); } children.sort(new ContextComparator()); return children.iterator(); } /** * Wraps objects inside a model. * * @param context a context object. * @return A context model. */ @Override public IModel<BaseContext> model(BaseContext context) { return Model.of(context); } /** * Detaches model after use. */ @Override public void detach() { // nothing to do } /** * Adds an inbound context to a context. * * @param context a context * @param inboundContext an inbound context * @return A merged inbound context. */ public InboundContext add(Context context, InboundContext inboundContext) { InboundContextDao inboundContextDao = new InboundContextDao(); inboundContext = inboundContextDao.refresh(inboundContext); inboundContext.setInherit(Boolean.TRUE); inboundContext = inboundContextDao.merge(inboundContext); map.add(context, inboundContext); return inboundContext; } /** * Removes an inbound context from a context. * * @param inboundContext an inbound context * @return A merged inbound context. */ public InboundContext remove(InboundContext inboundContext) { InboundContextDao inboundContextDao = new InboundContextDao(); for (Map.Entry<Context, List<InboundContext>> entry : map.entrySet()) { Context context = entry.getKey(); List<InboundContext> inboundContexts = entry.getValue(); if (inboundContexts.contains(inboundContext)) { inboundContexts.remove(inboundContext); if (inboundContexts.isEmpty()) { map.remove(context); } break; } } inboundContext = inboundContextDao.refresh(inboundContext); inboundContext.setInherit(Boolean.FALSE); return inboundContextDao.merge(inboundContext); } /** * A comparator for contexts. */ private class ContextComparator implements Comparator<BaseContext> { /** * Compares two contexts. * * @param context1 context 1 * @param context2 context 2 * @return A negative or a positive number. */ @Override public int compare(BaseContext context1, BaseContext context2) { if (context1.getNumber() < context2.getNumber()) { return -1; } else if (context1.getNumber() > context2.getNumber()) { return 1; } else { throw new IllegalArgumentException(); } } } }
package main.java.com.bag.server; import bftsmart.reconfiguration.util.RSAKeyLoader; import bftsmart.tom.MessageContext; import bftsmart.tom.ServiceProxy; import bftsmart.tom.core.messages.TOMMessageType; import bftsmart.tom.util.TOMUtil; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.pool.KryoPool; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import main.java.com.bag.operations.IOperation; import main.java.com.bag.util.Constants; import main.java.com.bag.util.Log; import main.java.com.bag.util.storage.NodeStorage; import main.java.com.bag.util.storage.RelationshipStorage; import main.java.com.bag.util.storage.SignatureStorage; import org.jetbrains.annotations.NotNull; import java.security.PublicKey; import java.util.*; /** * Class handling server communication in the global cluster. */ public class GlobalClusterSlave extends AbstractRecoverable { /** * Name of the location of the global config. */ private static final String GLOBAL_CONFIG_LOCATION = "global/config"; /** * The wrapper class instance. Used to access the global cluster if possible. */ private final ServerWrapper wrapper; /** * The id of the local cluster. */ private final int id; /** * The id of the internal client used in this server */ private final int idClient; /** * Cache which holds the signatureStorages for the consistency. */ private final Cache<Long, SignatureStorage> signatureStorageCache = Caffeine.newBuilder().build(); /** * The serviceProxy to establish communication with the other replicas. */ private final ServiceProxy proxy; GlobalClusterSlave(final int id, @NotNull final ServerWrapper wrapper, final ServerInstrumentation instrumentation) { super(id, GLOBAL_CONFIG_LOCATION, wrapper, instrumentation); this.id = id; this.idClient = id + 1000; this.wrapper = wrapper; Log.getLogger().info("Turning on client proxy with id:" + idClient); this.proxy = new ServiceProxy(this.idClient, GLOBAL_CONFIG_LOCATION); Log.getLogger().info("Turned on global cluster with id:" + id); } private byte[] makeEmptyAbortResult() { final Output output = new Output(0, 128); final KryoPool pool = new KryoPool.Builder(super.getFactory()).softReferences().build(); final Kryo kryo = pool.borrow(); kryo.writeObject(output, Constants.ABORT); byte[] temp = output.getBuffer(); output.close(); pool.release(kryo); return temp; } /** * Every byte array is one request. * * @param bytes the requests. * @param messageContexts the contexts. * @return the answers of all requests in this batch. */ @Override public byte[][] appExecuteBatch(final byte[][] bytes, final MessageContext[] messageContexts) { byte[][] allResults = new byte[bytes.length][]; for (int i = 0; i < bytes.length; ++i) { if (messageContexts != null && messageContexts[i] != null) { KryoPool pool = new KryoPool.Builder(super.getFactory()).softReferences().build(); Kryo kryo = pool.borrow(); Input input = new Input(bytes[i]); String type = kryo.readObject(input, String.class); if (Constants.COMMIT_MESSAGE.equals(type)) { final Long timeStamp = kryo.readObject(input, Long.class); byte[] result = executeCommit(kryo, input, timeStamp); pool.release(kryo); allResults[i] = result; } else { Log.getLogger().error("Return empty bytes for message type: " + type); allResults[i] = makeEmptyAbortResult(); updateCounts(0, 0, 0, 1); } } else { Log.getLogger().error("Received message with empty context!"); allResults[i] = makeEmptyAbortResult(); updateCounts(0, 0, 0, 1); } } return allResults; } @Override void readSpecificData(final Input input, final Kryo kryo) { final int length = kryo.readObject(input, Integer.class); for (int i = 0; i < length; i++) { try { signatureStorageCache.put(kryo.readObject(input, Long.class), kryo.readObject(input, SignatureStorage.class)); } catch (ClassCastException ex) { Log.getLogger().warn("Unable to restore signatureStoreMap entry: " + i + " at server: " + id, ex); } } } @Override public Output writeSpecificData(final Output output, final Kryo kryo) { if (signatureStorageCache == null) { return output; } Log.getLogger().warn("Size at global: " + signatureStorageCache.estimatedSize()); final Map<Long, SignatureStorage> copy = signatureStorageCache.asMap(); kryo.writeObject(output, copy.size()); for (final Map.Entry<Long, SignatureStorage> entrySet : copy.entrySet()) { kryo.writeObject(output, entrySet.getKey()); kryo.writeObject(output, entrySet.getValue()); } return output; } /** * Check for conflicts and unpack things for conflict handle check. * * @param kryo the kryo instance. * @param input the input. * @return the response. */ private synchronized byte[] executeCommit(final Kryo kryo, final Input input, final long timeStamp) { Log.getLogger().info("Execute commit"); //Read the inputStream. final List readsSetNodeX = kryo.readObject(input, ArrayList.class); final List readsSetRelationshipX = kryo.readObject(input, ArrayList.class); final List writeSetX = kryo.readObject(input, ArrayList.class); //Create placeHolders. ArrayList<NodeStorage> readSetNode; ArrayList<RelationshipStorage> readsSetRelationship; ArrayList<IOperation> localWriteSet; input.close(); Output output = new Output(128); kryo.writeObject(output, Constants.COMMIT_RESPONSE); try { readSetNode = (ArrayList<NodeStorage>) readsSetNodeX; readsSetRelationship = (ArrayList<RelationshipStorage>) readsSetRelationshipX; localWriteSet = (ArrayList<IOperation>) writeSetX; } catch (Exception e) { Log.getLogger().warn("Couldn't convert received data to sets. Returning abort", e); kryo.writeObject(output, Constants.ABORT); kryo.writeObject(output, getGlobalSnapshotId()); //Send abort to client and abort byte[] returnBytes = output.getBuffer(); output.close(); return returnBytes; } if (!ConflictHandler.checkForConflict(super.getGlobalWriteSet(), super.getLatestWritesSet(), new ArrayList<>(localWriteSet), readSetNode, readsSetRelationship, timeStamp, wrapper.getDataBaseAccess())) { updateCounts(0, 0, 0, 1); Log.getLogger() .info("Found conflict, returning abort with timestamp: " + timeStamp + " globalSnapshot at: " + getGlobalSnapshotId() + " and writes: " + localWriteSet.size() + " and reads: " + readSetNode.size() + " + " + readsSetRelationship.size()); kryo.writeObject(output, Constants.ABORT); kryo.writeObject(output, getGlobalSnapshotId()); if (!localWriteSet.isEmpty()) { Log.getLogger().warn("Aborting of: " + getGlobalSnapshotId() + " localId: " + timeStamp); } //Send abort to client and abort byte[] returnBytes = output.getBuffer(); output.close(); return returnBytes; } if (!localWriteSet.isEmpty()) { super.executeCommit(localWriteSet); if (wrapper.getLocalCLuster() != null) { signCommitWithDecisionAndDistribute(localWriteSet, Constants.COMMIT, getGlobalSnapshotId(), kryo); } } else { updateCounts(0, 0, 1, 0); } kryo.writeObject(output, Constants.COMMIT); kryo.writeObject(output, getGlobalSnapshotId()); byte[] returnBytes = output.getBuffer(); output.close(); Log.getLogger().info("No conflict found, returning commit with snapShot id: " + getGlobalSnapshotId() + " size: " + returnBytes.length); return returnBytes; } /** * Check for conflicts and unpack things for conflict handle check. * * @param kryo the kryo instance. * @param input the input. * @return the response. */ private byte[] executeReadOnlyCommit(final Kryo kryo, final Input input, final long timeStamp) { //Read the inputStream. final List readsSetNodeX = kryo.readObject(input, ArrayList.class); final List readsSetRelationshipX = kryo.readObject(input, ArrayList.class); final List writeSetX = kryo.readObject(input, ArrayList.class); //Create placeHolders. ArrayList<NodeStorage> readSetNode; ArrayList<RelationshipStorage> readsSetRelationship; ArrayList<IOperation> localWriteSet; input.close(); Output output = new Output(128); kryo.writeObject(output, Constants.COMMIT_RESPONSE); try { readSetNode = (ArrayList<NodeStorage>) readsSetNodeX; readsSetRelationship = (ArrayList<RelationshipStorage>) readsSetRelationshipX; localWriteSet = (ArrayList<IOperation>) writeSetX; } catch (Exception e) { Log.getLogger().warn("Couldn't convert received data to sets. Returning abort", e); kryo.writeObject(output, Constants.ABORT); kryo.writeObject(output, getGlobalSnapshotId()); //Send abort to client and abort byte[] returnBytes = output.getBuffer(); output.close(); return returnBytes; } if (!ConflictHandler.checkForConflict(super.getGlobalWriteSet(), super.getLatestWritesSet(), localWriteSet, readSetNode, readsSetRelationship, timeStamp, wrapper.getDataBaseAccess())) { updateCounts(0, 0, 0, 1); Log.getLogger() .info("Found conflict, returning abort with timestamp: " + timeStamp + " globalSnapshot at: " + getGlobalSnapshotId() + " and writes: " + localWriteSet.size() + " and reads: " + readSetNode.size() + " + " + readsSetRelationship.size()); kryo.writeObject(output, Constants.ABORT); kryo.writeObject(output, getGlobalSnapshotId()); //Send abort to client and abort byte[] returnBytes = output.getBuffer(); output.close(); return returnBytes; } updateCounts(0, 0, 1, 0); kryo.writeObject(output, Constants.COMMIT); kryo.writeObject(output, getGlobalSnapshotId()); byte[] returnBytes = output.getBuffer(); output.close(); Log.getLogger().info("No conflict found, returning commit with snapShot id: " + getGlobalSnapshotId() + " size: " + returnBytes.length); return returnBytes; } private class SignatureThread extends Thread { final List<IOperation> localWriteSet; final String commit; final long globalSnapshotId; final Kryo kryo; private SignatureThread(final List<IOperation> localWriteSet, final String commit, final long globalSnapshotId, final Kryo kryo) { this.localWriteSet = localWriteSet; this.commit = commit; this.globalSnapshotId = globalSnapshotId; this.kryo = kryo; } @Override public void run() { signCommitWithDecisionAndDistribute(localWriteSet, Constants.COMMIT, getGlobalSnapshotId(), kryo); } } private void signCommitWithDecisionAndDistribute(final List<IOperation> localWriteSet, final String decision, final long snapShotId, final Kryo kryo) { Log.getLogger().info("Sending signed commit to the other global replicas"); final RSAKeyLoader rsaLoader = new RSAKeyLoader(this.idClient, GLOBAL_CONFIG_LOCATION, false); //Todo probably will need a bigger buffer in the future. size depending on the set size? final Output output = new Output(0, 100240); kryo.writeObject(output, Constants.SIGNATURE_MESSAGE); kryo.writeObject(output, decision); kryo.writeObject(output, snapShotId); kryo.writeObject(output, localWriteSet); final byte[] message = output.toBytes(); final byte[] signature; try { signature = TOMUtil.signMessage(rsaLoader.loadPrivateKey(), message); } catch (Exception e) { Log.getLogger().warn("Unable to sign message at server " + id, e); return; } final SignatureStorage signatureStorage; if (signatureStorageCache.getIfPresent(getGlobalSnapshotId()) != null) { signatureStorage = signatureStorageCache.getIfPresent(getGlobalSnapshotId()); if (signatureStorage.getMessage().length != output.toBytes().length) { Log.getLogger().error("Message in signatureStorage: " + signatureStorage.getMessage().length + " message of committing server: " + message.length); } } else { Log.getLogger().info("Size of message stored is: " + message.length); signatureStorage = new SignatureStorage(super.getReplica().getReplicaContext().getStaticConfiguration().getN() - 1, message, decision); signatureStorageCache.put(snapShotId, signatureStorage); } signatureStorage.setProcessed(); Log.getLogger().info("Set processed by global cluster: " + snapShotId + " by: " + idClient); signatureStorage.addSignatures(idClient, signature); if (signatureStorage.hasEnough()) { Log.getLogger().info("Sending update to slave signed by all members: " + snapShotId); updateSlave(signatureStorage); signatureStorage.setDistributed(); if (signatureStorage.hasAll()) { signatureStorageCache.invalidate(snapShotId); } } else { signatureStorageCache.put(snapShotId, signatureStorage); } kryo.writeObject(output, message.length); kryo.writeObject(output, signature.length); output.writeBytes(signature); proxy.sendMessageToTargets(output.getBuffer(), 0, proxy.getViewManager().getCurrentViewProcesses(), TOMMessageType.UNORDERED_REQUEST); output.close(); } private Output makeEmptyReadResponse(String message, Kryo kryo) { final Output output = new Output(0, 10240); kryo.writeObject(output, message); kryo.writeObject(output, new ArrayList<NodeStorage>()); kryo.writeObject(output, new ArrayList<RelationshipStorage>()); return output; } /** * Handle a signature message. * * @param input the message. * @param messageContext the context. * @param kryo the kryo object. */ private void handleSignatureMessage(final Input input, final MessageContext messageContext, final Kryo kryo) { //Our own message. if (idClient == messageContext.getSender()) { return; } final byte[] buffer = input.getBuffer(); final String decision = kryo.readObject(input, String.class); final Long snapShotId = kryo.readObject(input, Long.class); final List writeSet = kryo.readObject(input, ArrayList.class); final ArrayList<IOperation> localWriteSet; try { localWriteSet = (ArrayList<IOperation>) writeSet; } catch (ClassCastException e) { Log.getLogger().warn("Couldn't convert received signature message.", e); return; } Log.getLogger().info("Server: " + id + " Received message to sign with snapShotId: " + snapShotId + " of Server " + messageContext.getSender() + " and decision: " + decision + " and a writeSet of the length of: " + localWriteSet.size()); final int messageLength = kryo.readObject(input, Integer.class); final int signatureLength = kryo.readObject(input, Integer.class); final byte[] signature = input.readBytes(signatureLength); //Not required anymore. input.close(); final RSAKeyLoader rsaLoader = new RSAKeyLoader(messageContext.getSender(), GLOBAL_CONFIG_LOCATION, false); final PublicKey key; try { key = rsaLoader.loadPublicKey(); } catch (Exception e) { Log.getLogger().warn("Unable to load public key on server " + id + " sent by server " + messageContext.getSender(), e); return; } final byte[] message = new byte[messageLength]; System.arraycopy(buffer, 0, message, 0, messageLength); boolean signatureMatches = TOMUtil.verifySignature(key, message, signature); if (signatureMatches) { storeSignedMessage(snapShotId, signature, messageContext, decision, message, writeSet); return; } Log.getLogger().warn("Signature doesn't match of message, throwing message away."); } @Override public byte[] appExecuteUnordered(final byte[] bytes, final MessageContext messageContext) { Log.getLogger().info("Received unordered message at global replica"); final KryoPool pool = new KryoPool.Builder(getFactory()).softReferences().build(); final Kryo kryo = pool.borrow(); final Input input = new Input(bytes); final String messageType = kryo.readObject(input, String.class); Output output = new Output(1, 804800); switch (messageType) { case Constants.READ_MESSAGE: Log.getLogger().info("Received Node read message"); try { kryo.writeObject(output, Constants.READ_MESSAGE); output = handleNodeRead(input, kryo, output); } catch (Exception t) { Log.getLogger().error("Error on " + Constants.READ_MESSAGE + ", returning empty read", t); output.close(); output = makeEmptyReadResponse(Constants.READ_MESSAGE, kryo); } break; case Constants.RELATIONSHIP_READ_MESSAGE: Log.getLogger().info("Received Relationship read message"); try { kryo.writeObject(output, Constants.READ_MESSAGE); output = handleRelationshipRead(input, kryo, output); } catch (Exception t) { Log.getLogger().error("Error on " + Constants.RELATIONSHIP_READ_MESSAGE + ", returning empty read", t); output = makeEmptyReadResponse(Constants.RELATIONSHIP_READ_MESSAGE, kryo); } break; case Constants.SIGNATURE_MESSAGE: if (wrapper.getLocalCLuster() != null) { handleSignatureMessage(input, messageContext, kryo); } break; case Constants.REGISTER_GLOBALLY_MESSAGE: Log.getLogger().info("Received register globally message"); output.close(); input.close(); pool.release(kryo); return handleRegisteringSlave(input, kryo); case Constants.REGISTER_GLOBALLY_CHECK: Log.getLogger().info("Received globally check message"); output.close(); input.close(); pool.release(kryo); return handleGlobalRegistryCheck(input, kryo); case Constants.COMMIT: Log.getLogger().info("Received commit message"); output.close(); byte[] result = handleReadOnlyCommit(input, kryo); input.close(); pool.release(kryo); Log.getLogger().info("Return it to client, size: " + result.length); return result; default: Log.getLogger().warn("Incorrect operation sent unordered to the server"); break; } byte[] returnValue = output.getBuffer(); Log.getLogger().info("Return it to client, size: " + returnValue.length); input.close(); output.close(); pool.release(kryo); return returnValue; } private byte[] handleReadOnlyCommit(final Input input, final Kryo kryo) { final Long timeStamp = kryo.readObject(input, Long.class); return executeReadOnlyCommit(kryo, input, timeStamp); } /** * Handle the check for the global registering of a slave. * * @param input the incoming message. * @param kryo the kryo instance. * @return the reply */ private byte[] handleGlobalRegistryCheck(final Input input, final Kryo kryo) { final Output output = new Output(512); kryo.writeObject(output, Constants.REGISTER_GLOBALLY_CHECK); boolean decision = false; if (!wrapper.getLocalCLuster().isPrimary() || wrapper.getLocalCLuster().askIfIsPrimary(kryo.readObject(input, Integer.class), kryo.readObject(input, Integer.class), kryo)) { decision = true; } kryo.writeObject(output, decision); final byte[] result = output.getBuffer(); output.close(); input.close(); return result; } /** * This message comes from the local cluster. * Will respond true if it can register. * Message which handles slaves registering at the global cluster. * * @param kryo the kryo instance. * @param input the message. * @return the message in bytes. */ @SuppressWarnings("squid:S2095") private byte[] handleRegisteringSlave(final Input input, final Kryo kryo) { final int localClusterID = kryo.readObject(input, Integer.class); final int newPrimary = kryo.readObject(input, Integer.class); final int oldPrimary = kryo.readObject(input, Integer.class); final ServiceProxy localProxy = new ServiceProxy(1000 + oldPrimary, "local" + localClusterID); final Output output = new Output(512); kryo.writeObject(output, Constants.REGISTER_GLOBALLY_CHECK); kryo.writeObject(output, newPrimary); byte[] result = localProxy.invokeUnordered(output.getBuffer()); final Output nextOutput = new Output(512); kryo.writeObject(output, Constants.REGISTER_GLOBALLY_REPLY); final Input answer = new Input(result); if (Constants.REGISTER_GLOBALLY_REPLY.equals(answer.readString())) { kryo.writeObject(nextOutput, answer.readBoolean()); } final byte[] returnBuffer = nextOutput.getBuffer(); nextOutput.close(); answer.close(); localProxy.close(); output.close(); return returnBuffer; //remove currentView and edit system.config //If alright send the result to all remaining global clusters so that they update themselves. } /** * Store the signed message on the server. * If n-f messages arrived send it to client. * * @param snapShotId the snapShotId as key. * @param signature the signature * @param context the message context. * @param decision the decision. * @param message the message. */ private void storeSignedMessage( final Long snapShotId, final byte[] signature, @NotNull final MessageContext context, final String decision, final byte[] message, final List<IOperation> writeSet) { final SignatureStorage signatureStorage; if (signatureStorageCache.getIfPresent(snapShotId) == null) { signatureStorage = new SignatureStorage(super.getReplica().getReplicaContext().getStaticConfiguration().getN() - 1, message, decision); signatureStorageCache.put(snapShotId, signatureStorage); Log.getLogger().info("Replica: " + id + " did not have the transaction prepared. Might be slow or corrupted, message size stored: " + message.length); } else { signatureStorage = signatureStorageCache.getIfPresent(snapShotId); } if (signatureStorage.getMessage().length != message.length) { Log.getLogger().error("Message in signatureStorage: " + signatureStorage.getMessage().length + " message of writing server " + message.length + " ws: " + writeSet.size()); } if (!decision.equals(signatureStorage.getDecision())) { Log.getLogger().warn("Replica: " + id + " did receive a different decision of replica: " + context.getSender() + ". Might be corrupted."); return; } signatureStorage.addSignatures(context.getSender(), signature); Log.getLogger().info("Adding signature to signatureStorage, has: " + signatureStorage.getSignatures().size() + " is: " + signatureStorage.isProcessed() + " by: " + context.getSender()); if (signatureStorage.hasEnough()) { Log.getLogger().info("Sending update to slave signed by all members: " + snapShotId); if (signatureStorage.isProcessed()) { updateSlave(signatureStorage); signatureStorage.setDistributed(); } if (signatureStorage.hasAll() && signatureStorage.isDistributed()) { signatureStorageCache.invalidate(snapShotId); return; } } signatureStorageCache.put(snapShotId, signatureStorage); } /** * Update the slave with a transaction. * * @param signatureStorage the signatureStorage with message and signatures.. */ private void updateSlave(final SignatureStorage signatureStorage) { if (this.wrapper.getLocalCLuster() != null) { this.wrapper.getLocalCLuster().propagateUpdate(new SignatureStorage(signatureStorage)); } } /** * Invoke a message to the global cluster. * * @param input the input object. * @return the response. */ Output invokeGlobally(final Input input) { return new Output(proxy.invokeOrdered(input.getBuffer())); } /** * Closes the global cluster and his code. */ public void close() { super.terminate(); proxy.close(); } }
package mil.dds.anet.beans.search; import java.time.Instant; import java.util.List; import mil.dds.anet.beans.Person.PersonStatus; import mil.dds.anet.beans.Person.Role; public class PersonSearchQuery extends AbstractSearchQuery { public enum PersonSearchSortBy { CREATED_AT, NAME, RANK } String orgUuid; Role role; List<PersonStatus> status; Boolean includeChildOrgs; String rank; String country; Instant endOfTourDateStart; Instant endOfTourDateEnd; // Filter to people in positions at a certain location String locationUuid; // Also match on positions whose name or code matches text. Boolean matchPositionName; // Find people who are pending verification Boolean pendingVerification; private PersonSearchSortBy sortBy; public PersonSearchQuery() { super(); this.setPageSize(100); this.sortBy = PersonSearchSortBy.NAME; this.setSortOrder(SortOrder.ASC); } public String getOrgUuid() { return orgUuid; } public void setOrgUuid(String orgUuid) { this.orgUuid = orgUuid; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public List<PersonStatus> getStatus() { return status; } public void setStatus(List<PersonStatus> status) { this.status = status; } public Boolean getIncludeChildOrgs() { return includeChildOrgs; } public void setIncludeChildOrgs(Boolean includeChildOrgs) { this.includeChildOrgs = includeChildOrgs; } public String getRank() { return rank; } public void setRank(String rank) { this.rank = rank; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getLocationUuid() { return locationUuid; } public void setLocationUuid(String locationUuid) { this.locationUuid = locationUuid; } public Boolean getMatchPositionName() { return Boolean.TRUE.equals(matchPositionName); } public void setMatchPositionName(Boolean matchPositionName) { this.matchPositionName = matchPositionName; } public Boolean getPendingVerification() { return pendingVerification; } public void setPendingVerification(Boolean pendingVerification) { this.pendingVerification = pendingVerification; } public PersonSearchSortBy getSortBy() { return sortBy; } public void setSortBy(PersonSearchSortBy sortBy) { this.sortBy = sortBy; } public Instant getEndOfTourDateStart() { return endOfTourDateStart; } public void setEndOfTourDateStart(Instant endOfTourDateStart) { this.endOfTourDateStart = endOfTourDateStart; } public Instant getEndOfTourDateEnd() { return endOfTourDateEnd; } public void setEndOfTourDateEnd(Instant endOfTourDateEnd) { this.endOfTourDateEnd = endOfTourDateEnd; } public static PersonSearchQuery withText(String text, int pageNum, int pageSize) { PersonSearchQuery query = new PersonSearchQuery(); query.setText(text); query.setPageNum(pageNum); query.setPageSize(pageSize); return query; } }
package modtweaker.mods.tconstruct.handlers; import minetweaker.MineTweakerAPI; import minetweaker.api.item.IIngredient; import minetweaker.api.item.IItemStack; import minetweaker.api.item.IngredientAny; import minetweaker.api.liquid.ILiquidStack; import modtweaker.helpers.LogHelper; import modtweaker.mods.tconstruct.TConstructHelper; import modtweaker.utils.BaseListAddition; import modtweaker.utils.BaseListRemoval; import net.minecraftforge.fluids.FluidStack; import slimeknights.mantle.util.RecipeMatch; import slimeknights.tconstruct.library.smeltery.CastingRecipe; import slimeknights.tconstruct.library.smeltery.ICastingRecipe; import stanhebben.zenscript.annotations.Optional; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; import java.util.LinkedList; import java.util.List; import static modtweaker.helpers.InputHelper.*; import static modtweaker.helpers.StackHelper.matches; @ZenClass("mods.tconstruct.Casting") public class Casting { protected static final String name = "TConstruct Casting"; @ZenMethod public static void addBasinRecipe(IItemStack output, ILiquidStack liquid, @Optional IItemStack cast, @Optional boolean consumeCast, @Optional int timeInTicks) { if (liquid == null || output == null) { LogHelper.logError(String.format("Required parameters missing for %s Recipe.", name)); return; } FluidStack fluid = toFluid(liquid); if (timeInTicks == 0) { timeInTicks = CastingRecipe.calcCooldownTime(fluid.getFluid(), fluid.amount); } CastingRecipe rec = new CastingRecipe(toStack(output), RecipeMatch.of(toStack(cast)), fluid, timeInTicks, consumeCast, false); MineTweakerAPI.apply(new Add(rec, (LinkedList<ICastingRecipe>) TConstructHelper.basinCasting)); } @ZenMethod public static void addTableRecipe(IItemStack output, ILiquidStack liquid, @Optional IItemStack cast, @Optional boolean consumeCast, @Optional int timeInTicks) { if (liquid == null || output == null) { LogHelper.logError(String.format("Required parameters missing for %s Recipe.", name)); return; } RecipeMatch match = null; if (cast != null) { match = RecipeMatch.of(toStack(cast)); } FluidStack fluid = toFluid(liquid); if (timeInTicks == 0) { timeInTicks = CastingRecipe.calcCooldownTime(fluid.getFluid(), fluid.amount); } CastingRecipe rec = new CastingRecipe(toStack(output), match, fluid, timeInTicks, consumeCast, false); MineTweakerAPI.apply(new Add(rec, (LinkedList<ICastingRecipe>) TConstructHelper.tableCasting)); } //Passes the list to the base list implementation, and adds the recipe private static class Add extends BaseListAddition<ICastingRecipe> { public Add(CastingRecipe recipe, LinkedList<ICastingRecipe> list) { super(Casting.name, list); this.recipes.add(recipe); } @Override protected String getRecipeInfo(ICastingRecipe recipe) { return LogHelper.getStackDescription(((CastingRecipe) recipe).getResult()); } } @ZenMethod public static void removeTableRecipe(IIngredient output, @Optional IIngredient liquid, @Optional IIngredient cast) { removeRecipe(output, liquid, cast, TConstructHelper.tableCasting); } @ZenMethod public static void removeBasinRecipe(IIngredient output, @Optional IIngredient liquid, @Optional IIngredient cast) { removeRecipe(output, liquid, cast, TConstructHelper.basinCasting); } public static void removeRecipe(IIngredient output, IIngredient liquid, IIngredient cast, List<ICastingRecipe> list) { if (output == null) { LogHelper.logError(String.format("Required parameters missing for %s Recipe.", name)); return; } if (liquid == null) { liquid = IngredientAny.INSTANCE; } List<ICastingRecipe> recipes = new LinkedList<ICastingRecipe>(); for (ICastingRecipe recipe : list) { if (recipe instanceof CastingRecipe) { if (!matches(output, toIItemStack(((CastingRecipe) recipe).getResult()))) { continue; } if (!matches(liquid, toILiquidStack(((CastingRecipe) recipe).getFluid()))) { continue; } if ((((CastingRecipe) recipe).cast != null && cast != null) && (((CastingRecipe) recipe).cast.matches(toStacks(cast.getItems().toArray(new IItemStack[0]))) == null)) { continue; } recipes.add((CastingRecipe) recipe); } } if (!recipes.isEmpty()) { MineTweakerAPI.apply(new Remove(list, recipes)); } else { LogHelper.logWarning(String.format("No %s Recipe found for output %s, material %s and cast %s. Command ignored!", Casting.name, output.toString(), liquid.toString(), cast != null ? cast.toString() : null)); } } // Removes all matching recipes, apply is never the same for anything, so will always need to override it private static class Remove extends BaseListRemoval<ICastingRecipe> { public Remove(List<ICastingRecipe> list, List<ICastingRecipe> recipes) { super(Casting.name, list, recipes); } @Override protected String getRecipeInfo(ICastingRecipe recipe) { return LogHelper.getStackDescription(((CastingRecipe) recipe).getResult()); } } }
package net.interfax.rest.client.domain; import java.util.List; import java.util.Map; public class APIResponse { private int statusCode; private String responseBody; private Map<String, List<Object>> headers; public int getStatusCode() { return statusCode; } public void setStatusCode(final int statusCode) { this.statusCode = statusCode; } public String getResponseBody() { return responseBody; } public void setResponseBody(final String responseBody) { this.responseBody = responseBody; } public Map<String, List<Object>> getHeaders() { return headers; } public void setHeaders(final Map<String, List<Object>> headers) { this.headers = headers; } }
package net.sf.mzmine.util.logging; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Formatter; import java.util.logging.LogRecord; /** * Console log formatter */ public class ConsoleFormatter extends Formatter { private static final DateFormat format = new SimpleDateFormat("H:mm:ss"); private static final String lineSep = System.getProperty("line.separator"); public String format(LogRecord record) { StringBuilder output = new StringBuilder(512); Date eventTime = new Date(record.getMillis()); output.append("["); output.append(format.format(eventTime)); output.append('|'); output.append(record.getLevel()); output.append('|'); output.append(record.getLoggerName()); output.append("]: "); output.append(record.getMessage()); if (record.getThrown() != null) { output.append("("); output.append(record.getThrown().toString()); Object[] stackTrace = record.getThrown().getStackTrace(); if (stackTrace.length > 0) { output.append("@"); output.append(stackTrace[0].toString()); } output.append(")"); } output.append(lineSep); return output.toString(); } }
package org.b3log.symphony.processor; import com.qiniu.util.Auth; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.DateUtils; import org.b3log.latke.Keys; import org.b3log.latke.Latkes; import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Logger; import org.b3log.latke.model.User; import org.b3log.latke.service.LangPropsService; import org.b3log.latke.service.ServiceException; import org.b3log.latke.servlet.HTTPRequestContext; import org.b3log.latke.servlet.HTTPRequestMethod; import org.b3log.latke.servlet.annotation.After; import org.b3log.latke.servlet.annotation.Before; import org.b3log.latke.servlet.annotation.RequestProcessing; import org.b3log.latke.servlet.annotation.RequestProcessor; import org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer; import org.b3log.latke.util.Locales; import org.b3log.latke.util.Requests; import org.b3log.latke.util.Strings; import org.b3log.symphony.model.*; import org.b3log.symphony.processor.advice.CSRFToken; import org.b3log.symphony.processor.advice.LoginCheck; import org.b3log.symphony.processor.advice.PermissionGrant; import org.b3log.symphony.processor.advice.stopwatch.StopwatchEndAdvice; import org.b3log.symphony.processor.advice.stopwatch.StopwatchStartAdvice; import org.b3log.symphony.processor.advice.validate.UserForgetPwdValidation; import org.b3log.symphony.processor.advice.validate.UserRegister2Validation; import org.b3log.symphony.processor.advice.validate.UserRegisterValidation; import org.b3log.symphony.service.*; import org.b3log.symphony.util.Sessions; import org.b3log.symphony.util.Symphonys; import org.json.JSONObject; import javax.inject.Inject; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @RequestProcessor public class LoginProcessor { /** * Wrong password tries. * <p> * &lt;userId, {"wrongCount": int, "captcha": ""}&gt; */ public static final Map<String, JSONObject> WRONG_PWD_TRIES = new ConcurrentHashMap<>(); /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(LoginProcessor.class.getName()); /** * User management service. */ @Inject private UserMgmtService userMgmtService; /** * User query service. */ @Inject private UserQueryService userQueryService; /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Pointtransfer management service. */ @Inject private PointtransferMgmtService pointtransferMgmtService; /** * Data model service. */ @Inject private DataModelService dataModelService; /** * Verifycode management service. */ @Inject private VerifycodeMgmtService verifycodeMgmtService; /** * Verifycode query service. */ @Inject private VerifycodeQueryService verifycodeQueryService; /** * Timeline management service. */ @Inject private TimelineMgmtService timelineMgmtService; /** * Option query service. */ @Inject private OptionQueryService optionQueryService; /** * Invitecode query service. */ @Inject private InvitecodeQueryService invitecodeQueryService; /** * Invitecode management service. */ @Inject private InvitecodeMgmtService invitecodeMgmtService; /** * Invitecode management service. */ @Inject private NotificationMgmtService notificationMgmtService; /** * Role query service. */ @Inject private RoleQueryService roleQueryService; /** * Tag query service. */ @Inject private TagQueryService tagQueryService; /** * Shows login page. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/guide", method = HTTPRequestMethod.GET) @Before(adviceClass = {StopwatchStartAdvice.class, LoginCheck.class}) @After(adviceClass = {CSRFToken.class, PermissionGrant.class, StopwatchEndAdvice.class}) public void showGuide(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final JSONObject currentUser = (JSONObject) request.getAttribute(User.USER); final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); context.setRenderer(renderer); renderer.setTemplateName("/verify/guide.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); dataModel.put(Common.CURRENT_USER, currentUser); final List<JSONObject> tags = tagQueryService.getTags(32); dataModel.put(Tag.TAGS, tags); final List<JSONObject> users = userQueryService.getNiceUsers(12); dataModel.put(User.USERS, users); // Qiniu file upload authenticate final Auth auth = Auth.create(Symphonys.get("qiniu.accessKey"), Symphonys.get("qiniu.secretKey")); final String uploadToken = auth.uploadToken(Symphonys.get("qiniu.bucket")); dataModel.put("qiniuUploadToken", uploadToken); dataModel.put("qiniuDomain", Symphonys.get("qiniu.domain")); if (!Symphonys.getBoolean("qiniu.enabled")) { dataModel.put("qiniuUploadToken", ""); } final long imgMaxSize = Symphonys.getLong("upload.img.maxSize"); dataModel.put("imgMaxSize", imgMaxSize); final long fileMaxSize = Symphonys.getLong("upload.file.maxSize"); dataModel.put("fileMaxSize", fileMaxSize); dataModelService.fillHeaderAndFooter(request, response, dataModel); } /** * Shows login page. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/login", method = HTTPRequestMethod.GET) @Before(adviceClass = StopwatchStartAdvice.class) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void showLogin(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { if (null != userQueryService.getCurrentUser(request) || userMgmtService.tryLogInWithCookie(request, response)) { response.sendRedirect(Latkes.getServePath()); return; } final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); context.setRenderer(renderer); String referer = request.getParameter(Common.GOTO); if (StringUtils.isBlank(referer)) { referer = request.getHeader("referer"); } renderer.setTemplateName("/verify/login.ftl"); final Map<String, Object> dataModel = renderer.getDataModel(); dataModel.put(Common.GOTO, referer); dataModelService.fillHeaderAndFooter(request, response, dataModel); } /** * Shows forget password page. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/forget-pwd", method = HTTPRequestMethod.GET) @Before(adviceClass = StopwatchStartAdvice.class) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void showForgetPwd(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); context.setRenderer(renderer); final Map<String, Object> dataModel = renderer.getDataModel(); renderer.setTemplateName("forget-pwd.ftl"); dataModelService.fillHeaderAndFooter(request, response, dataModel); } /** * Forget password. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/forget-pwd", method = HTTPRequestMethod.POST) @Before(adviceClass = UserForgetPwdValidation.class) public void forgetPwd(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { context.renderJSON(); final JSONObject requestJSONObject = (JSONObject) request.getAttribute(Keys.REQUEST); final String email = requestJSONObject.optString(User.USER_EMAIL); try { final JSONObject user = userQueryService.getUserByEmail(email); if (null == user) { context.renderFalseResult().renderMsg(langPropsService.get("notFoundUserLabel")); return; } final String userId = user.optString(Keys.OBJECT_ID); final JSONObject verifycode = new JSONObject(); verifycode.put(Verifycode.BIZ_TYPE, Verifycode.BIZ_TYPE_C_RESET_PWD); final String code = RandomStringUtils.randomAlphanumeric(6); verifycode.put(Verifycode.CODE, code); verifycode.put(Verifycode.EXPIRED, DateUtils.addDays(new Date(), 1).getTime()); verifycode.put(Verifycode.RECEIVER, email); verifycode.put(Verifycode.STATUS, Verifycode.STATUS_C_UNSENT); verifycode.put(Verifycode.TYPE, Verifycode.TYPE_C_EMAIL); verifycode.put(Verifycode.USER_ID, userId); verifycodeMgmtService.addVerifycode(verifycode); context.renderTrueResult().renderMsg(langPropsService.get("verifycodeSentLabel")); } catch (final ServiceException e) { final String msg = langPropsService.get("resetPwdLabel") + " - " + e.getMessage(); LOGGER.log(Level.ERROR, msg + "[name={0}, email={1}]", email); context.renderMsg(msg); } } /** * Shows reset password page. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/reset-pwd", method = HTTPRequestMethod.GET) @Before(adviceClass = StopwatchStartAdvice.class) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void showResetPwd(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); context.setRenderer(renderer); final Map<String, Object> dataModel = renderer.getDataModel(); final String code = request.getParameter("code"); final JSONObject verifycode = verifycodeQueryService.getVerifycode(code); if (null == verifycode) { dataModel.put(Keys.MSG, langPropsService.get("verifycodeExpiredLabel")); renderer.setTemplateName("/error/custom.ftl"); } else { renderer.setTemplateName("verify/reset-pwd.ftl"); final String userId = verifycode.optString(Verifycode.USER_ID); final JSONObject user = userQueryService.getUser(userId); dataModel.put(User.USER, user); } dataModelService.fillHeaderAndFooter(request, response, dataModel); } /** * Resets password. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws ServletException servlet exception * @throws IOException io exception */ @RequestProcessing(value = "/reset-pwd", method = HTTPRequestMethod.POST) public void resetPwd(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { context.renderJSON(); final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, response); final String password = requestJSONObject.optString(User.USER_PASSWORD); // Hashed final String userId = requestJSONObject.optString(Common.USER_ID); String name = null; String email = null; try { final JSONObject user = userQueryService.getUser(userId); if (null == user) { context.renderMsg(langPropsService.get("resetPwdLabel") + " - " + "User Not Found"); return; } user.put(User.USER_PASSWORD, password); userMgmtService.updatePassword(user); context.renderTrueResult(); LOGGER.info("User [email=" + user.optString(User.USER_EMAIL) + "] reseted password"); } catch (final ServiceException e) { final String msg = langPropsService.get("resetPwdLabel") + " - " + e.getMessage(); LOGGER.log(Level.ERROR, msg + "[name={0}, email={1}]", name, email); context.renderMsg(msg); } } /** * Shows registration page. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws Exception exception */ @RequestProcessing(value = "/register", method = HTTPRequestMethod.GET) @Before(adviceClass = StopwatchStartAdvice.class) @After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class}) public void showRegister(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { if (null != userQueryService.getCurrentUser(request) || userMgmtService.tryLogInWithCookie(request, response)) { response.sendRedirect(Latkes.getServePath()); return; } final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request); context.setRenderer(renderer); final Map<String, Object> dataModel = renderer.getDataModel(); dataModel.put(Common.REFERRAL, ""); boolean useInvitationLink = false; String referral = request.getParameter("r"); if (!UserRegisterValidation.invalidUserName(referral)) { final JSONObject referralUser = userQueryService.getUserByName(referral); if (null != referralUser) { dataModel.put(Common.REFERRAL, referral); final Map<String, JSONObject> permissions = roleQueryService.getUserPermissionsGrantMap(referralUser.optString(Keys.OBJECT_ID)); final JSONObject useILPermission = permissions.get(Permission.PERMISSION_ID_C_COMMON_USE_INVITATION_LINK); useInvitationLink = UserExt.containsWhiteListInvitationUser(referral) && useILPermission.optBoolean(Permission.PERMISSION_T_GRANT); } } final String code = request.getParameter("code"); if (Strings.isEmptyOrNull(code)) { // Register Step 1 renderer.setTemplateName("verify/register.ftl"); } else { // Register Step 2 final JSONObject verifycode = verifycodeQueryService.getVerifycode(code); if (null == verifycode) { dataModel.put(Keys.MSG, langPropsService.get("verifycodeExpiredLabel")); renderer.setTemplateName("/error/custom.ftl"); } else { renderer.setTemplateName("verify/register2.ftl"); final String userId = verifycode.optString(Verifycode.USER_ID); final JSONObject user = userQueryService.getUser(userId); dataModel.put(User.USER, user); if (UserExt.USER_STATUS_C_VALID == user.optInt(UserExt.USER_STATUS) || UserExt.NULL_USER_NAME.equals(user.optString(User.USER_NAME))) { dataModel.put(Keys.MSG, langPropsService.get("userExistLabel")); renderer.setTemplateName("/error/custom.ftl"); } else { referral = StringUtils.substringAfter(code, "r="); if (!Strings.isEmptyOrNull(referral)) { dataModel.put(Common.REFERRAL, referral); } } } } final String allowRegister = optionQueryService.getAllowRegister(); dataModel.put(Option.ID_C_MISC_ALLOW_REGISTER, allowRegister); if (useInvitationLink && "2".equals(allowRegister)) { dataModel.put(Option.ID_C_MISC_ALLOW_REGISTER, "1"); } dataModelService.fillHeaderAndFooter(request, response, dataModel); } /** * Register Step 1. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws ServletException servlet exception * @throws IOException io exception */ @RequestProcessing(value = "/register", method = HTTPRequestMethod.POST) @Before(adviceClass = UserRegisterValidation.class) public void register(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { context.renderJSON(); final JSONObject requestJSONObject = (JSONObject) request.getAttribute(Keys.REQUEST); final String name = requestJSONObject.optString(User.USER_NAME); final String email = requestJSONObject.optString(User.USER_EMAIL); final String invitecode = requestJSONObject.optString(Invitecode.INVITECODE); final String referral = requestJSONObject.optString(Common.REFERRAL); final JSONObject user = new JSONObject(); user.put(User.USER_NAME, name); user.put(User.USER_EMAIL, email); user.put(User.USER_PASSWORD, ""); final Locale locale = Locales.getLocale(); user.put(UserExt.USER_LANGUAGE, locale.getLanguage() + "_" + locale.getCountry()); try { final String newUserId = userMgmtService.addUser(user); final JSONObject verifycode = new JSONObject(); verifycode.put(Verifycode.BIZ_TYPE, Verifycode.BIZ_TYPE_C_REGISTER); String code = RandomStringUtils.randomAlphanumeric(6); if (!Strings.isEmptyOrNull(referral)) { code += "r=" + referral; } verifycode.put(Verifycode.CODE, code); verifycode.put(Verifycode.EXPIRED, DateUtils.addDays(new Date(), 1).getTime()); verifycode.put(Verifycode.RECEIVER, email); verifycode.put(Verifycode.STATUS, Verifycode.STATUS_C_UNSENT); verifycode.put(Verifycode.TYPE, Verifycode.TYPE_C_EMAIL); verifycode.put(Verifycode.USER_ID, newUserId); verifycodeMgmtService.addVerifycode(verifycode); final String allowRegister = optionQueryService.getAllowRegister(); if ("2".equals(allowRegister) && StringUtils.isNotBlank(invitecode)) { final JSONObject ic = invitecodeQueryService.getInvitecode(invitecode); ic.put(Invitecode.USER_ID, newUserId); ic.put(Invitecode.USE_TIME, System.currentTimeMillis()); final String icId = ic.optString(Keys.OBJECT_ID); invitecodeMgmtService.updateInvitecode(icId, ic); } context.renderTrueResult().renderMsg(langPropsService.get("verifycodeSentLabel")); } catch (final ServiceException e) { final String msg = langPropsService.get("registerFailLabel") + " - " + e.getMessage(); LOGGER.log(Level.ERROR, msg + "[name={0}, email={1}]", name, email); context.renderMsg(msg); } } /** * Register Step 2. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws ServletException servlet exception * @throws IOException io exception */ @RequestProcessing(value = "/register2", method = HTTPRequestMethod.POST) @Before(adviceClass = UserRegister2Validation.class) public void register2(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { context.renderJSON(); final JSONObject requestJSONObject = (JSONObject) request.getAttribute(Keys.REQUEST); final String password = requestJSONObject.optString(User.USER_PASSWORD); // Hashed final int appRole = requestJSONObject.optInt(UserExt.USER_APP_ROLE); final String referral = requestJSONObject.optString(Common.REFERRAL); final String userId = requestJSONObject.optString(Common.USER_ID); String name = null; String email = null; try { final JSONObject user = userQueryService.getUser(userId); if (null == user) { context.renderMsg(langPropsService.get("registerFailLabel") + " - " + "User Not Found"); return; } name = user.optString(User.USER_NAME); email = user.optString(User.USER_EMAIL); user.put(UserExt.USER_APP_ROLE, appRole); user.put(User.USER_PASSWORD, password); user.put(UserExt.USER_STATUS, UserExt.USER_STATUS_C_VALID); userMgmtService.addUser(user); Sessions.login(request, response, user, false); final String ip = Requests.getRemoteAddr(request); userMgmtService.updateOnlineStatus(user.optString(Keys.OBJECT_ID), ip, true); if (!Strings.isEmptyOrNull(referral)) { final JSONObject referralUser = userQueryService.getUserByName(referral); if (null != referralUser) { final String referralId = referralUser.optString(Keys.OBJECT_ID); // Point pointtransferMgmtService.transfer(Pointtransfer.ID_C_SYS, userId, Pointtransfer.TRANSFER_TYPE_C_INVITED_REGISTER, Pointtransfer.TRANSFER_SUM_C_INVITE_REGISTER, referralId, System.currentTimeMillis()); pointtransferMgmtService.transfer(Pointtransfer.ID_C_SYS, referralId, Pointtransfer.TRANSFER_TYPE_C_INVITE_REGISTER, Pointtransfer.TRANSFER_SUM_C_INVITE_REGISTER, userId, System.currentTimeMillis()); } } final JSONObject ic = invitecodeQueryService.getInvitecodeByUserId(userId); if (null != ic && Invitecode.STATUS_C_UNUSED == ic.optInt(Invitecode.STATUS)) { ic.put(Invitecode.STATUS, Invitecode.STATUS_C_USED); ic.put(Invitecode.USER_ID, userId); ic.put(Invitecode.USE_TIME, System.currentTimeMillis()); final String icId = ic.optString(Keys.OBJECT_ID); invitecodeMgmtService.updateInvitecode(icId, ic); final String icGeneratorId = ic.optString(Invitecode.GENERATOR_ID); if (StringUtils.isNotBlank(icGeneratorId) && !Pointtransfer.ID_C_SYS.equals(icGeneratorId)) { pointtransferMgmtService.transfer(Pointtransfer.ID_C_SYS, icGeneratorId, Pointtransfer.TRANSFER_TYPE_C_INVITECODE_USED, Pointtransfer.TRANSFER_SUM_C_INVITECODE_USED, userId, System.currentTimeMillis()); final JSONObject notification = new JSONObject(); notification.put(Notification.NOTIFICATION_USER_ID, icGeneratorId); notification.put(Notification.NOTIFICATION_DATA_ID, userId); notificationMgmtService.addInvitecodeUsedNotification(notification); } } context.renderTrueResult(); LOGGER.log(Level.INFO, "Registered a user [name={0}, email={1}]", name, email); // Timeline final JSONObject timeline = new JSONObject(); timeline.put(Common.USER_ID, user.optString(Keys.OBJECT_ID)); timeline.put(Common.TYPE, Common.NEW_USER); String content = langPropsService.get("timelineNewUserLabel"); content = content.replace("{user}", "<a target='_blank' rel='nofollow' href='" + Latkes.getServePath() + "/member/" + name + "'>" + name + "</a>"); timeline.put(Common.CONTENT, content); timelineMgmtService.addTimeline(timeline); } catch (final ServiceException e) { final String msg = langPropsService.get("registerFailLabel") + " - " + e.getMessage(); LOGGER.log(Level.ERROR, msg + "[name={0}, email={1}]", name, email); context.renderMsg(msg); } } /** * Logins user. * * @param context the specified context * @param request the specified request * @param response the specified response * @throws ServletException servlet exception * @throws IOException io exception */ @RequestProcessing(value = "/login", method = HTTPRequestMethod.POST) public void login(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { context.renderJSON().renderMsg(langPropsService.get("loginFailLabel")); final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, response); final String nameOrEmail = requestJSONObject.optString("nameOrEmail"); try { JSONObject user = userQueryService.getUserByName(nameOrEmail); if (null == user) { user = userQueryService.getUserByEmail(nameOrEmail); } if (null == user) { context.renderMsg(langPropsService.get("notFoundUserLabel")); return; } if (UserExt.USER_STATUS_C_INVALID == user.optInt(UserExt.USER_STATUS)) { userMgmtService.updateOnlineStatus(user.optString(Keys.OBJECT_ID), "", false); context.renderMsg(langPropsService.get("userBlockLabel")); return; } if (UserExt.USER_STATUS_C_NOT_VERIFIED == user.optInt(UserExt.USER_STATUS)) { userMgmtService.updateOnlineStatus(user.optString(Keys.OBJECT_ID), "", false); context.renderMsg(langPropsService.get("notVerifiedLabel")); return; } if (UserExt.USER_STATUS_C_INVALID_LOGIN == user.optInt(UserExt.USER_STATUS)) { userMgmtService.updateOnlineStatus(user.optString(Keys.OBJECT_ID), "", false); context.renderMsg(langPropsService.get("invalidLoginLabel")); return; } final String userId = user.optString(Keys.OBJECT_ID); JSONObject wrong = WRONG_PWD_TRIES.get(userId); if (null == wrong) { wrong = new JSONObject(); } final int wrongCount = wrong.optInt(Common.WRON_COUNT); if (wrongCount > 3) { final String captcha = requestJSONObject.optString(CaptchaProcessor.CAPTCHA); if (!StringUtils.equals(wrong.optString(CaptchaProcessor.CAPTCHA), captcha)) { context.renderMsg(langPropsService.get("captchaErrorLabel")); context.renderJSONValue(Common.NEED_CAPTCHA, userId); return; } } final String userPassword = user.optString(User.USER_PASSWORD); if (userPassword.equals(requestJSONObject.optString(User.USER_PASSWORD))) { Sessions.login(request, response, user, requestJSONObject.optBoolean(Common.REMEMBER_LOGIN)); final String ip = Requests.getRemoteAddr(request); userMgmtService.updateOnlineStatus(user.optString(Keys.OBJECT_ID), ip, true); context.renderMsg("").renderTrueResult(); WRONG_PWD_TRIES.remove(userId); return; } if (wrongCount > 2) { context.renderJSONValue(Common.NEED_CAPTCHA, userId); } wrong.put(Common.WRON_COUNT, wrongCount + 1); WRONG_PWD_TRIES.put(userId, wrong); context.renderMsg(langPropsService.get("wrongPwdLabel")); } catch (final ServiceException e) { context.renderMsg(langPropsService.get("loginFailLabel")); } } /** * Logout. * * @param context the specified context * @throws IOException io exception */ @RequestProcessing(value = {"/logout"}, method = HTTPRequestMethod.GET) public void logout(final HTTPRequestContext context) throws IOException { final HttpServletRequest httpServletRequest = context.getRequest(); Sessions.logout(httpServletRequest, context.getResponse()); String destinationURL = httpServletRequest.getParameter(Common.GOTO); if (Strings.isEmptyOrNull(destinationURL)) { destinationURL = "/"; } context.getResponse().sendRedirect(destinationURL); } /** * Expires invitecodes. * * @param request the specified HTTP servlet request * @param response the specified HTTP servlet response * @param context the specified HTTP request context * @throws Exception exception */ @RequestProcessing(value = "/cron/invitecode-expire", method = HTTPRequestMethod.GET) @Before(adviceClass = StopwatchStartAdvice.class) @After(adviceClass = StopwatchEndAdvice.class) public void expireInvitecodes(final HttpServletRequest request, final HttpServletResponse response, final HTTPRequestContext context) throws Exception { final String key = Symphonys.get("keyOfSymphony"); if (!key.equals(request.getParameter("key"))) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } invitecodeMgmtService.expireInvitecodes(); context.renderJSON().renderTrueResult(); } }
package org.basex.query.up.primitives; public enum PrimitiveType { /* * XQuery/Update * * The type order corresponds to the order updates are carried out node-wise. * The XQuery Update Facility specification proposes the following order: * * - INSERTINTO, INSERTATTR, REPLACEVALUE, RENAMENODE * - INSERTBEFORE, INSERTAFTER, INSERTINTOFIRST, INSERTINTOLAST * - REPLACENODE * - REPLACEELEMCONT * - DELETE * - PUT * * Why does it differ from the specification? * * We apply the order to each single target node instead of a document (like * stated in the specification). The result stays the same. Several * adjustments to the proposed order simplify the implementation. In general, * updates that shift pre values on the descendant/following axis are moved * to the back to avoid further calculation expenses to determine target * pre values. */ /** Insert attribute. */ INSERTATTR, /** Replace value. */ REPLACEVALUE, /** Rename. */ RENAMENODE, /** Insert after. */ INSERTAFTER, /** Insert into as first. */ INSERTINTOFIRST, /** Insert into (as last). */ INSERTINTO, /** Replace element content. */ REPLACEELEMCONT, /** Put. */ PUT, /** Insert before. */ INSERTBEFORE, /** Replace node. */ REPLACENODE, /** Delete. */ DELETENODE }
package org.bulatnig.smpp.session.impl; import org.bulatnig.smpp.net.Connection; import org.bulatnig.smpp.pdu.CommandId; import org.bulatnig.smpp.pdu.CommandStatus; import org.bulatnig.smpp.pdu.Pdu; import org.bulatnig.smpp.pdu.PduException; import org.bulatnig.smpp.pdu.impl.EnquireLink; import org.bulatnig.smpp.pdu.impl.EnquireLinkResp; import org.bulatnig.smpp.pdu.impl.Unbind; import org.bulatnig.smpp.session.MessageListener; import org.bulatnig.smpp.session.Session; import org.bulatnig.smpp.session.State; import org.bulatnig.smpp.session.StateListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * Asynchronous session implementation. * * @author Bulat Nigmatullin */ public class BasicSession implements Session { private static final Logger logger = LoggerFactory.getLogger(BasicSession.class); private final Connection conn; private int smscResponseTimeout = DEFAULT_SMSC_RESPONSE_TIMEOUT; private int pingTimeout = DEFAULT_ENQUIRE_LINK_TIMEOUT; private int reconnectTimeout = DEFAULT_RECONNECT_TIMEOUT; private MessageListener messageListener = new DefaultMessageListener(); private StateListener stateListener = new DefaultStateListener(); private PingThread pingThread; private ReadThread readThread; private Pdu bindPdu; private volatile long sequenceNumber = 0; private volatile long lastActivity; private volatile State state = State.DISCONNECTED; public BasicSession(Connection conn) { this.conn = conn; } public void setMessageListener(MessageListener messageListener) { this.messageListener = messageListener; } public void setStateListener(StateListener stateListener) { this.stateListener = stateListener; } public void setSmscResponseTimeout(int timeout) { this.smscResponseTimeout = timeout; } public void setEnquireLinkTimeout(int timeout) { this.pingTimeout = timeout; } public void setReconnectTimeout(int timeout) { this.reconnectTimeout = timeout; } public synchronized Pdu open(Pdu pdu) throws PduException, IOException { bindPdu = pdu; return open(); } @Override public synchronized long nextSequenceNumber() { if (sequenceNumber == 2147483647L) sequenceNumber = 1; else sequenceNumber++; return sequenceNumber; } @Override public synchronized boolean send(Pdu pdu) throws PduException { if (State.CONNECTED != state) return false; try { conn.write(pdu); return true; } catch (IOException e) { reconnect(e); return false; } } public synchronized void close() { if (State.RECONNECTING == state || closeInternal(null)) updateState(State.DISCONNECTED); } private synchronized Pdu open() throws PduException, IOException { logger.trace("Opening session."); conn.open(); logger.trace("TCP connection established. Sending bind request."); bindPdu.setSequenceNumber(nextSequenceNumber()); conn.write(bindPdu); ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor(); es.schedule(new Runnable() { @Override public void run() { logger.warn("Bind response timed out."); conn.close(); } }, smscResponseTimeout, TimeUnit.MILLISECONDS); logger.trace("Bind request sent. Waiting for bind response."); try { Pdu bindResp = conn.read(); es.shutdownNow(); logger.trace("Bind response command status: {}.", bindResp.getCommandStatus()); if (CommandStatus.ESME_ROK == bindResp.getCommandStatus()) { updateLastActivity(); pingThread = new PingThread(); pingThread.setName("Ping"); pingThread.start(); readThread = new ReadThread(); Thread t2 = new Thread(readThread); t2.setName("Read"); t2.start(); updateState(State.CONNECTED); logger.trace("Session successfully opened."); } return bindResp; } finally { if (!es.isShutdown()) es.shutdownNow(); } } /** * Actually close session. * * @param reason exception, caused session close, or null * @return session closed */ private synchronized boolean closeInternal(Exception reason) { if (State.DISCONNECTED != state) { logger.trace("Closing session..."); pingThread.stopAndInterrupt(); pingThread = null; if (!(reason instanceof IOException) && readThread.run) { try { synchronized (conn) { Pdu unbind = new Unbind(); unbind.setSequenceNumber(nextSequenceNumber()); send(unbind); conn.wait(smscResponseTimeout); } } catch (Exception e) { logger.debug("Unbind request send failed.", e); } } readThread.stop(); readThread = null; conn.close(); logger.trace("Session closed."); return true; } else { logger.trace("Session already closed."); return false; } } private void reconnect(Exception reason) { // only one thread should do reconnect boolean doReconnect = false; synchronized (state) { if (State.RECONNECTING != state) { doReconnect = true; state = State.RECONNECTING; } } if (doReconnect) { closeInternal(reason); updateState(State.RECONNECTING, reason); boolean reconnectSuccessful = false; while (!reconnectSuccessful && state == State.RECONNECTING) { try { Pdu bindResponse = open(); if (CommandStatus.ESME_ROK == bindResponse.getCommandStatus()) { reconnectSuccessful = true; } else { logger.warn("Reconnect failed. Bind response error code: {}.", bindResponse.getCommandStatus()); } } catch (Exception e) { logger.warn("Reconnect failed.", e); try { Thread.sleep(reconnectTimeout); } catch (InterruptedException e1) { logger.trace("Reconnect sleep interrupted.", e1); } } } if (reconnectSuccessful) state = State.CONNECTED; } } private void updateLastActivity() { lastActivity = System.currentTimeMillis(); } private void updateState(State newState) { updateState(newState, null); } private void updateState(State newState, Exception e) { this.state = newState; stateListener.changed(newState, e); } private class PingThread extends Thread { private volatile boolean run = true; @Override public void run() { logger.trace("Ping thread started."); try { while (run) { logger.trace("Checking last activity."); if (pingTimeout < (System.currentTimeMillis() - lastActivity)) { long prevLastActivity = lastActivity; Pdu enquireLink = new EnquireLink(); enquireLink.setSequenceNumber(nextSequenceNumber()); send(enquireLink); synchronized (conn) { conn.wait(smscResponseTimeout); } if (run && lastActivity == prevLastActivity) { reconnect(new IOException("Enquire link response not received. Session closed.")); break; } } logger.trace("Going to sleep {}", pingTimeout); Thread.sleep(pingTimeout); } } catch (PduException e) { if (run) { logger.warn("EnquireLink request failed.", e); run = false; reconnect(e); } } catch (InterruptedException e) { logger.trace("Ping thread interrupted."); } finally { logger.trace("Ping thread stopped."); } } void stopAndInterrupt() { run = false; interrupt(); } } private class ReadThread implements Runnable { private volatile boolean run = true; @Override public void run() { logger.trace("Read thread started."); try { while (run) { Pdu request = conn.read(); updateLastActivity(); Pdu response; if (CommandId.ENQUIRE_LINK == request.getCommandId()) { response = new EnquireLinkResp(); response.setSequenceNumber(request.getSequenceNumber()); send(response); } else if (CommandId.ENQUIRE_LINK_RESP == request.getCommandId()) { synchronized (conn) { conn.notifyAll(); } } else if (CommandId.UNBIND_RESP == request.getCommandId()) { synchronized (conn) { conn.notifyAll(); } stop(); } else { messageListener.received(request); } } } catch (PduException e) { if (run) { logger.warn("Incoming message parsing failed.", e); run = false; reconnect(e); } } catch (IOException e) { if (run) { logger.warn("Reading IO failure.", e); run = false; reconnect(e); } } finally { logger.trace("Read thread stopped."); } } void stop() { run = false; } } }
package org.digidoc4j.impl; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.util.List; import javax.security.auth.x500.X500Principal; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.digidoc4j.CertificateValidator; import org.digidoc4j.Configuration; import org.digidoc4j.exceptions.CertificateValidationException; import org.digidoc4j.exceptions.SignatureVerificationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import eu.europa.esig.dss.DSSUtils; import eu.europa.esig.dss.x509.CertificateSource; import eu.europa.esig.dss.x509.CertificateToken; import eu.europa.esig.dss.x509.crl.CRLReasonEnum; import eu.europa.esig.dss.x509.ocsp.OCSPSource; import eu.europa.esig.dss.x509.ocsp.OCSPToken; public class OCSPCertificateValidator implements CertificateValidator { private final Logger log = LoggerFactory.getLogger(OCSPCertificateValidator.class); private final Configuration configuration; private final CertificateSource certificateSource; private final OCSPSource ocspSource; /** * @param configuration configuration context * @param certificateSource the source of certificates * @param ocspSource the source of OCSP */ public OCSPCertificateValidator(Configuration configuration, CertificateSource certificateSource, OCSPSource ocspSource) { this.configuration = configuration; this.certificateSource = certificateSource; this.ocspSource = ocspSource; } @Override public void validate(X509Certificate subjectCertificate) throws CertificateValidationException { try { if (subjectCertificate == null) { throw new IllegalArgumentException("Subject certificate is not provided"); } this.verifyOCSPToken(this.ocspSource.getOCSPToken(new CertificateToken(subjectCertificate), this.getIssuerCertificateToken(subjectCertificate))); } catch (SignatureVerificationException e) { throw CertificateValidationException.of(CertificateValidationException.CertificateValidationStatus.UNTRUSTED, e); } catch (CertificateValidationException e) { throw e; } catch (Exception e) { throw CertificateValidationException.of(e); } } /* * RESTRICTED METHODS */ private CertificateToken getIssuerCertificateToken(X509Certificate certificate) throws CertificateEncodingException { CertificateToken certificateToken = null; try { certificateToken = DSSUtils.loadCertificate(certificate.getEncoded()); if (certificateToken.getIssuerX500Principal() != null) { return this.getFromCertificateSource(certificateToken.getIssuerX500Principal()); } } catch (IllegalStateException e) { this.log.warn("Certificate with DSS ID <{}> is untrusted. Not all the intermediate certificates added into OCSP" + " certificate source?", (certificateToken == null) ? certificate.getSubjectX500Principal().getName() : certificateToken .getDSSIdAsString(), e); } throw CertificateValidationException.of(CertificateValidationException.CertificateValidationStatus.UNTRUSTED); } private CertificateToken getFromCertificateSource(X500Principal principal) { List<CertificateToken> tokens = this.getCertificateTokens(principal); if (tokens.size() != 1) { throw new IllegalStateException(String.format("<%s> matching certificate tokens found from certificate source", tokens.size())); } return tokens.get(0); } private List<CertificateToken> getCertificateTokens(X500Principal principal) { List<CertificateToken> tokens = this.configuration.getTSL().get(principal); if (CollectionUtils.isEmpty(tokens)) { tokens = this.certificateSource.get(principal); } return tokens; } private void verifyOCSPToken(OCSPToken token) { if (token == null) { throw CertificateValidationException.of("No token response is present"); } try { if (token.getStatus() != null) { if (!token.getStatus()) { this.log.debug("Certificate with DSS ID <{}> - status <{}>", token.getDSSIdAsString(), CRLReasonEnum.valueOf(token.getReason()) .name()); throw CertificateValidationException.of(CertificateValidationException.CertificateValidationStatus.REVOKED); } // Otherwise status is GOOD return; } if (StringUtils.isNotBlank(token.getReason())) { this.log.debug("Certificate with DSS ID <{}> - status <{}>", token.getDSSIdAsString(), CRLReasonEnum.valueOf(token.getReason()) .name()); throw CertificateValidationException.of(CertificateValidationException.CertificateValidationStatus.UNKNOWN); } } catch (CertificateValidationException e) { throw e; } catch (Exception e) { throw CertificateValidationException.of(e); } } /* * ACCESSORS */ @Override public CertificateSource getCertificateSource() { return certificateSource; } }
package org.dungeon.achievements; import org.dungeon.date.Date; import org.dungeon.game.DungeonStringBuilder; import org.dungeon.game.Game; import org.dungeon.game.Id; import org.dungeon.io.Writer; import org.dungeon.logging.DungeonLogger; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; /** * AchievementTracker that tracks the unlocked achievements. */ public class AchievementTracker implements Serializable { private final Set<UnlockedAchievement> unlockedAchievements = new HashSet<UnlockedAchievement>(); /** * Writes an achievement unlocked message with some information about the unlocked achievement. */ private static void writeAchievementUnlock(Achievement achievement, DungeonStringBuilder builder) { String format = "You unlocked the achievement %s because you %s."; builder.append(String.format(format, achievement.getName(), achievement.getText())); } /** * Returns how many unlocked achievements there are in this AchievementTracker. * * @return how many unlocked achievements there are in this AchievementTracker */ public int getUnlockedCount() { return unlockedAchievements.size(); } /** * Unlock a specific Achievement. * * <p>If there already is an UnlockedAchievement with the same ID, a warning will be logged. * * @param achievement the Achievement to be unlocked. */ private void unlock(Achievement achievement, DungeonStringBuilder builder) { Date now = Game.getGameState().getWorld().getWorldDate(); if (!isUnlocked(achievement)) { writeAchievementUnlock(achievement, builder); unlockedAchievements.add(new UnlockedAchievement(achievement, now)); } else { DungeonLogger.warning("Tried to unlock an already unlocked achievement."); } } /** * Return the UnlockedAchievement object that corresponds to a specific Achievement. * * @param achievement an Achievement object. * @return the UnlockedAchievement that corresponds to this Achievement. */ private UnlockedAchievement getUnlockedAchievement(Achievement achievement) { Id id = achievement.getId(); for (UnlockedAchievement ua : unlockedAchievements) { if (ua.id.equals(id)) { return ua; } } return null; } /** * Returns a List with all the UnlockedAchievements in this AchievementTracker sorted using the provided Comparator. * * @param comparator a Comparator of UnlockedAchievements, not null * @return a sorted List with all the UnlockedAchievements in this AchievementTracker */ public List<UnlockedAchievement> getUnlockedAchievements(Comparator<UnlockedAchievement> comparator) { if (comparator == null) { throw new IllegalArgumentException("comparator is null."); } List<UnlockedAchievement> list = new ArrayList<UnlockedAchievement>(unlockedAchievements); Collections.sort(list, comparator); return list; } /** * Return true if a given Achievement is unlocked in this AchievementTracker. * * @param achievement an Achievement object. * @return true if this Achievement is unlocked, false otherwise. */ public boolean isUnlocked(Achievement achievement) { return getUnlockedAchievement(achievement) != null; } /** * Updates this AchievementTracker by iterating over the achievements and unlocking the ones that are fulfilled but * not yet added to the unlocked list of this tracker. * * <p>Before writing the first achievement unlock message, if there is one, a new line is written. */ public void update() { DungeonStringBuilder builder = new DungeonStringBuilder(); boolean wroteNewLine = false; // If we are going to write anything at all, we must start with a blank line. for (Achievement achievement : AchievementStore.getAchievements()) { if (!isUnlocked(achievement) && achievement.isFulfilled()) { if (!wroteNewLine) { builder.append("\n"); wroteNewLine = true; } unlock(achievement, builder); builder.append("\n"); } } Writer.write(builder); } }
package org.embulk.input.zendesk; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import org.apache.commons.io.FileUtils; import org.embulk.config.ConfigDiff; import org.embulk.config.ConfigException; import org.embulk.config.ConfigSource; import org.embulk.config.TaskReport; import org.embulk.config.TaskSource; import org.embulk.guess.csv.CsvGuessPlugin; import org.embulk.input.zendesk.models.AuthenticationMethod; import org.embulk.input.zendesk.models.Target; import org.embulk.input.zendesk.services.ZendeskChatService; import org.embulk.input.zendesk.services.ZendeskCustomObjectService; import org.embulk.input.zendesk.services.ZendeskNPSService; import org.embulk.input.zendesk.services.ZendeskService; import org.embulk.input.zendesk.services.ZendeskSupportAPIService; import org.embulk.input.zendesk.services.ZendeskUserEventService; import org.embulk.input.zendesk.utils.ZendeskConstants; import org.embulk.input.zendesk.utils.ZendeskDateUtils; import org.embulk.input.zendesk.utils.ZendeskUtils; import org.embulk.spi.Buffer; import org.embulk.spi.DataException; import org.embulk.spi.Exec; import org.embulk.spi.InputPlugin; import org.embulk.spi.PageBuilder; import org.embulk.spi.PageOutput; import org.embulk.spi.Schema; import org.embulk.spi.type.Types; import org.embulk.util.config.Config; import org.embulk.util.config.ConfigDefault; import org.embulk.util.config.ConfigMapper; import org.embulk.util.config.ConfigMapperFactory; import org.embulk.util.config.Task; import org.embulk.util.config.TaskMapper; import org.embulk.util.config.modules.ColumnModule; import org.embulk.util.config.modules.SchemaModule; import org.embulk.util.config.modules.TypeModule; import org.embulk.util.config.units.SchemaConfig; import org.embulk.util.guess.SchemaGuess; import org.json.CDL; import org.json.JSONArray; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.StreamSupport; public class ZendeskInputPlugin implements InputPlugin { public interface PluginTask extends Task { @Config("login_url") String getLoginUrl(); @Config("auth_method") @ConfigDefault("\"basic\"") AuthenticationMethod getAuthenticationMethod(); @Config("target") Target getTarget(); @Config("username") @ConfigDefault("null") Optional<String> getUsername(); @Config("password") @ConfigDefault("null") Optional<String> getPassword(); @Config("token") @ConfigDefault("null") Optional<String> getToken(); @Config("access_token") @ConfigDefault("null") Optional<String> getAccessToken(); @Config("start_time") @ConfigDefault("null") Optional<String> getStartTime(); @Min(1) @Max(30) @Config("retry_limit") @ConfigDefault("5") int getRetryLimit(); @Min(1) @Max(3600) @Config("retry_initial_wait_sec") @ConfigDefault("4") int getRetryInitialWaitSec(); @Min(30) @Max(3600) @Config("max_retry_wait_sec") @ConfigDefault("60") int getMaxRetryWaitSec(); @Config("incremental") @ConfigDefault("true") boolean getIncremental(); @Config("includes") @ConfigDefault("[]") List<String> getIncludes(); @Config("dedup") @ConfigDefault("true") boolean getDedup(); @Config("app_marketplace_integration_name") @ConfigDefault("null") Optional<String> getAppMarketPlaceIntegrationName(); @Config("app_marketplace_org_id") @ConfigDefault("null") Optional<String> getAppMarketPlaceOrgId(); @Config("app_marketplace_app_id") @ConfigDefault("null") Optional<String> getAppMarketPlaceAppId(); @Config("object_types") @ConfigDefault("[]") List<String> getObjectTypes(); @Config("relationship_types") @ConfigDefault("[]") List<String> getRelationshipTypes(); @Config("end_time") @ConfigDefault("null") Optional<String> getEndTime(); @Config("user_event_type") @ConfigDefault("null") Optional<String> getUserEventType(); @Config("user_event_source") @ConfigDefault("null") Optional<String> getUserEventSource(); @Config("columns") SchemaConfig getColumns(); } private ZendeskService zendeskService; private RecordImporter recordImporter; private static final Logger logger = LoggerFactory.getLogger(ZendeskInputPlugin.class); public static final ConfigMapperFactory CONFIG_MAPPER_FACTORY = ConfigMapperFactory.builder() .addDefaultModules() .addModule(new SchemaModule()) .addModule(new ColumnModule()) .addModule(new TypeModule()) .build(); public static final ConfigMapper CONFIG_MAPPER = CONFIG_MAPPER_FACTORY.createConfigMapper(); private static final TaskMapper TASK_MAPPER = CONFIG_MAPPER_FACTORY.createTaskMapper(); @Override public ConfigDiff transaction(final ConfigSource config, final Control control) { final PluginTask task = CONFIG_MAPPER.map(config, PluginTask.class); validateInputTask(task); final Schema schema = task.getColumns().toSchema(); int taskCount = 1; // For non-incremental target, we will split records based on number of pages. 100 records per page // In preview, run with taskCount = 1 if (!Exec.isPreview() && !getZendeskService(task).isSupportIncremental() && getZendeskService(task) instanceof ZendeskSupportAPIService) { final JsonNode result = getZendeskService(task).getDataFromPath("", 0, false, 0); if (result.has(ZendeskConstants.Field.COUNT) && !result.get(ZendeskConstants.Field.COUNT).isNull() && result.get(ZendeskConstants.Field.COUNT).isInt()) { taskCount = ZendeskUtils.numberToSplitWithHintingInTask(result.get(ZendeskConstants.Field.COUNT).asInt()); } } return resume(task.toTaskSource(), schema, taskCount, control); } @Override public ConfigDiff resume(final TaskSource taskSource, final Schema schema, final int taskCount, final Control control) { final PluginTask task = TASK_MAPPER.map(taskSource, PluginTask.class); final List<TaskReport> taskReports = control.run(taskSource, schema, taskCount); return this.buildConfigDiff(task, taskReports); } @Override public void cleanup(final TaskSource taskSource, final Schema schema, final int taskCount, final List<TaskReport> successTaskReports) { } @Override public TaskReport run(final TaskSource taskSource, final Schema schema, final int taskIndex, final PageOutput output) { final PluginTask task = TASK_MAPPER.map(taskSource, PluginTask.class); if (getZendeskService(task).isSupportIncremental() && !isValidTimeRange(task)) { if (Exec.isPreview()) { throw new ConfigException("Invalid End time. End time is greater than current time"); } logger.warn("The end time, '" + task.getEndTime().get() + "', is greater than the current time. No records will be imported"); // we just need to store config_diff when incremental_mode is enable if (task.getIncremental()) { return buildTaskReportKeepOldStartAndEndTime(task); } return Exec.newTaskReport(); } try (final PageBuilder pageBuilder = getPageBuilder(schema, output)) { final TaskReport taskReport = getZendeskService(task).addRecordToImporter(taskIndex, getRecordImporter(schema, pageBuilder)); pageBuilder.finish(); return taskReport; } } @Override public ConfigDiff guess(final ConfigSource config) { config.set("columns", new ObjectMapper().createArrayNode()); final PluginTask task = CONFIG_MAPPER.map(config, PluginTask.class); validateInputTask(task); if (!isValidTimeRange(task)) { throw new ConfigException("Invalid End time. End time is greater than current time"); } return Exec.newConfigDiff().set("columns", buildColumns(task)); } @VisibleForTesting protected PageBuilder getPageBuilder(final Schema schema, final PageOutput output) { return Exec.getPageBuilder(Exec.getBufferAllocator(), schema, output); } private ConfigDiff buildConfigDiff(final PluginTask task, final List<TaskReport> taskReports) { final ConfigDiff configDiff = Exec.newConfigDiff(); if (!taskReports.isEmpty() && task.getIncremental()) { final TaskReport taskReport = taskReports.get(0); if (taskReport.has(ZendeskConstants.Field.START_TIME)) { final OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(Instant.ofEpochSecond( taskReport.get(JsonNode.class, ZendeskConstants.Field.START_TIME).asLong()), ZoneOffset.UTC); configDiff.set(ZendeskConstants.Field.START_TIME, offsetDateTime.format(DateTimeFormatter.ofPattern(ZendeskConstants.Misc.RUBY_TIMESTAMP_FORMAT_INPUT))); } if (taskReport.has(ZendeskConstants.Field.END_TIME)) { final OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(Instant.ofEpochSecond( taskReport.get(JsonNode.class, ZendeskConstants.Field.END_TIME).asLong()), ZoneOffset.UTC); configDiff.set(ZendeskConstants.Field.END_TIME, offsetDateTime.format(DateTimeFormatter.ofPattern(ZendeskConstants.Misc.RUBY_TIMESTAMP_FORMAT_INPUT))); } } return configDiff; } private JsonNode buildColumns(final PluginTask task) { JsonNode jsonNode = getZendeskService(task).getDataFromPath("", 0, true, 0); String targetName = task.getTarget().getJsonName(); if (jsonNode.has(targetName) && !jsonNode.get(targetName).isNull() && jsonNode.get(targetName).isArray() && jsonNode.get(targetName).size() > 0) { return addAllColumnsToSchema(jsonNode, task.getTarget(), task.getIncludes()); } throw new ConfigException("Could not guess schema due to empty data set"); } private final Pattern idPattern = Pattern.compile(ZendeskConstants.Regex.ID); private JsonNode addAllColumnsToSchema(final JsonNode jsonNode, final Target target, final List<String> includes) { ConfigDiff configDiff = guessData(jsonNode, target.getJsonName()); ConfigDiff parser = configDiff.getNested("parser"); if (parser.has("columns")) { JsonNode columns = parser.get(JsonNode.class, "columns"); final Iterator<JsonNode> ite = columns.elements(); while (ite.hasNext()) { final ObjectNode entry = (ObjectNode) ite.next(); final String name = entry.get("name").asText(); final String type = entry.get("type").asText(); if (type.equals(Types.TIMESTAMP.getName())) { entry.put("format", ZendeskConstants.Misc.RUBY_TIMESTAMP_FORMAT); } if (name.equals("id")) { if (!type.equals(Types.LONG.getName())) { if (type.equals(Types.TIMESTAMP.getName())) { entry.remove("format"); } entry.put("type", Types.LONG.getName()); } // Id of User Events target is more suitable for String if (target.equals(Target.USER_EVENTS)) { entry.put("type", Types.STRING.getName()); } } else if (idPattern.matcher(name).find()) { if (type.equals(Types.TIMESTAMP.getName())) { entry.remove("format"); } entry.put("type", Types.STRING.getName()); } } addIncludedObjectsToSchema((ArrayNode) columns, includes); return columns; } else { throw new ConfigException("Fail to guess column"); } } @VisibleForTesting protected ConfigDiff guessData(final JsonNode jsonNode, final String targetJsonName) { List<String> unifiedFieldNames = unifiedFieldNames(jsonNode, targetJsonName); List<List<Object>> samples = createSampleData(jsonNode, targetJsonName, unifiedFieldNames); List<ConfigDiff> columnConfigs = SchemaGuess.of(CONFIG_MAPPER_FACTORY).fromListRecords(unifiedFieldNames, samples); if (columnConfigs.isEmpty()) { throw new ConfigException("Fail to guess column"); } columnConfigs.forEach(conf -> conf.remove("index")); ConfigDiff parserGuessed = CONFIG_MAPPER_FACTORY.newConfigDiff(); parserGuessed.set("columns", columnConfigs); ConfigDiff configDiff = CONFIG_MAPPER_FACTORY.newConfigDiff(); configDiff.setNested("parser", parserGuessed); return configDiff; } private List<List<Object>> createSampleData(JsonNode jsonNode, String targetJsonName, List<String> unifiedFieldNames) { final List<List<Object>> samples = new ArrayList<>(); Iterator<JsonNode> records = ZendeskUtils.getListRecords(jsonNode, targetJsonName); while (records.hasNext()) { JsonNode node = records.next(); List<Object> line = new ArrayList<>(); for (String field: unifiedFieldNames) { JsonNode childNode = node.get(field); if (childNode == null || childNode.isNull() || "null".equals(childNode.asText())) { line.add(null); continue; } if (childNode.isContainerNode()) { line.add(childNode); } else { line.add(childNode.asText()); } } samples.add(line); } return samples; } private List<String> unifiedFieldNames(JsonNode jsonNode, String targetJsonName) { List<String> columnNames = new ArrayList<>(); Iterator<JsonNode> records = ZendeskUtils.getListRecords(jsonNode, targetJsonName); while (records.hasNext()) { Iterator<String> fieldNames = records.next().fieldNames(); while (fieldNames.hasNext()) { String field = fieldNames.next(); if (!columnNames.contains(field)) { columnNames.add(field); } } } return columnNames; } /** * Method to read sample bytes of the csv file */ private byte[] readSampleBytes(String downloadedFilePath) { final int sampleBytes = 64000; final ByteArrayOutputStream bos = new ByteArrayOutputStream(sampleBytes); byte[] buffer = new byte[sampleBytes]; try (FileInputStream inputStream = new FileInputStream(downloadedFilePath)) { int read = inputStream.read(buffer, 0, sampleBytes); bos.write(buffer, 0, read); } catch (IOException e) { throw new DataException(e); } return bos.toByteArray(); } private void addIncludedObjectsToSchema(final ArrayNode arrayNode, final List<String> includes) { final ObjectMapper mapper = new ObjectMapper(); includes.stream() .map((include) -> mapper.createObjectNode() .put("name", include) .put("type", Types.JSON.getName())) .forEach(arrayNode::add); } private ConfigSource createGuessConfig() { return CONFIG_MAPPER_FACTORY.newConfigSource() .set("guess_plugins", ImmutableList.of("zendesk")) .set("guess_sample_buffer_bytes", ZendeskConstants.Misc.GUESS_BUFFER_SIZE); } private ZendeskService getZendeskService(PluginTask task) { if (zendeskService == null) { zendeskService = dispatchPerTarget(task); } return zendeskService; } @VisibleForTesting protected ZendeskService dispatchPerTarget(ZendeskInputPlugin.PluginTask task) { switch (task.getTarget()) { case TICKETS: case USERS: case ORGANIZATIONS: case TICKET_METRICS: case TICKET_EVENTS: case TICKET_FORMS: case TICKET_FIELDS: return new ZendeskSupportAPIService(task); case RECIPIENTS: case SCORES: return new ZendeskNPSService(task); case OBJECT_RECORDS: case RELATIONSHIP_RECORDS: return new ZendeskCustomObjectService(task); case USER_EVENTS: return new ZendeskUserEventService(task); case CHAT: return new ZendeskChatService(task); default: throw new ConfigException("Unsupported " + task.getTarget() + ", supported values: '" + Arrays.toString(Target.values()) + "'"); } } private RecordImporter getRecordImporter(Schema schema, PageBuilder pageBuilder) { if (recordImporter == null) { recordImporter = new RecordImporter(schema, pageBuilder); } return recordImporter; } private void validateInputTask(PluginTask task) { validateAppMarketPlace(task.getAppMarketPlaceIntegrationName().isPresent(), task.getAppMarketPlaceAppId().isPresent(), task.getAppMarketPlaceOrgId().isPresent()); validateCredentials(task); validateIncremental(task); validateCustomObject(task); validateUserEvent(task); validateTime(task); } private void validateCredentials(PluginTask task) { switch (task.getAuthenticationMethod()) { case OAUTH: if (!task.getAccessToken().isPresent()) { throw new ConfigException(String.format("access_token is required for authentication method '%s'", task.getAuthenticationMethod().name().toLowerCase())); } break; case TOKEN: if (!task.getUsername().isPresent() || !task.getToken().isPresent()) { throw new ConfigException(String.format("username and token are required for authentication method '%s'", task.getAuthenticationMethod().name().toLowerCase())); } break; case BASIC: if (!task.getUsername().isPresent() || !task.getPassword().isPresent()) { throw new ConfigException(String.format("username and password are required for authentication method '%s'", task.getAuthenticationMethod().name().toLowerCase())); } break; default: throw new ConfigException("Unknown authentication method"); } } private void validateAppMarketPlace(final boolean isAppMarketIntegrationNamePresent, final boolean isAppMarketAppIdPresent, final boolean isAppMarketOrgIdPresent) { final boolean isAllAvailable = isAppMarketIntegrationNamePresent && isAppMarketAppIdPresent && isAppMarketOrgIdPresent; final boolean isAllUnAvailable = !isAppMarketIntegrationNamePresent && !isAppMarketAppIdPresent && !isAppMarketOrgIdPresent; // All or nothing needed if (!(isAllAvailable || isAllUnAvailable)) { throw new ConfigException("All of app_marketplace_integration_name, app_marketplace_org_id, " + "app_marketplace_app_id " + "are required to fill out for Apps Marketplace API header"); } } private void validateIncremental(PluginTask task) { if (task.getIncremental() && getZendeskService(task).isSupportIncremental()) { if (!task.getDedup()) { logger.warn("You've selected to skip de-duplicating records, result may contain duplicated data"); } if (!getZendeskService(task).isSupportIncremental() && task.getStartTime().isPresent()) { logger.warn(String.format("Target: '%s' doesn't support incremental export API. Will be ignored start_time option", task.getTarget())); } } } private void validateCustomObject(PluginTask task) { if (task.getTarget().equals(Target.OBJECT_RECORDS) && task.getObjectTypes().isEmpty()) { throw new ConfigException("Should have at least one Object Type"); } if (task.getTarget().equals(Target.RELATIONSHIP_RECORDS) && task.getRelationshipTypes().isEmpty()) { throw new ConfigException("Should have at least one Relationship Type"); } } private void validateUserEvent(PluginTask task) { if (task.getTarget().equals(Target.USER_EVENTS)) { if (task.getUserEventType().isPresent() && !task.getUserEventSource().isPresent()) { throw new ConfigException("User Profile Source is required when filtering by User Event Type"); } } } private void validateTime(PluginTask task) { if (getZendeskService(task).isSupportIncremental()) { // Can't set end_time to 0, so it should be valid task.getEndTime().ifPresent(time -> { if (!ZendeskDateUtils.supportedTimeFormat(task.getEndTime().get()).isPresent()) { throw new ConfigException("End Time should follow these format " + ZendeskConstants.Misc.SUPPORT_DATE_TIME_FORMAT.toString()); } }); if (task.getStartTime().isPresent() && task.getEndTime().isPresent() && ZendeskDateUtils.getStartTime(task.getStartTime().get()) > ZendeskDateUtils.isoToEpochSecond(task.getEndTime().get())) { throw new ConfigException("End Time should be later or equal than Start Time"); } } } private boolean isValidTimeRange(PluginTask task) { return !task.getEndTime().isPresent() || ZendeskDateUtils.isoToEpochSecond(task.getEndTime().get()) <= Instant.now().getEpochSecond(); } private TaskReport buildTaskReportKeepOldStartAndEndTime(PluginTask task) { final TaskReport taskReport = Exec.newTaskReport(); if (task.getStartTime().isPresent()) { taskReport.set(ZendeskConstants.Field.START_TIME, ZendeskDateUtils.isoToEpochSecond(task.getStartTime().get())); } if (task.getEndTime().isPresent()) { taskReport.set(ZendeskConstants.Field.END_TIME, ZendeskDateUtils.isoToEpochSecond(task.getEndTime().get())); } return taskReport; } }
package org.jabref.logic.texparser; import java.io.IOException; import java.io.LineNumberReader; import java.io.UncheckedIOException; import java.nio.channels.ClosedChannelException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jabref.model.texparser.TexParser; import org.jabref.model.texparser.TexParserResult; import org.apache.tika.parser.txt.CharsetDetector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DefaultTexParser implements TexParser { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultTexParser.class); private static final String TEX_EXT = ".tex"; private static final String BIB_EXT = ".bib"; /** * It is allowed to add new cite commands for pattern matching. Some valid examples: "citep", "[cC]ite", and * "[cC]ite(author|title|year|t|p)?". */ private static final String[] CITE_COMMANDS = { "[cC]ite(alt|alp|author|authorfull|date|num|p|t|text|title|url|year|yearpar)?", "([aA]|[aA]uto|fnote|foot|footfull|full|no|[nN]ote|[pP]aren|[pP]note|[tT]ext|[sS]mart|super)cite", "footcitetext", "(block|text)cquote" }; private static final String CITE_GROUP = "key"; private static final Pattern CITE_PATTERN = Pattern.compile( String.format("\\\\(%s)\\*?(?:\\[(?:[^\\]]*)\\]){0,2}\\{(?<%s>[^\\}]*)\\}(?:\\{[^\\}]*\\})?", String.join("|", CITE_COMMANDS), CITE_GROUP)); private static final String BIBLIOGRAPHY_GROUP = "bib"; private static final Pattern BIBLIOGRAPHY_PATTERN = Pattern.compile( String.format("\\\\(?:bibliography|addbibresource)\\{(?<%s>[^\\}]*)\\}", BIBLIOGRAPHY_GROUP)); private static final String INCLUDE_GROUP = "file"; private static final Pattern INCLUDE_PATTERN = Pattern.compile( String.format("\\\\(?:include|input)\\{(?<%s>[^\\}]*)\\}", INCLUDE_GROUP)); private final TexParserResult texParserResult; public DefaultTexParser() { this.texParserResult = new TexParserResult(); } public TexParserResult getTexParserResult() { return texParserResult; } @Override public TexParserResult parse(String citeString) { matchCitation(Paths.get(""), 1, citeString); return texParserResult; } @Override public TexParserResult parse(Path texFile) { return parse(Collections.singletonList(texFile)); } @Override public TexParserResult parse(List<Path> texFiles) { texParserResult.addFiles(texFiles); List<Path> referencedFiles = new ArrayList<>(); for (Path file : texFiles) { if (!file.toFile().exists()) { LOGGER.error(String.format("File does not exist: %s", file)); continue; } try (LineNumberReader lineNumberReader = new LineNumberReader(new CharsetDetector().setText(Files.readAllBytes(file)).detect().getReader())) { for (String line = lineNumberReader.readLine(); line != null; line = lineNumberReader.readLine()) { // Skip comments and blank lines. if (line.trim().isEmpty() || line.trim().charAt(0) == '%') { continue; } matchCitation(file, lineNumberReader.getLineNumber(), line); matchBibFile(file, line); matchNestedFile(file, texFiles, referencedFiles, line); } } catch (ClosedChannelException e) { LOGGER.error("Parsing has been interrupted"); return null; } catch (IOException | UncheckedIOException e) { LOGGER.error("Error while parsing file {}", file, e); } } // Parse all files referenced by TEX files, recursively. if (!referencedFiles.isEmpty()) { parse(referencedFiles); } return texParserResult; } /** * Find cites along a specific line and store them. */ private void matchCitation(Path file, int lineNumber, String line) { Matcher citeMatch = CITE_PATTERN.matcher(line); while (citeMatch.find()) { for (String key : citeMatch.group(CITE_GROUP).split(",")) { texParserResult.addKey(key.trim(), file, lineNumber, citeMatch.start(), citeMatch.end(), line); } } } /** * Find BIB files along a specific line and store them. */ private void matchBibFile(Path file, String line) { Matcher bibliographyMatch = BIBLIOGRAPHY_PATTERN.matcher(line); while (bibliographyMatch.find()) { for (String bibString : bibliographyMatch.group(BIBLIOGRAPHY_GROUP).split(",")) { bibString = bibString.trim(); Path bibFile = file.getParent().resolve( bibString.endsWith(BIB_EXT) ? bibString : String.format("%s%s", bibString, BIB_EXT)); if (bibFile.toFile().exists()) { texParserResult.addBibFile(file, bibFile); } } } } /** * Find inputs and includes along a specific line and store them for parsing later. */ private void matchNestedFile(Path file, List<Path> texFiles, List<Path> referencedFiles, String line) { Matcher includeMatch = INCLUDE_PATTERN.matcher(line); while (includeMatch.find()) { String include = includeMatch.group(INCLUDE_GROUP); Path nestedFile = file.getParent().resolve( include.endsWith(TEX_EXT) ? include : String.format("%s%s", include, TEX_EXT)); if (nestedFile.toFile().exists() && !texFiles.contains(nestedFile)) { referencedFiles.add(nestedFile); } } } }
package edu.wustl.catissuecore.util; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import edu.common.dynamicextensions.bizlogic.BizLogicFactory; import edu.common.dynamicextensions.domain.AbstractMetadata; import edu.common.dynamicextensions.domain.integration.EntityMap; import edu.common.dynamicextensions.exception.DynamicExtensionsSystemException; import edu.wustl.catissuecore.bizlogic.AnnotationBizLogic; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.catissuecore.util.global.Utility; import edu.wustl.common.bizlogic.DefaultBizLogic; import edu.wustl.common.exception.BizLogicException; import edu.wustl.common.security.exceptions.UserNotAuthorizedException; import edu.wustl.common.util.dbManager.DAOException; /** * This class show/hides entities-forms mention in CSV file. * @author suhas_khot * */ public final class AssociatesForms { /* * create singleton object */ private static AssociatesForms associatForms= new AssociatesForms(); /* * private constructor */ private AssociatesForms() { } /* * returns single object */ public static AssociatesForms getInstance() { return associatForms; } /** * Map for storing containers corresponding to entitiesIds */ private static Map<Long, Long> entityIdsVsContainersId = new HashMap<Long, Long>(); /** * @param args stores command line user inputs * @throws DynamicExtensionsSystemException fails to validate * @throws DAOException if it fails to do database operation * @throws IOException if it fails to read file IO operation * @throws BizLogicException fails to get the instance of BizLogic * @throws UserNotAuthorizedException if user is not authorized to perform the operations */ public static void main(String[] args) throws DynamicExtensionsSystemException, IOException, DAOException, UserNotAuthorizedException, BizLogicException { //Validates arguments validateCSV(args); String filePath = args[0]; CSVFileParser csvFileParser = new CSVFileParser(filePath); //get EntityGroup with Collection Protocol along with corresponding entities csvFileParser.processCSV(); Long typeId = (Long) Utility.getObjectIdentifier(Constants.COLLECTION_PROTOCOL, AbstractMetadata.class.getName(), Constants.NAME); entityIdsVsContainersId = Utility.getAllContainers(csvFileParser.getEntityGroupIds()); disAssociateEntitiesAndForms(typeId); associateEntitiesForms(csvFileParser.getEntityIds(),typeId); associateEntitiesForms(csvFileParser.getFormIds(),typeId); } /** * @throws DynamicExtensionsSystemException fails to validate arguments * @param args filename */ private static void validateCSV(String[] args) throws DynamicExtensionsSystemException { if (args.length == 0) { throw new DynamicExtensionsSystemException("PLEASE SPECIFY THE PATH FOR .csv FILE"); } } /** * @param typeId type id of collection protocol * @throws DAOException if it fails to do database operation */ private static void disAssociateEntitiesAndForms(Long typeId) throws DAOException { DefaultBizLogic defaultBizLogic = BizLogicFactory.getDefaultBizLogic(); AnnotationBizLogic annotation = new AnnotationBizLogic(); Long cpId = Long.valueOf(0); for (Long containerId : entityIdsVsContainersId.values()) { if (containerId != null) { List<EntityMap> entityMapList = defaultBizLogic.retrieve(EntityMap.class.getName(), Constants.CONTAINERID, containerId); if (entityMapList != null && !entityMapList.isEmpty()) { EntityMap entityMap = entityMapList.get(0); Utility.editConditions(entityMap, cpId, typeId); annotation.updateEntityMap(entityMap); } } } } /** * @param entityIds entityIds collection * @throws DAOException if it fails to do database operation * @throws DynamicExtensionsSystemException * @throws UserNotAuthorizedException if user is not authorized to perform the operations * @throws BizLogicException fails to get the instance of BizLogic */ private static void associateEntitiesForms(List<Long> entityIds, Long typeId) throws DAOException, DynamicExtensionsSystemException, UserNotAuthorizedException, BizLogicException { AnnotationBizLogic annotation = new AnnotationBizLogic(); DefaultBizLogic defaultBizLogic = BizLogicFactory.getDefaultBizLogic(); Long conditionObject = Long.valueOf(-1); for (Long entityId : entityIds) { Long containerId = getContainerId(entityId); if (containerId == null) { throw new DynamicExtensionsSystemException( "This entity is not directly associated with the hook entity. Please enter proper entity in Show_Hide_Forms.csv file"); } else { List<EntityMap> entityMapList = defaultBizLogic.retrieve(EntityMap.class.getName(), Constants.CONTAINERID, containerId); if (entityMapList != null && !entityMapList.isEmpty()) { EntityMap entityMap = entityMapList.get(0); Utility.editConditions(entityMap, conditionObject, typeId); annotation.updateEntityMap(entityMap); } } } } /** * @param entityId to get corresponding containerId * @return containerId based on particular entityId */ private static Long getContainerId(Long entityId) { Long containerId = null; if (entityIdsVsContainersId != null && !entityIdsVsContainersId.isEmpty()) { for (Long entityIdFromMap : entityIdsVsContainersId.keySet()) { if (entityIdFromMap.equals(entityId)) { containerId = entityIdsVsContainersId.get(entityIdFromMap); } } } return containerId; } }
package org.minimalj.backend.sql; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Map.Entry; import org.minimalj.model.properties.PropertyInterface; import org.minimalj.util.IdUtils; import org.minimalj.util.LoggingRuntimeException; /** * Minimal-J internal * * - elements have own id * - Additional columns named parent and position */ public class ContainingSubTable<PARENT, ELEMENT> extends Table<ELEMENT> implements ListTable<PARENT, ELEMENT> { protected final String selectByParentAndPositionQuery; protected final String countQuery; protected final String nextPositionQuery; public ContainingSubTable(SqlPersistence sqlPersistence, String name, Class<ELEMENT> elementClass) { super(sqlPersistence, name, elementClass); selectByParentAndPositionQuery = selectByParentAndPositionQuery(); countQuery = countQuery(); nextPositionQuery = nextPositionQuery(); } @Override public List<ELEMENT> readAll(PARENT parent) { return new LazyList<PARENT, ELEMENT>(sqlPersistence, clazz, parent, getTableName()); } public int size(Object parentId) { try (PreparedStatement statement = createStatement(sqlPersistence.getConnection(), countQuery, false)) { statement.setObject(1, parentId); try (ResultSet resultSet = statement.executeQuery()) { resultSet.next(); return resultSet.getInt(1); } } catch (SQLException x) { throw new RuntimeException(x); } } protected int nextPosition(Object parentId) { try (PreparedStatement statement = createStatement(sqlPersistence.getConnection(), nextPositionQuery, false)) { statement.setObject(1, parentId); try (ResultSet resultSet = statement.executeQuery()) { resultSet.next(); return resultSet.getInt(1); } } catch (SQLException x) { throw new RuntimeException(x); } } public ELEMENT read(Object parentId, int position) { try (PreparedStatement statement = createStatement(sqlPersistence.getConnection(), selectByParentAndPositionQuery, false)) { statement.setObject(1, parentId); statement.setInt(2, position); ELEMENT object = executeSelect(statement); if (object != null) { IdUtils.setId(object, new ElementId(IdUtils.getId(object), getTableName(), position)); loadLists(object); } return object; } catch (SQLException x) { throw new LoggingRuntimeException(x, sqlLogger, "Couldn't read " + getTableName() + " with parent " + parentId + " on position " + position); } } private Object insertElement(PreparedStatement statement, ELEMENT element, Object parentId, int position) throws SQLException { Object elementId = IdUtils.getId(element); if (elementId == null) { elementId = IdUtils.createId(); IdUtils.setId(element, elementId); } int parameterPos = setParameters(statement, element, false, ParameterMode.INSERT, elementId); statement.setObject(parameterPos++, parentId); statement.setInt(parameterPos, position); statement.execute(); insertLists(element); return elementId; } public void add(Object parentId, ELEMENT element) { int position = nextPosition(parentId); try (PreparedStatement statement = createStatement(sqlPersistence.getConnection(), insertQuery, false)) { insertElement(statement, element, parentId, position); } catch (SQLException x) { throw new RuntimeException(x.getMessage()); } } public ELEMENT addElement(Object parentId, ELEMENT element) { int position = nextPosition(parentId); try (PreparedStatement statement = createStatement(sqlPersistence.getConnection(), insertQuery, false)) { Object elementId = insertElement(statement, element, parentId, position); element = read(elementId); IdUtils.setId(element, new ElementId(elementId, getTableName(), position)); return element; } catch (SQLException x) { throw new RuntimeException(x.getMessage()); } } @Override public void addAll(PARENT parent, List<ELEMENT> elements) { Object parentId = IdUtils.getId(parent); int position = nextPosition(parentId); try (PreparedStatement statement = createStatement(sqlPersistence.getConnection(), insertQuery, false)) { for (ELEMENT element : elements) { insertElement(statement, element, parentId, position++); } } catch (SQLException x) { throw new RuntimeException(x.getMessage()); } } public void update(ElementId id, ELEMENT object) { try (PreparedStatement updateStatement = createStatement(sqlPersistence.getConnection(), updateQuery, false)) { setParameters(updateStatement, object, false, ParameterMode.UPDATE, id.getId()); updateStatement.execute(); for (Entry<PropertyInterface, ListTable> listTableEntry : lists.entrySet()) { List list = (List) listTableEntry.getKey().getValue(object); listTableEntry.getValue().replaceAll(object, list); } } catch (SQLException x) { throw new LoggingRuntimeException(x, sqlLogger, "Couldn't update in " + getTableName() + " with " + object); } } @Override // TODO more efficient implementation. For the add - Transaction this is extremly bad implementation public void replaceAll(PARENT parent, List<ELEMENT> objects) { // TODO } // Queries protected String countQuery() { StringBuilder query = new StringBuilder(); query.append("SELECT COUNT(*) FROM ").append(getTableName()).append(" WHERE parent = ?"); return query.toString(); } protected String nextPositionQuery() { StringBuilder query = new StringBuilder(); query.append("SELECT MAX(position + 1) FROM ").append(getTableName()).append(" WHERE parent = ?"); return query.toString(); } protected String selectByParentAndPositionQuery() { StringBuilder query = new StringBuilder(); query.append("SELECT * FROM ").append(getTableName()).append(" WHERE parent = ? AND position = ?"); return query.toString(); } @Override protected String insertQuery() { StringBuilder s = new StringBuilder(); s.append("INSERT INTO ").append(getTableName()).append(" ("); for (Object columnNameObject : getColumns().keySet()) { // myst, direkt auf columnNames zugreiffen funktionert hier nicht String columnName = (String) columnNameObject; s.append(columnName).append(", "); } s.append("id, parent, position) VALUES ("); for (int i = 0; i<getColumns().size(); i++) { s.append("?, "); } s.append("?, ?, ?)"); return s.toString(); } @Override protected String updateQuery() { StringBuilder s = new StringBuilder(); s.append("UPDATE ").append(getTableName()).append(" SET "); for (Object columnNameObject : getColumns().keySet()) { s.append((String) columnNameObject).append("= ?, "); } s.delete(s.length()-2, s.length()); s.append(" WHERE id = ?"); return s.toString(); } @Override protected String deleteQuery() { return "DELETE FROM " + getTableName() + " WHERE id = ?"; } @Override protected void addSpecialColumns(SqlSyntax syntax, StringBuilder s) { syntax.addIdColumn(s, Object.class, 36); s.append(",\n parent CHAR(36) NOT NULL"); s.append(",\n position INTEGER NOT NULL"); } @Override protected void addPrimaryKey(SqlSyntax syntax, StringBuilder s) { syntax.addPrimaryKey(s, "id"); } }
package org.openforis.ceo.postgres; import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT; import static org.openforis.ceo.utils.DatabaseUtils.connect; import static org.openforis.ceo.utils.JsonUtils.expandResourcePath; import static org.openforis.ceo.utils.JsonUtils.parseJson; import static org.openforis.ceo.utils.JsonUtils.toStream; import static org.openforis.ceo.utils.PartUtils.partToString; import static org.openforis.ceo.utils.PartUtils.partsToJsonObject; import static org.openforis.ceo.utils.PartUtils.writeFilePart; import static org.openforis.ceo.utils.ProjectUtils.*; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import java.nio.file.Files; import java.nio.file.Paths; import java.sql.PreparedStatement; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.servlet.MultipartConfigElement; import javax.servlet.http.HttpServletResponse; import org.openforis.ceo.db_api.Projects; import spark.Request; import spark.Response; public class PostgresProjects implements Projects { private static JsonObject buildProjectJson(ResultSet rs) { var newProject = new JsonObject(); try { newProject.addProperty("id",rs.getInt("id")); newProject.addProperty("institution",rs.getInt("institution_id")); newProject.addProperty("availability",rs.getString("availability")); newProject.addProperty("name",rs.getString("name")); newProject.addProperty("description",rs.getString("description")); newProject.addProperty("privacyLevel",rs.getString("privacy_level")); newProject.addProperty("boundary",rs.getString("boundary")); newProject.addProperty("baseMapSource",rs.getString("base_map_source")); newProject.addProperty("plotDistribution",rs.getString("plot_distribution")); newProject.addProperty("numPlots",rs.getInt("num_plots")); newProject.addProperty("plotSpacing",rs.getDouble("plot_spacing")); newProject.addProperty("plotShape",rs.getString("plot_shape")); newProject.addProperty("plotSize",rs.getDouble("plot_size")); newProject.addProperty("archived", rs.getString("availability").equals("archived")); newProject.addProperty("sampleDistribution",rs.getString("sample_distribution")); newProject.addProperty("samplesPerPlot",rs.getInt("samples_per_plot")); newProject.addProperty("sampleResolution",rs.getDouble("sample_resolution")); newProject.addProperty("classification_times",""); newProject.add("sampleValues", parseJson(rs.getString("sample_survey")).getAsJsonArray()); newProject.addProperty("editable", false); } catch (SQLException e) { System.out.println(e.getMessage()); } return newProject; } private static String queryProjectGet(PreparedStatement pstmt) { var allProjects = new JsonArray(); try(var rs = pstmt.executeQuery()){ while(rs.next()) { allProjects.add(buildProjectJson(rs)); } } catch (SQLException e) { System.out.println(e.getMessage()); return "[]"; } return allProjects.toString(); } public String getAllProjects(Request req, Response res) { var userId = req.queryParams("userId"); var institutionId = req.queryParams("institutionId"); try (var conn = connect()) { if (userId == null || userId.isEmpty()) { if (institutionId == null || institutionId.isEmpty()) { try(var pstmt = conn.prepareStatement("SELECT * FROM select_all_projects()")) { return queryProjectGet(pstmt); } } else { try(var pstmt = conn.prepareStatement("SELECT * FROM select_all_institution_projects(?)")) { pstmt.setInt(1, Integer.parseInt(institutionId)); return queryProjectGet(pstmt); } } } else { if (institutionId == null || institutionId.isEmpty()) { try(var pstmt = conn.prepareStatement("SELECT * FROM select_all_user_projects(?)")) { pstmt.setInt(1, Integer.parseInt(userId)); return queryProjectGet(pstmt); } } else { try(var pstmt = conn.prepareStatement("SELECT * FROM select_institution_projects_with_roles(?,?)")) { pstmt.setInt(1, Integer.parseInt(userId)); pstmt.setInt(2, Integer.parseInt(institutionId)); return queryProjectGet(pstmt); } } } } catch (SQLException e) { System.out.println(e.getMessage()); return "[]"; } } private static String projectById(Integer projectId) { var project = new JsonObject(); try (var conn = connect(); var pstmt = conn.prepareStatement("SELECT * FROM select_project(?)")) { pstmt.setInt(1, projectId); try(var rs = pstmt.executeQuery()){ if(rs.next()) { return buildProjectJson(rs).toString(); } else { project.addProperty("id", 0); project.addProperty("institution",0); project.addProperty("availability", "nonexistent"); project.addProperty("name", ""); project.addProperty("description", ""); project.addProperty("privacyLevel", "public"); project.add("boundary", null); project.add("baseMapSource", null); project.addProperty("plotDistribution", "random"); project.add("numPlots", null); project.add("plotSpacing", null); project.addProperty("plotShape", "circle"); project.add("plotSize", null); project.addProperty("sampleDistribution", "random"); project.add("samplesPerPlot", null); project.add("sampleResolution", null); project.addProperty("archived", false); project.add("sampleValues", parseJson("[]").getAsJsonArray()); return project.toString(); } } } catch (SQLException e) { System.out.println(e.getMessage()); return ""; } } public String getProjectById(Request req, Response res) { var projectId = req.params(":id"); return projectById(Integer.parseInt(projectId)); } private static JsonObject buildPlotJson(ResultSet rs) { var singlePlot = new JsonObject(); try { singlePlot.addProperty("id",rs.getInt("id")); singlePlot.addProperty("projectId",rs.getInt("project_id")); singlePlot.addProperty("center",rs.getString("center")); singlePlot.addProperty("flagged",rs.getInt("flagged") == 0 ? false : true); singlePlot.addProperty("analyses",rs.getInt("assigned")); singlePlot.addProperty("user",rs.getString("username")); singlePlot.addProperty("confidence",rs.getInt("confidence")); singlePlot.addProperty("collection_time", rs.getString("collection_time")); singlePlot.addProperty("plotId",rs.getString("plotId")); singlePlot.addProperty("geom",rs.getString("geom")); } catch (SQLException e) { System.out.println(e.getMessage()); } return singlePlot; } public String getProjectPlots(Request req, Response res) { var projectId = req.params(":id"); var maxPlots = Integer.parseInt(req.params(":max")); try (var conn = connect(); var pstmt = conn.prepareStatement("SELECT * FROM select_project_plots(?,?)")) { var plots = new JsonArray(); pstmt.setInt(1,Integer.parseInt(projectId)); pstmt.setInt(2,maxPlots); try(var rs = pstmt.executeQuery()){ while (rs.next()) { // singlePlot.add("samples",getSampleJsonArray(singlePlot.get("id").getAsInt())); plots.add(buildPlotJson(rs)); } } return plots.toString(); } catch (SQLException e) { System.out.println(e.getMessage()); return ""; } } public String getProjectPlot(Request req, Response res) { var projectId = req.params(":project-id"); var plotId = req.params(":plot-id"); return ""; } private static JsonArray getSampleJsonArray(Integer plot_id, Integer proj_id) { try (var conn = connect(); var samplePstmt = conn.prepareStatement("SELECT * FROM select_plot_samples(?,?)")) { samplePstmt.setInt(1, plot_id); samplePstmt.setInt(2, proj_id); var samples = new JsonArray(); try(var sampleRs = samplePstmt.executeQuery()){ while (sampleRs.next()) { var sample = new JsonObject(); sample.addProperty("id", sampleRs.getString("id")); sample.addProperty("point", sampleRs.getString("point")); sample.addProperty("sampleId",sampleRs.getString("sampleId")); sample.addProperty("geom",sampleRs.getString("geom")); if (sampleRs.getString("value").length() > 2) sample.add("value", parseJson(sampleRs.getString("value")).getAsJsonObject()); samples.add(sample); } } return samples; } catch (SQLException e) { System.out.println(e.getMessage()); return new JsonArray(); } } public String getProjectStats(Request req, Response res) { var projectId = req.params(":id"); var stats = new JsonObject(); try (var conn = connect(); var pstmt = conn.prepareStatement("SELECT * FROM select_project_statistics(?)")) { pstmt.setInt(1,Integer.parseInt(projectId)); try(var rs = pstmt.executeQuery()){ if (rs.next()){ stats.addProperty("flaggedPlots",rs.getInt("flagged_plots")); stats.addProperty("analyzedPlots",rs.getInt("assigned_plots")); stats.addProperty("unanalyzedPlots",rs.getInt("unassigned_plots")); stats.addProperty("members",rs.getInt("members")); stats.addProperty("contributors",rs.getInt("contributors")); stats.addProperty("createdDate",rs.getString("created_date")); stats.addProperty("publishDate",rs.getString("published_date")); stats.addProperty("closeDate",rs.getString("closed_date")); stats.addProperty("archiveDate",rs.getString("archived_date")); } } return stats.toString(); } catch (SQLException e) { System.out.println(e.getMessage()); return ""; } } public String getUnassignedPlot(Request req, Response res) { var projectId = Integer.parseInt(req.params(":id")); var currentPlotId = Integer.parseInt(req.queryParamOrDefault("currentPlotId", "0")); try (var conn = connect(); var pstmt = conn.prepareStatement("SELECT * FROM select_unassigned_plot(?,?)")) { var singlePlot = new JsonObject(); pstmt.setInt(1,projectId); pstmt.setInt(2,currentPlotId); try(var rs = pstmt.executeQuery()){ if (rs.next()) { singlePlot = buildPlotJson(rs); singlePlot.add("samples",getSampleJsonArray(singlePlot.get("id").getAsInt(), projectId)); } } return singlePlot.toString(); } catch (SQLException e) { System.out.println(e.getMessage()); return ""; } } public String getUnassignedPlotById(Request req, Response res) { var projectId = Integer.parseInt(req.params(":projid")); var plotId = Integer.parseInt(req.params(":id")); try (var conn = connect(); var pstmt = conn.prepareStatement("SELECT * FROM select_unassigned_plots_by_plot_id(?,?)")) { var singlePlot = new JsonObject(); pstmt.setInt(1,projectId); pstmt.setInt(2,plotId); try(var rs = pstmt.executeQuery()){ if (rs.next()) { singlePlot = buildPlotJson(rs); singlePlot.add("samples",getSampleJsonArray(singlePlot.get("id").getAsInt(), projectId)); } } return singlePlot.toString(); } catch (SQLException e) { System.out.println(e.getMessage()); return ""; } } private static String valueOrBlank(String input) { return input == null || input.equals("null") ? "" : input; } private static ArrayList<String> getPlotHeaders(Connection conn, Integer projectId) { var plotHeaders = new ArrayList<String>(); try (var pstmt = conn.prepareStatement("SELECT * FROM get_plot_headers(?)")){ pstmt.setInt(1, projectId); try (var rs = pstmt.executeQuery()){ while (rs.next()) { if (!List.of("GID", "GEOM", "PLOT_GEOM").contains(rs.getString("column_names").toUpperCase())){ plotHeaders.add("plot_" + rs.getString("column_names")); } } } } catch (SQLException e) { System.out.println(e.getMessage()); } return plotHeaders; } private static ArrayList<String> getSampleHeaders(Connection conn, Integer projectId) { var sampleHeaders = new ArrayList<String>(); try (var pstmt = conn.prepareStatement("SELECT * FROM get_sample_headers(?)")){ pstmt.setInt(1, projectId); try (var rs = pstmt.executeQuery()){ while (rs.next()) { if (!List.of("GID", "GEOM", "LAT", "LON", "SAMPLE_GEOM").contains(rs.getString("column_names").toUpperCase())){ sampleHeaders.add("samples_" + rs.getString("column_names")); } } } } catch (SQLException e) { System.out.println(e.getMessage()); } return sampleHeaders; } public HttpServletResponse dumpProjectAggregateData(Request req, Response res) { var projectId = Integer.parseInt(req.params(":id")); try (var conn = connect(); var pstmt = conn.prepareStatement("SELECT * FROM select_project(?)")) { // check if project exists pstmt.setInt(1,projectId); try(var rs = pstmt.executeQuery()){ if (rs.next()) { var plotSummaries = new JsonArray(); var sampleValueGroups = parseJson(rs.getString("sample_survey")).getAsJsonArray(); var projectName = rs.getString("name").replace(" ", "-").replace(",", "").toLowerCase(); var plotHeaders = getPlotHeaders(conn, projectId); try(var pstmtDump = conn.prepareStatement("SELECT * FROM dump_project_plot_data(?)")){ pstmtDump.setInt(1, projectId); try(var rsDump = pstmtDump.executeQuery()){ while (rsDump.next()) { var plotSummary = new JsonObject(); plotSummary.addProperty("plot_id", rsDump.getString("plot_id")); plotSummary.addProperty("center_lon", rsDump.getString("lon")); plotSummary.addProperty("center_lat", rsDump.getString("lat")); plotSummary.addProperty("size_m", rsDump.getDouble("plot_size")); plotSummary.addProperty("shape", rsDump.getString("plot_shape")); plotSummary.addProperty("flagged", rsDump.getInt("flagged") > 0); plotSummary.addProperty("analyses", rsDump.getInt("assigned")); var samples = parseJson(rsDump.getString("samples")).getAsJsonArray(); plotSummary.addProperty("sample_points", samples.size()); plotSummary.addProperty("user_id", valueOrBlank(rsDump.getString("email"))); plotSummary.addProperty("analysis_duration", valueOrBlank(rsDump.getString("analysis_duration"))); plotSummary.addProperty("collection_time", valueOrBlank(rsDump.getString("collection_time"))); plotSummary.add("distribution", getValueDistribution(samples, getSampleValueTranslations(sampleValueGroups))); if (valueOrBlank(rsDump.getString("ext_plot_data")) != ""){ var ext_plot_data = parseJson(rsDump.getString("ext_plot_data")).getAsJsonObject(); plotHeaders.forEach(head -> plotSummary.addProperty("plot_" + head, getOrEmptyString(ext_plot_data, head).getAsString()) ); } plotSummaries.add(plotSummary); } } var compbinedHeaders = Arrays.stream(plotHeaders.toArray()) .map(head -> !head.toString().contains("plot_") ? "plot_" + head : head) .toArray(String[]::new); return outputAggregateCsv(res, sampleValueGroups, plotSummaries, projectName, compbinedHeaders); } } } } catch (SQLException e) { System.out.println(e.getMessage()); return res.raw(); } res.raw().setStatus(SC_NO_CONTENT); return res.raw(); } public HttpServletResponse dumpProjectRawData(Request req, Response res) { var projectId =Integer.parseInt( req.params(":id")); try (var conn = connect(); var pstmt = conn.prepareStatement("SELECT * FROM select_project(?)")) { // check if project exists pstmt.setInt(1,projectId); try(var rs = pstmt.executeQuery()){ if (rs.next()) { var sampleSummaries = new JsonArray(); var sampleValueGroups = parseJson(rs.getString("sample_survey")).getAsJsonArray(); var projectName = rs.getString("name").replace(" ", "-").replace(",", "").toLowerCase(); var plotHeaders = getPlotHeaders(conn, projectId); var sampleHeaders = getSampleHeaders(conn, projectId); try(var pstmtDump = conn.prepareStatement("SELECT * FROM dump_project_sample_data(?)")){ pstmtDump.setInt(1, projectId); try(var rsDump = pstmtDump.executeQuery()){ while (rsDump.next()) { var plotSummary = new JsonObject(); plotSummary.addProperty("plot_id", rsDump.getString("plot_id")); plotSummary.addProperty("sample_id", rsDump.getString("sample_id")); plotSummary.addProperty("lon", rsDump.getString("lon")); plotSummary.addProperty("lat", rsDump.getString("lat")); plotSummary.addProperty("flagged", rsDump.getInt("flagged") > 0); plotSummary.addProperty("analyses", rsDump.getInt("assigned")); plotSummary.addProperty("user_id", valueOrBlank(rsDump.getString("email"))); plotSummary.addProperty("analysis_duration", valueOrBlank(rsDump.getString("analysis_duration"))); plotSummary.addProperty("collection_time", valueOrBlank(rsDump.getString("collection_time"))); if (rsDump.getString("value") != null && parseJson(rsDump.getString("value")).isJsonPrimitive()) { plotSummary.addProperty("value", rsDump.getString("value")); } else { plotSummary.add("value", rsDump.getString("value") == null ? null : parseJson(rsDump.getString("value")).getAsJsonObject()); } if (valueOrBlank(rsDump.getString("imagery_title")) != "") { plotSummary.addProperty("imagery_title", rsDump.getString("imagery_title")); if (!sampleHeaders.contains("imagery_title")) sampleHeaders.add("imagery_title"); if (valueOrBlank(rsDump.getString("imagery_attributes")).length() > 2) { var attributes = parseJson(rsDump.getString("imagery_attributes")).getAsJsonObject(); attributes.keySet().forEach(key -> { plotSummary.addProperty(key, attributes.get(key).getAsString()); if (!sampleHeaders.contains(key)) sampleHeaders.add(key); }); } } if (valueOrBlank(rsDump.getString("ext_plot_data")) != ""){ var ext_plot_data = parseJson(rsDump.getString("ext_plot_data")).getAsJsonObject(); plotHeaders.forEach(head -> plotSummary.addProperty("plot_" + head, getOrEmptyString(ext_plot_data, head).getAsString()) ); } if (valueOrBlank(rsDump.getString("ext_sample_data")) != ""){ var ext_sample_data = parseJson(rsDump.getString("ext_sample_data")).getAsJsonObject(); sampleHeaders.forEach(head -> plotSummary.addProperty("sample_" + head, getOrEmptyString(ext_sample_data, head).getAsString()) ); } sampleSummaries.add(plotSummary); } } // json object has plot_ or sample_ appended to differenciate var compbinedHeaders = Stream.concat( Arrays.stream(plotHeaders.toArray()), Arrays.stream(sampleHeaders.toArray()) ).toArray(String[]::new); return outputRawCsv(res, sampleValueGroups, sampleSummaries, projectName, compbinedHeaders); } } } } catch (SQLException e) { System.out.println(e.getMessage()); return res.raw(); } res.raw().setStatus(SC_NO_CONTENT); return res.raw(); } public String publishProject(Request req, Response res) { var projectId = req.params(":id"); try (var conn = connect(); var pstmt = conn.prepareStatement("SELECT * FROM publish_project(?)")) { pstmt.setInt(1,Integer.parseInt(projectId)); try(var rs = pstmt.executeQuery()){ var idReturn = 0; if (rs.next()) { idReturn = rs.getInt("publish_project"); } return projectById(idReturn); } } catch (SQLException e) { System.out.println(e.getMessage()); return ""; } } public String closeProject(Request req, Response res) { var projectId = req.params(":id"); try (var conn = connect(); var pstmt = conn.prepareStatement("SELECT * FROM close_project(?)")) { pstmt.setInt(1,Integer.parseInt(projectId)); try(var rs = pstmt.executeQuery()){ var idReturn = 0; if (rs.next()) { idReturn = rs.getInt("close_project"); } return projectById(idReturn); } } catch (SQLException e) { System.out.println(e.getMessage()); return ""; } } public String archiveProject(Request req, Response res) { var projectId = req.params(":id"); try (var conn = connect(); var pstmt = conn.prepareStatement("SELECT * FROM archive_project(?)") ;) { pstmt.setInt(1,Integer.parseInt(projectId)); try(var rs = pstmt.executeQuery()){ var idReturn = 0; if (rs.next()) { idReturn = rs.getInt("archive_project"); } return projectById(idReturn); } } catch (SQLException e) { System.out.println(e.getMessage()); return ""; } } public String addUserSamples(Request req, Response res) { var jsonInputs = parseJson(req.body()).getAsJsonObject(); var projectId = jsonInputs.get("projectId").getAsString(); var plotId = jsonInputs.get("plotId").getAsString(); var userName = jsonInputs.get("userId").getAsString(); var confidence = jsonInputs.get("confidence").getAsInt(); var collectionStart = jsonInputs.get("collectionStart").getAsString(); var userSamples = jsonInputs.get("userSamples").getAsJsonObject(); var userImages = jsonInputs.get("userImages").getAsJsonObject(); try (var conn = connect(); var userPstmt = conn.prepareStatement("SELECT * FROM get_user(?)")) { userPstmt.setString(1, userName); try(var userRs = userPstmt.executeQuery()){ if (userRs.next()){ var userId = userRs.getInt("id"); var SQL = "SELECT * FROM add_user_samples(?,?,?,?::int,?::timestamp,?::jsonb,?::jsonb)"; var pstmt = conn.prepareStatement(SQL) ; pstmt.setInt(1, Integer.parseInt(projectId)); pstmt.setInt(2, Integer.parseInt(plotId)); pstmt.setInt(3, userId); pstmt.setString(4, confidence == -1 ? null : Integer.toString(confidence)); pstmt.setTimestamp(5, new Timestamp(Long.parseLong(collectionStart))); pstmt.setString(6, userSamples.toString()); pstmt.setString(7, userImages.toString()); pstmt.execute(); return plotId; } return ""; } } catch (SQLException e) { System.out.println(e.getMessage()); return ""; } } public String flagPlot(Request req, Response res) { var jsonInputs = parseJson(req.body()).getAsJsonObject(); var plotId = jsonInputs.get("plotId").getAsString(); var userName = jsonInputs.get("userId").getAsString(); try (var conn = connect(); var pstmt = conn.prepareStatement("SELECT * FROM flag_plot(?,?,?::int)")) { pstmt.setInt(1,Integer.parseInt(plotId)); pstmt.setString(2,userName); pstmt.setString(3,null); //confidence try(var rs = pstmt.executeQuery()){ var idReturn = 0; if (rs.next()) { idReturn = rs.getInt("flag_plot"); } return Integer.toString(idReturn); } } catch (SQLException e) { System.out.println(e.getMessage()); return ""; } } private static String loadCsvHeaders(String filename) { try (var lines = Files.lines(Paths.get(expandResourcePath("/csv/" + filename)))) { var fields = Arrays.stream( lines.findFirst().orElse("").split(",")) .map(col -> { if (List.of("LON", "LAT").contains(col.toUpperCase())) { return col + " float"; } return col + " text"; }) .collect(Collectors.joining(",")); return fields; } catch (Exception e) { throw new RuntimeException("Malformed plot CSV. Fields must be LON,LAT,PLOTID."); } } private static void deleteFile(String csvFile) { var csvFilePath = Paths.get(expandResourcePath("/csv"), csvFile); try { if (csvFilePath.toFile().exists()) { // System.out.println("Deleting file: " + csvFilePath); Files.delete(csvFilePath); } else { // System.out.println("No file found: " + csvFilePath); } } catch (Exception e) { System.out.println("Error deleting directory at: " + csvFilePath); } } private static void deleteFiles(int projectId) { deleteFile("project-" + projectId + "-plots.csv"); deleteFile("project-" + projectId + "-samples.csv"); deleteFile("project-" + projectId + "-plots.zip"); deleteFile("project-" + projectId + "-samples.zip"); } private static String loadPlots(Connection conn, String plotDistribution, Integer projectId, String plotsFile) { try { if (plotDistribution.equals("csv")) { var plots_table = "project_" + projectId + "_plots_csv"; // add emptye table to the database try(var pstmt = conn.prepareStatement("SELECT * FROM create_new_table(?,?)")){ pstmt.setString(1, plots_table); pstmt.setString(2, loadCsvHeaders(plotsFile)); pstmt.execute(); } // import csv file runBashScriptForProject(projectId, "plots", "csv2postgres.sh", "/csv"); // add index for reference try(var pstmt = conn.prepareStatement("SELECT * FROM add_index_col(?)")){ pstmt.setString(1,plots_table); pstmt.execute(); } return plots_table; } if (plotDistribution.equals("shp")) { runBashScriptForProject(projectId, "plots", "shp2postgres.sh", "/shp"); return "project_" + projectId + "_plots_shp"; } } catch (SQLException e) { System.out.println(e.getMessage()); } return null; } private static String loadSamples(Connection conn, String sampleDistribution, Integer projectId, String samplesFile) { try { if (sampleDistribution.equals("csv")) { var samples_table = "project_" + projectId + "_samples_csv"; // create new table try(var pstmt = conn.prepareStatement("SELECT * FROM create_new_table(?,?)")){ pstmt.setString(1,samples_table); pstmt.setString(2, loadCsvHeaders(samplesFile)); pstmt.execute(); } // fill table runBashScriptForProject(projectId, "samples", "csv2postgres.sh", "/csv"); // add index for reference try(var pstmt = conn.prepareStatement("SELECT * FROM add_index_col(?)")){ pstmt.setString(1,"project_" + projectId + "_samples_csv"); pstmt.execute(); } return samples_table; } if (sampleDistribution.equals("shp")) { runBashScriptForProject(projectId, "samples", "shp2postgres.sh", "/shp"); return "project_" + projectId + "_samples_shp"; } } catch (SQLException e) { System.out.println(e.getMessage()); } return null; } private static void createProjectPlots(JsonObject newProject) { // Store the parameters needed for plot generation in local variables with nulls set to 0 var projectId = newProject.get("id").getAsInt(); var lonMin = getOrZero(newProject,"lonMin").getAsDouble(); var latMin = getOrZero(newProject,"latMin").getAsDouble(); var lonMax = getOrZero(newProject,"lonMax").getAsDouble(); var latMax = getOrZero(newProject,"latMax").getAsDouble(); var plotDistribution = getOrEmptyString(newProject, "plotDistribution").getAsString(); var numPlots = getOrZero(newProject,"numPlots").getAsInt(); var plotSpacing = getOrZero(newProject,"plotSpacing").getAsDouble(); var plotShape = getOrEmptyString(newProject,"plotShape").getAsString(); var plotSize = getOrZero(newProject,"plotSize").getAsDouble(); var sampleDistribution = getOrEmptyString(newProject, "sampleDistribution").getAsString(); var samplesPerPlot = getOrZero(newProject,"samplesPerPlot").getAsInt(); var sampleResolution = getOrZero(newProject,"sampleResolution").getAsDouble(); var plotsFile = newProject.has("plots_file") ? newProject.get("plots_file").getAsString() : ""; var samplesFile = newProject.has("samples_file") ? newProject.get("samples_file").getAsString() : ""; try (var conn = connect()) { // load files into the database (loadPlot, loadSamples) and update projects try (var pstmt = conn.prepareStatement("SELECT * FROM update_project_tables(?,?::text,?::text)")) { pstmt.setInt(1, projectId); pstmt.setString(2, loadPlots(conn, plotDistribution, projectId, plotsFile)); pstmt.setString(3, loadSamples(conn, sampleDistribution, projectId, samplesFile)); pstmt.execute(); } try (var pstmt = conn.prepareStatement("SELECT * FROM cleanup_project_tables(?,?)")) { pstmt.setInt(1, projectId); pstmt.setDouble(2, plotSize); pstmt.execute(); } // if both are files, adding plots and samples is done inside PG if (List.of("csv", "shp").contains(plotDistribution) && List.of("csv", "shp").contains(sampleDistribution)) { try (var pstmt = conn.prepareStatement("SELECT * FROM samples_from_plots_with_files(?)")) { pstmt.setInt(1, projectId); pstmt.execute(); } // Add plots from file and use returned plot ID to create samples } else if (List.of("csv", "shp").contains(plotDistribution)) { try (var pstmt = conn.prepareStatement("SELECT * FROM add_file_plots(?)")) { pstmt.setInt(1,projectId); try (var rs = pstmt.executeQuery()) { while (rs.next()){ var plotCenter = new Double[] {rs.getDouble("lon"), rs.getDouble("lat")}; createProjectSamples(conn, rs.getInt("id"), sampleDistribution, plotCenter, plotShape, plotSize, samplesPerPlot, sampleResolution, plotDistribution.equals("shp")); } } } } else { // Convert the lat/lon boundary coordinates to Web Mercator (units: meters) and apply an interior buffer of plotSize / 2 var bounds = reprojectBounds(lonMin, latMin, lonMax, latMax, 4326, 3857); var paddedBounds = padBounds(bounds[0], bounds[1], bounds[2], bounds[3], plotSize / 2.0); var left = paddedBounds[0]; var bottom = paddedBounds[1]; var right = paddedBounds[2]; var top = paddedBounds[3]; // Generate the plot objects and their associated sample points var newPlotCenters = plotDistribution.equals("random") ? createRandomPointsInBounds(left, bottom, right, top, numPlots) : createGriddedPointsInBounds(left, bottom, right, top, plotSpacing); Arrays.stream(newPlotCenters) .forEach(plotEntry -> { var plotCenter = (Double[]) plotEntry; var SqlPlots = "SELECT * FROM create_project_plot(?,ST_SetSRID(ST_GeomFromGeoJSON(?), 4326))"; try(var pstmtPlots = conn.prepareStatement(SqlPlots)) { pstmtPlots.setInt(1, projectId); pstmtPlots.setString(2, makeGeoJsonPoint(plotCenter[0], plotCenter[1]).toString()); try(var rsPlots = pstmtPlots.executeQuery()){ if (rsPlots.next()) { var newPlotId = rsPlots.getInt("create_project_plot"); createProjectSamples(conn, newPlotId, sampleDistribution, plotCenter, plotShape, plotSize, samplesPerPlot, sampleResolution, false); } } } catch (SQLException e) { System.out.println(e.getMessage()); } }); } // Update numPlots and samplesPerPlot to match the numbers that were generated try (var pstmt = conn.prepareStatement("SELECT * FROM update_project_counts(?)")) { pstmt.setInt(1, projectId); pstmt.execute(); } } catch (SQLException e) { System.out.println(e.getMessage()); } } private static void createProjectSamples(Connection conn, Integer newPlotId, String sampleDistribution, Double[] plotCenter, String plotShape, Double plotSize, Integer samplesPerPlot, Double sampleResolution, Boolean isShp) { var newSamplePoints = isShp || !List.of("random", "gridded").contains(sampleDistribution) ? new Double[][]{plotCenter} : sampleDistribution.equals("random") ? createRandomSampleSet(plotCenter, plotShape, plotSize, samplesPerPlot) : createGriddedSampleSet(plotCenter, plotShape, plotSize, sampleResolution); Arrays.stream(newSamplePoints) .forEach(sampleEntry -> { var SqlSamples = "SELECT * FROM create_project_plot_sample(?,ST_SetSRID(ST_GeomFromGeoJSON(?), 4326))"; var sampleCenter = (Double[]) sampleEntry; try (var pstmtSamples = conn.prepareStatement(SqlSamples)) { pstmtSamples.setInt(1, newPlotId); pstmtSamples.setString(2,makeGeoJsonPoint(sampleCenter[0], sampleCenter[1]).toString()); pstmtSamples.execute(); } catch (SQLException e) { System.out.println(e.getMessage()); } }); } public String createProject(Request req, Response res) { try { // Create a new multipart config for the servlet // NOTE: This is for Jetty. Under Tomcat, this is handled in the webapp/META-INF/context.xml file. req.raw().setAttribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement("")); // Read the input fields into a new JsonObject (NOTE: fields will be camelCased) var newProject = partsToJsonObject(req, new String[]{"institution", "privacy-level", "lon-min", "lon-max", "lat-min", "lat-max", "base-map-source", "plot-distribution", "num-plots", "plot-spacing", "plot-shape", "plot-size", "sample-distribution", "samples-per-plot", "sample-resolution", "sample-values", "classification_times", "project-template", "use-template-plots"}); // Manually add the name and description fields since they may be invalid JSON newProject.addProperty("name", partToString(req.raw().getPart("name"))); newProject.addProperty("description", partToString(req.raw().getPart("description"))); newProject.addProperty("availability", "unpublished"); var lonMin = getOrZero(newProject,"lonMin").getAsDouble(); var latMin = getOrZero(newProject,"latMin").getAsDouble(); var lonMax = getOrZero(newProject,"lonMax").getAsDouble(); var latMax = getOrZero(newProject,"latMax").getAsDouble(); newProject.addProperty("boundary", makeGeoJsonPolygon(lonMin, latMin, lonMax, latMax).toString()); var SQL = "SELECT * FROM create_project(?,?,?,?,?,ST_SetSRID(ST_GeomFromGeoJSON(?), 4326),?,?,?,?,?,?,?,?,?,?::JSONB,?::jsonb)"; try (var conn = connect(); var pstmt = conn.prepareStatement(SQL)) { pstmt.setInt(1,newProject.get("institution").getAsInt()); pstmt.setString(2 ,newProject.get("availability").getAsString()); pstmt.setString(3,newProject.get("name").getAsString()); pstmt.setString(4, newProject.get("description").getAsString()); pstmt.setString(5, newProject.get("privacyLevel").getAsString()); pstmt.setString(6, newProject.get("boundary").getAsString()); pstmt.setString(7, getOrEmptyString(newProject, "baseMapSource").getAsString()); pstmt.setString(8, getOrEmptyString(newProject, "plotDistribution").getAsString()); pstmt.setInt(9, getOrZero(newProject, "numPlots").getAsInt()); pstmt.setDouble(10, getOrZero(newProject, "plotSpacing").getAsDouble()); pstmt.setString(11, getOrEmptyString(newProject, "plotShape").getAsString()); pstmt.setDouble(12, getOrZero(newProject, "plotSize").getAsDouble()); pstmt.setString(13, getOrEmptyString(newProject, "sampleDistribution").getAsString()); pstmt.setInt(14, getOrZero(newProject, "samplesPerPlot").getAsInt()); pstmt.setDouble(15, getOrZero(newProject, "sampleResolution").getAsDouble()); pstmt.setString(16, newProject.get("sampleValues").getAsJsonArray().toString()); pstmt.setString(17, null); //classification times try(var rs = pstmt.executeQuery()){ var newProjectId = ""; if (rs.next()){ newProjectId = Integer.toString(rs.getInt("create_project")); newProject.addProperty("id", newProjectId); if (getOrZero(newProject, "useTemplatePlots").getAsBoolean()) { try(var copyPstmt = conn.prepareStatement("SELECT * FROM copy_template_plots(?,?)")){ copyPstmt.setInt(1, newProject.get("projectTemplate").getAsInt()); copyPstmt.setInt(2, Integer.parseInt(newProjectId)); copyPstmt.execute(); } } else { // Upload the plot-distribution-csv-file if one was provided // not stored in database if (newProject.get("plotDistribution").getAsString().equals("csv")) { var csvFileName = writeFilePart(req, "plot-distribution-csv-file", expandResourcePath("/csv"), "project-" + newProjectId + "-plots"); newProject.addProperty("plots_file", csvFileName); } // Upload the sample-distribution-csv-file if one was provided if (newProject.get("sampleDistribution").getAsString().equals("csv")) { var csvFileName = writeFilePart(req, "sample-distribution-csv-file", expandResourcePath("/csv"), "project-" + newProjectId + "-samples"); newProject.addProperty("samples_file", csvFileName); } // Upload the plot-distribution-shp-file if one was provided (this should be a ZIP file) if (newProject.get("plotDistribution").getAsString().equals("shp")) { var shpFileName = writeFilePart(req, "plot-distribution-shp-file", expandResourcePath("/shp"), "project-" + newProjectId + "-plots"); newProject.addProperty("plots_file", shpFileName); } // Upload the sample-distribution-shp-file if one was provided (this should be a ZIP file) if (newProject.get("sampleDistribution").getAsString().equals("shp")) { var shpFileName = writeFilePart(req, "sample-distribution-shp-file", expandResourcePath("/shp"), "project-" + newProjectId + "-samples"); newProject.addProperty("samples_file", shpFileName); } // Create the requested plot set and write it to plot-data-<newProjectId>.json createProjectPlots(newProject); deleteFiles(Integer.parseInt(newProjectId)); deleteShapeFileDirectories(Integer.parseInt(newProjectId)); } } // Indicate that the project was created successfully return newProjectId; } } catch (SQLException e) { System.out.println(e.getMessage()); // Indicate that an error occurred with project creation throw new RuntimeException(e); } } catch (Exception e) { // Indicate that an error occurred with project creation throw new RuntimeException(e); } } }
package org.sagebionetworks.web.client; import static org.sagebionetworks.web.client.ClientProperties.DEFAULT_PLACE_TOKEN; import static org.sagebionetworks.web.client.ClientProperties.GB; import static org.sagebionetworks.web.client.ClientProperties.IMAGE_CONTENT_TYPES_SET; import static org.sagebionetworks.web.client.ClientProperties.KB; import static org.sagebionetworks.web.client.ClientProperties.MB; import static org.sagebionetworks.web.client.ClientProperties.STYLE_DISPLAY_INLINE; import static org.sagebionetworks.web.client.ClientProperties.TABLE_CONTENT_TYPES_SET; import static org.sagebionetworks.web.client.ClientProperties.TB; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.gwtbootstrap3.client.ui.Button; import org.gwtbootstrap3.client.ui.Icon; import org.gwtbootstrap3.client.ui.Modal; import org.gwtbootstrap3.client.ui.ModalBody; import org.gwtbootstrap3.client.ui.ModalFooter; import org.gwtbootstrap3.client.ui.ModalSize; import org.gwtbootstrap3.client.ui.Popover; import org.gwtbootstrap3.client.ui.Tooltip; import org.gwtbootstrap3.client.ui.constants.IconType; import org.gwtbootstrap3.client.ui.constants.Placement; import org.gwtbootstrap3.client.ui.constants.Pull; import org.gwtbootstrap3.client.ui.constants.Trigger; import org.gwtbootstrap3.client.ui.html.Div; import org.gwtbootstrap3.extras.bootbox.client.Bootbox; import org.gwtbootstrap3.extras.bootbox.client.callback.AlertCallback; import org.gwtbootstrap3.extras.bootbox.client.callback.ConfirmCallback; import org.gwtbootstrap3.extras.notify.client.constants.NotifyType; import org.gwtbootstrap3.extras.notify.client.ui.Notify; import org.gwtbootstrap3.extras.notify.client.ui.NotifySettings; import org.sagebionetworks.gwt.client.schema.adapter.DateUtils; import org.sagebionetworks.repo.model.EntityBundle; import org.sagebionetworks.repo.model.EntityHeader; import org.sagebionetworks.repo.model.EntityPath; import org.sagebionetworks.repo.model.FileEntity; import org.sagebionetworks.repo.model.Project; import org.sagebionetworks.repo.model.Reference; import org.sagebionetworks.repo.model.UserGroupHeader; import org.sagebionetworks.repo.model.UserProfile; import org.sagebionetworks.repo.model.Versionable; import org.sagebionetworks.repo.model.file.FileHandle; import org.sagebionetworks.repo.model.file.PreviewFileHandle; import org.sagebionetworks.schema.FORMAT; import org.sagebionetworks.web.client.cookie.CookieProvider; import org.sagebionetworks.web.client.place.Down; import org.sagebionetworks.web.client.place.Home; import org.sagebionetworks.web.client.place.LoginPlace; import org.sagebionetworks.web.client.place.PeopleSearch; import org.sagebionetworks.web.client.place.Search; import org.sagebionetworks.web.client.place.Synapse; import org.sagebionetworks.web.client.place.Team; import org.sagebionetworks.web.client.place.TeamSearch; import org.sagebionetworks.web.client.place.Trash; import org.sagebionetworks.web.client.utils.Callback; import org.sagebionetworks.web.client.widget.FitImage; import org.sagebionetworks.web.client.widget.entity.JiraURLHelper; import org.sagebionetworks.web.client.widget.entity.WidgetSelectionState; import org.sagebionetworks.web.shared.PublicPrincipalIds; import org.sagebionetworks.web.shared.WebConstants; import org.sagebionetworks.web.shared.WidgetConstants; import org.sagebionetworks.web.shared.WikiPageKey; import org.sagebionetworks.web.shared.exceptions.BadRequestException; import org.sagebionetworks.web.shared.exceptions.ForbiddenException; import org.sagebionetworks.web.shared.exceptions.NotFoundException; import org.sagebionetworks.web.shared.exceptions.ReadOnlyModeException; import org.sagebionetworks.web.shared.exceptions.SynapseDownException; import org.sagebionetworks.web.shared.exceptions.UnauthorizedException; import org.sagebionetworks.web.shared.exceptions.UnknownErrorException; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Style; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.i18n.client.NumberFormat; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.AbstractImagePrototype; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.TextArea; import com.google.gwt.user.client.ui.UIObject; import com.google.gwt.user.client.ui.Widget; public class DisplayUtils { private static DateTimeFormat prettyFormat = null; private static Logger displayUtilsLogger = Logger.getLogger(DisplayUtils.class.getName()); public static PublicPrincipalIds publicPrincipalIds = null; public static enum MessagePopup { INFO, WARNING, QUESTION } public static NotifySettings getDefaultSettings() { NotifySettings notifySettings = NotifySettings.newSettings(); notifySettings.setTemplate("<div data-notify=\"container\" class=\"col-xs-11 alert alert-{0}\" role=\"alert\">\n" + " <button type=\"button\" aria-hidden=\"true\" class=\"close\" data-notify=\"dismiss\">x</button>\n" + " <span data-notify=\"icon\"></span>\n" + " <strong><span data-notify=\"title\">{1}</span></strong>\n" + " <span data-notify=\"message\">{2}</span>\n" + " <a href=\"{3}\" target=\"{4}\" data-notify=\"url\"></a>\n" + "</div>"); return notifySettings; } /** * Returns a properly aligned icon from an ImageResource * @param icon * @return */ public static String getIconHtml(ImageResource icon) { if(icon == null) return null; return "<span class=\"iconSpan\">" + AbstractImagePrototype.create(icon).getHTML() + "</span>"; } public static String getFriendlySize(double size, boolean abbreviatedUnits) { NumberFormat df = NumberFormat.getDecimalFormat(); if(size >= TB) { return df.format(size/TB) + (abbreviatedUnits?" TB":" Terabytes"); } if(size >= GB) { return df.format(size/GB) + (abbreviatedUnits?" GB":" Gigabytes"); } if(size >= MB) { return df.format(size/MB) + (abbreviatedUnits?" MB":" Megabytes"); } if(size >= KB) { return df.format(size/KB) + (abbreviatedUnits?" KB":" Kilobytes"); } return df.format(size) + " bytes"; } public static String getFileNameFromExternalUrl(String path){ //grab the text between the last '/' and following '?' String fileName = ""; if (path != null) { int lastSlash = path.lastIndexOf("/"); if (lastSlash > -1) { int firstQuestionMark = path.indexOf("?", lastSlash); if (firstQuestionMark > -1) { fileName = path.substring(lastSlash+1, firstQuestionMark); } else { fileName = path.substring(lastSlash+1); } } } return fileName; } /** * Handles the exception. Returns true if the user has been alerted to the exception already * @param ex * @param placeChanger * @return true if the user has been prompted */ public static boolean handleServiceException(Throwable ex, GlobalApplicationState globalApplicationState, boolean isLoggedIn, ShowsErrors view) { //send exception to the javascript console if (displayUtilsLogger != null && ex != null) displayUtilsLogger.log(Level.SEVERE, ex.getMessage()); if(ex instanceof ReadOnlyModeException || ex instanceof SynapseDownException) { globalApplicationState.getPlaceChanger().goTo(new Down(DEFAULT_PLACE_TOKEN)); return true; } else if(ex instanceof UnauthorizedException) { // send user to login page showInfo(DisplayConstants.SESSION_TIMEOUT, DisplayConstants.SESSION_HAS_TIMED_OUT); globalApplicationState.getPlaceChanger().goTo(new LoginPlace(LoginPlace.LOGOUT_TOKEN)); return true; } else if(ex instanceof ForbiddenException) { if(!isLoggedIn) { view.showErrorMessage(DisplayConstants.ERROR_LOGIN_REQUIRED); globalApplicationState.getPlaceChanger().goTo(new LoginPlace(LoginPlace.LOGIN_TOKEN)); } else { view.showErrorMessage(DisplayConstants.ERROR_FAILURE_PRIVLEDGES + " " + ex.getMessage()); } return true; } else if(ex instanceof BadRequestException) { //show error (not to file a jira though) view.showErrorMessage(ex.getMessage()); return true; } else if(ex instanceof NotFoundException) { view.showErrorMessage(DisplayConstants.ERROR_NOT_FOUND); globalApplicationState.getPlaceChanger().goTo(new Home(DEFAULT_PLACE_TOKEN)); return true; } else if (ex instanceof UnknownErrorException) { //An unknown error occurred. //Exception handling on the backend now throws the reason into the exception message. Easy! showErrorMessage(ex, globalApplicationState.getJiraURLHelper(), isLoggedIn, ex.getMessage()); return true; } // For other exceptions, allow the consumer to send a good message to the user return false; } public static boolean checkForRepoDown(Throwable caught, PlaceChanger placeChanger, SynapseView view) { if(caught instanceof ReadOnlyModeException) { view.showErrorMessage(DisplayConstants.SYNAPSE_IN_READ_ONLY_MODE); return true; } else if(caught instanceof SynapseDownException) { placeChanger.goTo(new Down(DEFAULT_PLACE_TOKEN)); return true; } return false; } /** * Returns a panel used to show a component is loading in the view * @param sageImageBundle * @return */ public static Div getLoadingWidget(SageImageBundle sageImageBundle) { Div cp = new Div(); cp.add(new HTML(SafeHtmlUtils.fromSafeConstant(DisplayUtils.getIconHtml(sageImageBundle.loading31())))); return cp; } public static String getLoadingHtml(SageImageBundle sageImageBundle) { return getLoadingHtml(sageImageBundle, DisplayConstants.LOADING); } public static String getLoadingHtml(SageImageBundle sageImageBundle, String message) { return DisplayUtils.getIconHtml(sageImageBundle.loading16()) + "&nbsp;" + message + "..."; } /** * Shows an info message to the user in the "Global Alert area". * @param title * @param message */ public static void showInfo(String title, String message) { NotifySettings settings = getDefaultSettings(); settings.setType(NotifyType.INFO); notify(title, message, settings); } public static void notify(String title, String message, NotifySettings settings) { try{ Notify.notify(title, message, settings); } catch(Throwable t) { SynapseJSNIUtilsImpl._consoleError(getStackTrace(t)); } } /** * Shows an warning message to the user in the "Global Alert area". * @param title * @param message */ public static void showError(String title, String message, Integer timeout) { NotifySettings settings = getDefaultSettings(); settings.setType(NotifyType.DANGER); settings.setAllowDismiss(false); if (timeout != null) { settings.setDelay(timeout); } notify(title, message, settings); } public static void showErrorMessage(String message) { showPopup("", message, MessagePopup.WARNING, null, null); } public static void showErrorMessage(String title, String message) { showPopup(title, message, MessagePopup.WARNING, null, null); } /** * @param t * @param jiraHelper * @param profile * @param friendlyErrorMessage * (optional) */ public static void showErrorMessage(final Throwable t, final JiraURLHelper jiraHelper, boolean isLoggedIn, String friendlyErrorMessage) { SynapseJSNIUtilsImpl._consoleError(getStackTrace(t)); if (!isLoggedIn) { showErrorMessage(t.getMessage()); return; } final Modal d = new Modal(); d.addStyleName("padding-5"); final String errorMessage = friendlyErrorMessage == null ? t.getMessage() : friendlyErrorMessage; Icon errorIcon = new Icon(IconType.EXCLAMATION_CIRCLE); errorIcon.setSize(org.gwtbootstrap3.client.ui.constants.IconSize.TIMES3); errorIcon.setPull(Pull.LEFT); errorIcon.addStyleName("margin-right-10"); HTML errorContent = new HTML(errorMessage); ModalBody dialogContent = new ModalBody(); dialogContent.addStyleName("margin-10"); dialogContent.add(errorIcon); dialogContent.add(errorContent); // create text area for steps FlowPanel formGroup = new FlowPanel(); formGroup.addStyleName("form-group margin-top-30"); formGroup.add(new HTML("<label>Describe the problem (optional)</label>")); final TextArea textArea = new TextArea(); textArea.addStyleName("form-control"); textArea.getElement().setAttribute("placeholder","Steps to reproduce the error"); textArea.getElement().setAttribute("rows", "4"); formGroup.add(textArea); dialogContent.add(formGroup); d.add(dialogContent); d.setSize(ModalSize.LARGE); d.setTitle("Synapse Error"); Button sendBugButton = new Button(DisplayConstants.SEND_BUG_REPORT, new ClickHandler() { @Override public void onClick(ClickEvent event) { jiraHelper.createIssueOnBackend(textArea.getValue(), t, errorMessage, new AsyncCallback<String>() { @Override public void onSuccess(String result) { d.hide(); showInfo("Report sent", "Thank you!"); } @Override public void onFailure(Throwable caught) { // failure to create issue! DisplayUtils.showErrorMessage(DisplayConstants.ERROR_GENERIC_NOTIFY+"\n" + caught.getMessage() +"\n\n" + textArea.getValue()); } }); } }); sendBugButton.setType(org.gwtbootstrap3.client.ui.constants.ButtonType.PRIMARY); Button doNotSendBugButton = new Button(DisplayConstants.DO_NOT_SEND_BUG_REPORT, new ClickHandler() { @Override public void onClick(ClickEvent event) { d.hide(); } }); ModalFooter footer = new ModalFooter(); footer.add(doNotSendBugButton); footer.add(sendBugButton); d.add(footer);; d.show(); } public static void showInfoDialog( String title, String message, Callback okCallback ) { showPopup(title, message, MessagePopup.INFO, okCallback, null); } public static void showConfirmDialog( String title, String message, Callback yesCallback, Callback noCallback ) { showPopup(title, message, MessagePopup.QUESTION, yesCallback, noCallback); } public static void showConfirmDialog( String title, String message, Callback yesCallback ) { showConfirmDialog(title, message, yesCallback, new Callback() { @Override public void invoke() { //do nothing when No is clicked } }); } public static void showPopup(String title, String message, DisplayUtils.MessagePopup iconStyle, final Callback primaryButtonCallback, final Callback secondaryButtonCallback) { SafeHtml popupHtml = getPopupSafeHtml(title, message, iconStyle); boolean isSecondaryButton = secondaryButtonCallback != null; if (isSecondaryButton) { Bootbox.confirm(popupHtml.asString(), new ConfirmCallback() { @Override public void callback(boolean isConfirmed) { if (isConfirmed) { if (primaryButtonCallback != null) primaryButtonCallback.invoke(); } else { if (secondaryButtonCallback != null) secondaryButtonCallback.invoke(); } } }); } else { Bootbox.alert(popupHtml.asString(), new AlertCallback() { @Override public void callback() { if (primaryButtonCallback != null) primaryButtonCallback.invoke(); } }); } } public static SafeHtml getPopupSafeHtml(String title, String message, DisplayUtils.MessagePopup iconStyle) { String iconHtml = ""; if (MessagePopup.INFO.equals(iconStyle)) iconHtml = getIcon("glyphicon-info-sign font-size-32 col-xs-1"); else if (MessagePopup.WARNING.equals(iconStyle)) iconHtml = getIcon("glyphicon-exclamation-sign font-size-32 col-xs-1"); else if (MessagePopup.QUESTION.equals(iconStyle)) iconHtml = getIcon("glyphicon-question-sign font-size-32 col-xs-1"); SafeHtmlBuilder builder = new SafeHtmlBuilder(); if (DisplayUtils.isDefined(title)) { builder.appendHtmlConstant("<h5>"); builder.appendEscaped(title); builder.appendHtmlConstant("</h5>"); } builder.appendHtmlConstant("<div class=\"row\">"); if (iconHtml.length() > 0) builder.appendHtmlConstant(iconHtml); String messageWidth = DisplayUtils.isDefined(iconHtml) ? "col-xs-11" : "col-xs-12"; builder.appendHtmlConstant("<div class=\""+messageWidth+"\">"); builder.appendEscaped(message); builder.appendHtmlConstant("</div></div>"); return builder.toSafeHtml(); } public static void scrollToTop(){ com.google.gwt.user.client.Window.scrollTo(0, 0); } public static String getPrimaryEmail(UserProfile userProfile) { List<String> emailAddresses = userProfile.getEmails(); if (emailAddresses == null || emailAddresses.isEmpty()) throw new IllegalStateException("UserProfile email list is empty"); return emailAddresses.get(0); } public static String getDisplayName(UserProfile profile) { return getDisplayName(profile.getFirstName(), profile.getLastName(), profile.getUserName()); } public static String getDisplayName(UserGroupHeader header) { return DisplayUtils.getDisplayName(header.getFirstName(), header.getLastName(), header.getUserName()); } public static String getDisplayName(String firstName, String lastName, String userName) { StringBuilder sb = new StringBuilder(); boolean hasDisplayName = false; if (firstName != null && firstName.length() > 0) { sb.append(firstName.trim()); hasDisplayName = true; } if (lastName != null && lastName.length() > 0) { sb.append(" "); sb.append(lastName.trim()); hasDisplayName = true; } sb.append(getUserName(userName, hasDisplayName)); return sb.toString(); } public static boolean isTemporaryUsername(String username){ if(username == null) throw new IllegalArgumentException("UserName cannot be null"); return username.startsWith(WebConstants.TEMPORARY_USERNAME_PREFIX); } public static String getUserName(String userName, boolean inParens) { StringBuilder sb = new StringBuilder(); if (userName != null && !isTemporaryUsername(userName)) { //if the name is filled in, then put the username in parens if (inParens) sb.append(" ("); sb.append(userName); if (inParens) sb.append(")"); } return sb.toString(); } public static String getMarkdownWidgetWarningHtml(String warningText) { return getWarningHtml(DisplayConstants.MARKDOWN_WIDGET_WARNING, warningText); } public static String getMarkdownAPITableWarningHtml(String warningText) { return getWarningHtml(DisplayConstants.MARKDOWN_API_TABLE_WARNING, warningText); } public static String getWarningHtml(String title, String warningText) { return getAlertHtml(title, warningText, BootstrapAlertType.WARNING); } public static String getAlertHtml(String title, String text, BootstrapAlertType type) { return "<div class=\"alert alert-"+type.toString().toLowerCase()+"\"><span class=\"boldText\">"+ title + "</span> " + SafeHtmlUtils.htmlEscape(text) + "</div>"; } public static String getBadgeHtml(String i) { return "<span class=\"badge moveup-4\">"+i+"</span>"; } public static String uppercaseFirstLetter(String display) { return display.substring(0, 1).toUpperCase() + display.substring(1); } /** * YYYY-MM-DD HH:mm:ss * @param toFormat * @return */ public static String convertDataToPrettyString(Date toFormat) { if(toFormat == null) throw new IllegalArgumentException("Date cannot be null"); if (prettyFormat == null) { prettyFormat = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss"); } return prettyFormat.format(toFormat); } /** * Converts a date to just a date. * @return yyyy-MM-dd * @return */ public static String converDateaToSimpleString(Date toFormat) { if(toFormat == null) throw new IllegalArgumentException("Date cannot be null"); return DateUtils.convertDateToString(FORMAT.DATE, toFormat); } public static String getTeamHistoryToken(String teamId) { Team place = new Team(teamId); return "#!" + getTeamPlaceString(Team.class) + ":" + place.toToken(); } public static String getTeamSearchHistoryToken(String searchTerm, Integer start) { TeamSearch place = new TeamSearch(searchTerm, start); return "#!" + getTeamSearchPlaceString(TeamSearch.class) + ":" + place.toToken(); } public static String getPeopleSearchHistoryToken(String searchTerm, Integer start) { PeopleSearch place = new PeopleSearch(searchTerm, start); return "#!" + getPeopleSearchPlaceString(PeopleSearch.class) + ":" + place.toToken(); } public static String getTrashHistoryToken(String token, Integer start) { Trash place = new Trash(token, start); return "#!" + getTrashPlaceString(Trash.class) + ":" + place.toToken(); } public static String getSearchHistoryToken(String searchQuery, Long start) { Search place = new Search(searchQuery, start); return "#!" + getSearchPlaceString(Search.class) + ":" + place.toToken(); } public static String getSynapseHistoryToken(String entityId) { return "#" + getSynapseHistoryTokenNoHash(entityId, null); } public static String getSynapseHistoryTokenNoHash(String entityId) { return getSynapseHistoryTokenNoHash(entityId, null); } public static String getSynapseHistoryToken(String entityId, Long versionNumber) { return "#" + getSynapseHistoryTokenNoHash(entityId, versionNumber); } public static String getSynapseHistoryTokenNoHash(String entityId, Long versionNumber) { return getSynapseHistoryTokenNoHash(entityId, versionNumber, null); } public static String getSynapseHistoryTokenNoHash(String entityId, Long versionNumber, Synapse.EntityArea area) { return getSynapseHistoryTokenNoHash(entityId, versionNumber, area, null); } public static String getSynapseHistoryTokenNoHash(String entityId, Long versionNumber, Synapse.EntityArea area, String areaToken) { Synapse place = new Synapse(entityId, versionNumber, area, areaToken); return "!"+ getPlaceString(Synapse.class) + ":" + place.toToken(); } /** * Stub the string removing the last partial word * @param str * @param length * @return */ public static String stubStr(String str, int length) { if(str == null) { return ""; } if(str.length() > length) { String sub = str.substring(0, length); str = sub.replaceFirst(" \\w+$", "") + ".."; // clean off partial last word } return str; } /** * Stub the string with partial word at end left in * @param contents * @param maxLength * @return */ public static String stubStrPartialWord(String contents, int maxLength) { String stub = contents; if(contents != null && contents.length() > maxLength) { stub = contents.substring(0, maxLength-3); stub += " .."; } return stub; } /* * Private methods */ private static String getPlaceString(Class<Synapse> place) { return getPlaceString(place.getName()); } private static String getTeamPlaceString(Class<Team> place) { return getPlaceString(place.getName()); } private static String getTeamSearchPlaceString(Class<TeamSearch> place) { return getPlaceString(place.getName()); } private static String getPeopleSearchPlaceString(Class<PeopleSearch> place) { return getPlaceString(place.getName()); } private static String getTrashPlaceString(Class<Trash> place) { return getPlaceString(place.getName()); } private static String getSearchPlaceString(Class<Search> place) { return getPlaceString(place.getName()); } private static String getPlaceString(String fullPlaceName) { fullPlaceName = fullPlaceName.replaceAll(".+\\.", ""); return fullPlaceName; } /** * Create the url to a profile attachment image. * @param baseURl * @param userId * @param tokenId * @param fileName * @return */ public static String createUserProfileAttachmentUrl(String baseURl, String userId, String fileHandleId, boolean preview){ StringBuilder builder = new StringBuilder(); builder.append(baseURl); builder.append("?"+WebConstants.USER_PROFILE_USER_ID+"="); builder.append(userId); builder.append("&"+WebConstants.USER_PROFILE_IMAGE_ID+"="); builder.append(fileHandleId); builder.append("&"+WebConstants.USER_PROFILE_PREVIEW+"="); builder.append(preview); return builder.toString(); } public static Popover addPopover(Widget widget, String message) { Popover popover = new Popover(widget); popover.setPlacement(Placement.AUTO); popover.setIsHtml(true); popover.setContent(message); return popover; } public static Tooltip addTooltip(Widget widget, String tooltipText){ return addTooltip(widget, tooltipText, Placement.AUTO); } /** * Adds a twitter bootstrap tooltip to the given widget using the standard Synapse configuration. * NOTE: Add the widget to the parent container only after adding the tooltip (the Tooltip is reconfigured on attach event). * * CAUTION - If not used with a non-block level element like * an anchor, img, or span the results will probably not be * quite what you want. Read the twitter bootstrap documentation * for the options that you can specify in optionsMap * * @param util the JSNIUtils class (or mock) * @param widget the widget to attach the tooltip to * @param tooltipText text to display * @param pos where to position the tooltip relative to the widget */ public static Tooltip addTooltip(Widget widget, String tooltipText, Placement pos){ Tooltip t = new Tooltip(); t.setPlacement(pos); t.setTitle(tooltipText); t.setIsHtml(true); t.setIsAnimated(false); t.setTrigger(Trigger.HOVER); t.setWidget(widget); return t; } public static String getVersionDisplay(Versionable versionable) { String version = ""; if(versionable == null || versionable.getVersionNumber() == null) return version; if(versionable.getVersionLabel() != null && !versionable.getVersionNumber().toString().equals(versionable.getVersionLabel())) { version = versionable.getVersionLabel() + " (" + versionable.getVersionNumber() + ")"; } else { version = versionable.getVersionNumber().toString(); } return version; } public static native JavaScriptObject newWindow(String url, String name, String features)/*-{ try { var window = $wnd.open(url, name, features); return window; }catch(err) { return null; } }-*/; public static Anchor createIconLink(AbstractImagePrototype icon, ClickHandler clickHandler) { Anchor anchor = new Anchor(); anchor.setHTML(icon.getHTML()); anchor.addClickHandler(clickHandler); return anchor; } public static boolean isInTestWebsite(CookieProvider cookies) { return isInCookies(DisplayUtils.SYNAPSE_TEST_WEBSITE_COOKIE_KEY, cookies); } public static void setTestWebsite(boolean testWebsite, CookieProvider cookies) { setInCookies(testWebsite, DisplayUtils.SYNAPSE_TEST_WEBSITE_COOKIE_KEY, cookies); } public static final String SYNAPSE_TEST_WEBSITE_COOKIE_KEY = "SynapseTestWebsite"; public static boolean isInCookies(String cookieKey, CookieProvider cookies) { return cookies.getCookie(cookieKey) != null; } public static void setInCookies(boolean value, String cookieKey, CookieProvider cookies) { if (value && !isInCookies(cookieKey, cookies)) { //set the cookie cookies.setCookie(cookieKey, "true"); } else{ cookies.removeCookie(cookieKey); } } /** * Create the URL to a version of a wiki's attachments. * @param baseFileHandleUrl * @param wikiKey * @param fileName * @param preview * @param wikiVersion * @return */ public static String createVersionOfWikiAttachmentUrl(String baseFileHandleUrl, WikiPageKey wikiKey, String fileName, boolean preview, Long wikiVersion, String xsrfToken) { String attachmentUrl = createWikiAttachmentUrl(baseFileHandleUrl, wikiKey, fileName, preview, xsrfToken); return attachmentUrl + "&" + WebConstants.WIKI_VERSION_PARAM_KEY + "=" + wikiVersion.toString(); } /** * Create the url to a wiki filehandle. * @param baseURl * @param id * @param tokenId * @param fileName * @return */ public static String createWikiAttachmentUrl(String baseFileHandleUrl, WikiPageKey wikiKey, String fileName, boolean preview, String xsrfToken){ //direct approach not working. have the filehandleservlet redirect us to the temporary wiki attachment url instead // String attachmentPathName = preview ? "attachmentpreview" : "attachment"; // return repoServicesUrl // +"/" +wikiKey.getOwnerObjectType().toLowerCase() // +"/"+ wikiKey.getOwnerObjectId() // +"/wiki/" // +wikiKey.getWikiPageId() // +"/"+ attachmentPathName+"?fileName="+URL.encodePathSegment(fileName); String wikiIdParam = wikiKey.getWikiPageId() == null ? "" : "&" + WebConstants.WIKI_ID_PARAM_KEY + "=" + wikiKey.getWikiPageId(); return baseFileHandleUrl + "?" + WebConstants.WIKI_OWNER_ID_PARAM_KEY + "=" + wikiKey.getOwnerObjectId() + "&" + WebConstants.WIKI_OWNER_TYPE_PARAM_KEY + "=" + wikiKey.getOwnerObjectType() + "&"+ WebConstants.XSRF_TOKEN_KEY + "=" + xsrfToken + "&" + WebConstants.WIKI_FILENAME_PARAM_KEY + "=" + fileName + "&" + WebConstants.FILE_HANDLE_PREVIEW_PARAM_KEY + "=" + Boolean.toString(preview) + wikiIdParam; } public static String createFileEntityUrl(String baseFileHandleUrl, String entityId, Long versionNumber, boolean preview, String xsrfToken){ return createFileEntityUrl(baseFileHandleUrl, entityId, versionNumber, preview, false, xsrfToken); } public static String getParamForNoCaching() { return WebConstants.NOCACHE_PARAM + new Date().getTime(); } /** * Create the url to a FileEntity filehandle. * @param baseURl * @param entityid * @return */ public static String createFileEntityUrl(String baseFileHandleUrl, String entityId, Long versionNumber, boolean preview, boolean proxy, String xsrfToken){ String versionParam = versionNumber == null ? "" : "&" + WebConstants.ENTITY_VERSION_PARAM_KEY + "=" + versionNumber.toString(); return baseFileHandleUrl + "?" + WebConstants.ENTITY_PARAM_KEY + "=" + entityId + "&" + WebConstants.FILE_HANDLE_PREVIEW_PARAM_KEY + "=" + Boolean.toString(preview) + "&" + WebConstants.PROXY_PARAM_KEY + "=" + Boolean.toString(proxy) + "&" + WebConstants.XSRF_TOKEN_KEY + "=" + xsrfToken + versionParam; } /** * Create the url to a Team icon filehandle. * @param baseURl * @param teamId * @return */ public static String createTeamIconUrl(String baseFileHandleUrl, String teamId, String xsrfToken){ return baseFileHandleUrl + "?" + WebConstants.TEAM_PARAM_KEY + "=" + teamId + "&" + WebConstants.XSRF_TOKEN_KEY + "=" + xsrfToken; } /** * Create the url to the raw file handle id (must be the owner to access) * @param baseURl * @param rawFileHandleId * @return */ public static String createRawFileHandleUrl(String baseFileHandleUrl, String rawFileHandleId, String xsrfToken){ return baseFileHandleUrl + "?" + WebConstants.RAW_FILE_HANDLE_PARAM + "=" + rawFileHandleId + "&" + WebConstants.XSRF_TOKEN_KEY + "=" + xsrfToken; } public static String createEntityVersionString(Reference ref) { return createEntityVersionString(ref.getTargetId(), ref.getTargetVersionNumber()); } public static String createEntityVersionString(String id, Long version) { String idNotNull = id == null ? "" : id; if(version != null) return idNotNull+WebConstants.ENTITY_VERSION_STRING+version; else return idNotNull; } public static Reference parseEntityVersionString(String entityVersion) { String[] parts = entityVersion.split(WebConstants.ENTITY_VERSION_STRING); Reference ref = null; if(parts.length > 0) { ref = new Reference(); ref.setTargetId(parts[0]); if(parts.length > 1) { try { ref.setTargetVersionNumber(Long.parseLong(parts[1])); } catch(NumberFormatException e) {} } } return ref; } public static boolean isRecognizedImageContentType(String contentType) { String lowerContentType = contentType.toLowerCase(); return IMAGE_CONTENT_TYPES_SET.contains(lowerContentType); } public static boolean isRecognizedTableContentType(String contentType) { String lowerContentType = contentType.toLowerCase(); return TABLE_CONTENT_TYPES_SET.contains(lowerContentType); } public static boolean isTextType(String contentType) { return contentType.toLowerCase().startsWith("text/"); } public static boolean isCSV(String contentType) { return contentType != null && contentType.toLowerCase().startsWith("text/csv"); } public static boolean isTAB(String contentType) { return contentType != null && contentType.toLowerCase().startsWith(WebConstants.TEXT_TAB_SEPARATED_VALUES); } /** * Return a preview filehandle associated with this bundle (or null if unavailable) * @param bundle * @return */ public static PreviewFileHandle getPreviewFileHandle(EntityBundle bundle) { PreviewFileHandle fileHandle = null; if (bundle.getFileHandles() != null) { for (FileHandle fh : bundle.getFileHandles()) { if (fh instanceof PreviewFileHandle) { fileHandle = (PreviewFileHandle) fh; break; } } } return fileHandle; } /** * Return the filehandle associated with this bundle (or null if unavailable) * @param bundle * @return */ public static FileHandle getFileHandle(EntityBundle bundle) { FileHandle fileHandle = null; if (bundle.getFileHandles() != null) { FileEntity entity = (FileEntity)bundle.getEntity(); String targetId = entity.getDataFileHandleId(); for (FileHandle fh : bundle.getFileHandles()) { if (fh.getId().equals(targetId)) { fileHandle = fh; break; } } } return fileHandle; } public interface SelectedHandler<T> { public void onSelected(T selected); } public static Widget getShareSettingsDisplay(boolean isPublic, SynapseJSNIUtils synapseJSNIUtils) { final SimplePanel lc = new SimplePanel(); lc.addStyleName(STYLE_DISPLAY_INLINE); String styleName = isPublic ? "public-acl-image" : "private-acl-image"; String description = isPublic ? DisplayConstants.PUBLIC_ACL_ENTITY_PAGE : DisplayConstants.PRIVATE_ACL_ENTITY_PAGE; String tooltip = isPublic ? DisplayConstants.PUBLIC_ACL_DESCRIPTION : DisplayConstants.PRIVATE_ACL_DESCRIPTION; SafeHtmlBuilder shb = new SafeHtmlBuilder(); shb.appendHtmlConstant("<div class=\"" + styleName+ "\" style=\"display:inline; position:absolute\"></div>"); shb.appendHtmlConstant("<span style=\"margin-left: 20px;\">"+description+"</span>"); //form the html HTMLPanel htmlPanel = new HTMLPanel(shb.toSafeHtml()); htmlPanel.addStyleName("inline-block"); lc.add(DisplayUtils.addTooltip(htmlPanel, tooltip, Placement.BOTTOM)); return lc; } public static void updateWidgetSelectionState(WidgetSelectionState state, String text, int cursorPos) { state.setWidgetSelected(false); state.setWidgetStartIndex(-1); state.setWidgetEndIndex(-1); state.setInnerWidgetText(null); if (cursorPos > -1) { //move back until I find a whitespace or the beginning int startWord = cursorPos-1; while(startWord > -1 && !Character.isSpace(text.charAt(startWord))) { startWord } startWord++; String possibleWidget = text.substring(startWord); if (possibleWidget.startsWith(WidgetConstants.WIDGET_START_MARKDOWN)) { //find the end int endWord = cursorPos; while(endWord < text.length() && !WidgetConstants.WIDGET_END_MARKDOWN.equals(String.valueOf(text.charAt(endWord)))) { endWord++; } //invalid widget specification if we went all the way to the end of the markdown if (endWord < text.length()) { //it's a widget //parse the type and descriptor endWord++; possibleWidget = text.substring(startWord, endWord); //set editable state.setWidgetSelected(true); state.setInnerWidgetText(possibleWidget.substring(WidgetConstants.WIDGET_START_MARKDOWN.length(), possibleWidget.length() - WidgetConstants.WIDGET_END_MARKDOWN.length())); state.setWidgetStartIndex(startWord); state.setWidgetEndIndex(endWord); } } } } /** * Surround the selectedText with the given markdown. Or, if the selected text is already surrounded by the markdown, then remove it. * @param text * @param markdown * @param startPos * @param selectionLength * @return */ public static String surroundText(String text, String startTag, String endTag, boolean isMultiline, int startPos, int selectionLength) throws IllegalArgumentException { if (text != null && selectionLength > -1 && startPos >= 0 && startPos <= text.length() && isDefined(startTag)) { if (endTag == null) endTag = ""; int startTagLength = startTag.length(); int endTagLength = endTag.length(); int eolPos = text.indexOf('\n', startPos); if (eolPos < 0) eolPos = text.length(); int endPos = startPos + selectionLength; if (eolPos < endPos && !isMultiline) throw new IllegalArgumentException(DisplayConstants.SINGLE_LINE_COMMAND_MESSAGE); String selectedText = text.substring(startPos, endPos); //check to see if this text is already surrounded by the markdown. int beforeSelectedTextPos = startPos - startTagLength; int afterSelectedTextPos = endPos + endTagLength; if (beforeSelectedTextPos > -1 && afterSelectedTextPos <= text.length()) { if (startTag.equals(text.substring(beforeSelectedTextPos, startPos)) && endTag.equals(text.substring(endPos, afterSelectedTextPos))) { //strip off markdown instead return text.substring(0, beforeSelectedTextPos) + selectedText + text.substring(afterSelectedTextPos); } } return text.substring(0, startPos) + startTag + selectedText + endTag + text.substring(endPos); } throw new IllegalArgumentException(DisplayConstants.INVALID_SELECTION); } public static boolean isDefined(String testString) { return testString != null && testString.trim().length() > 0; } public static FlowPanel createRowContainerFlowPanel() { FlowPanel row = new FlowPanel(); row.setStyleName("row"); return row; } public static enum ButtonType { DEFAULT, PRIMARY, SUCCESS, INFO, WARNING, DANGER, LINK } public static enum BootstrapAlertType { SUCCESS, INFO, WARNING, DANGER } public static com.google.gwt.user.client.ui.Button createButton(String title) { return createIconButton(title, ButtonType.DEFAULT, null); } public static com.google.gwt.user.client.ui.Button createButton(String title, ButtonType type) { return createIconButton(title, type, null); } public static com.google.gwt.user.client.ui.Button createIconButton(String title, ButtonType type, String iconClass) { com.google.gwt.user.client.ui.Button btn = new com.google.gwt.user.client.ui.Button(); relabelIconButton(btn, title, iconClass); btn.removeStyleName("gwt-Button"); btn.addStyleName("btn btn-" + type.toString().toLowerCase()); return btn; } public static void relabelIconButton(com.google.gwt.user.client.ui.Button btn, String title, String iconClass) { String style = iconClass == null ? "" : " class=\"glyphicon " + iconClass+ "\"" ; btn.setHTML(SafeHtmlUtils.fromSafeConstant("<span" + style +"></span> " + title)); } public static String getIcon(String iconClass) { return "<span class=\"glyphicon " + iconClass + "\"></span>"; } public static String getFontAwesomeIcon(String iconClass) { return "<span class=\"fa fa-" + iconClass + "\"></span>"; } public static EntityHeader getProjectHeader(EntityPath entityPath) { if(entityPath == null) return null; for(EntityHeader eh : entityPath.getPath()) { if(Project.class.getName().equals(eh.getType())) { return eh; } } return null; } public static FlowPanel getMediaObject(String heading, String description, ClickHandler clickHandler, String pictureUri, boolean defaultPictureSinglePerson, int headingLevel) { FlowPanel panel = new FlowPanel(); panel.addStyleName("media"); String linkStyle = ""; if (clickHandler != null) linkStyle = "link"; HTML headingHtml = new HTML("<h"+headingLevel+" class=\"media-heading "+linkStyle+"\">" + SafeHtmlUtils.htmlEscape(heading) + "</h"+headingLevel+">"); if (clickHandler != null) headingHtml.addClickHandler(clickHandler); if (pictureUri != null) { FitImage profilePicture = new FitImage(pictureUri, 64, 64); profilePicture.addStyleName("pull-left media-object imageButton"); if (clickHandler != null) profilePicture.addClickHandler(clickHandler); panel.add(profilePicture); } else { //display default picture String iconClass = defaultPictureSinglePerson ? "user" : "users"; String clickableButtonCssClass = clickHandler != null ? "imageButton" : ""; HTML profilePicture = new HTML(DisplayUtils.getFontAwesomeIcon(iconClass + " font-size-58 padding-2 " + clickableButtonCssClass + " userProfileImage lightGreyText margin-0-imp-before")); profilePicture.addStyleName("pull-left media-object displayInline "); if (clickHandler != null) profilePicture.addClickHandler(clickHandler); panel.add(profilePicture); } FlowPanel mediaBodyPanel = new FlowPanel(); mediaBodyPanel.addStyleName("media-body"); mediaBodyPanel.add(headingHtml); if (description != null) mediaBodyPanel.add(new HTML(SafeHtmlUtils.htmlEscape(description))); panel.add(mediaBodyPanel); return panel; } public static String getShareMessage(String displayName, String entityId, String hostUrl) { return displayName + DisplayConstants.SHARED_ON_SYNAPSE + ":\n"+hostUrl+"#!Synapse:"+entityId+"\n"; } public static void getPublicPrincipalIds(UserAccountServiceAsync userAccountService, final AsyncCallback<PublicPrincipalIds> callback){ if (publicPrincipalIds == null) { userAccountService.getPublicAndAuthenticatedGroupPrincipalIds(new AsyncCallback<PublicPrincipalIds>() { @Override public void onSuccess(PublicPrincipalIds result) { publicPrincipalIds = result; callback.onSuccess(result); } @Override public void onFailure(Throwable caught) { callback.onFailure(caught); } }); } else callback.onSuccess(publicPrincipalIds); } public static void hide(UIObject uiObject) { uiObject.setVisible(false); } public static void show(UIObject uiObject) { uiObject.setVisible(true); } public static void hide(com.google.gwt.dom.client.Element elem) { UIObject.setVisible(elem, false); } public static void show(com.google.gwt.dom.client.Element elem) { UIObject.setVisible(elem, true); } public static void showFormError(DivElement parentElement, DivElement messageElement) { parentElement.addClassName("has-error"); DisplayUtils.show(messageElement); } public static void hideFormError(DivElement parentElement, DivElement messageElement) { parentElement.removeClassName("has-error"); DisplayUtils.hide(messageElement); } public static String getInfoHtml(String safeHtmlMessage) { return "<div class=\"alert alert-info\">"+safeHtmlMessage+"</div>"; } public static String getStackTrace(Throwable t) { StringBuilder stackTrace = new StringBuilder(); if (t != null) { for (StackTraceElement element : t.getStackTrace()) { stackTrace.append(element + "\n"); } } return stackTrace.toString(); } /** * This is to work around a Chrome rendering bug, where some containers do not properly calculate their relative widths (in the dynamic bootstrap grid layout) when they are initially added. * The most visible of these cases is the Wiki Subpages panel (see SWC-1450). * @param e */ public static void clearElementWidth(Element e) { if ( e != null) { Style style = e.getStyle(); if (style != null) { style.setWidth(1, Unit.PX); style.clearWidth(); } } } /** * just return the empty string if input string parameter s is null, otherwise returns s. */ public static String replaceWithEmptyStringIfNull(String s) { if (s == null) return ""; else return s; } /** * return true if the widget is in the visible part of the page */ public static boolean isInViewport(Widget widget) { int docViewTop = Window.getScrollTop(); int docViewBottom = docViewTop + Window.getClientHeight(); int elemTop = widget.getAbsoluteTop(); int elemBottom = elemTop + widget.getOffsetHeight(); return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)); } }
package org.swiften.javautilities.object; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; public final class ObjectUtil { /** * Check if {@link Object} is not null. * @param object {@link Nullable} {@link Object}. * @return {@link Boolean} value. */ public static boolean nonNull(@Nullable Object object) { return object != null; } /** * Check if all {@link Object}s within {@link Iterable} is not null. * @param objects {@link Iterable} of {@link Object}. * @param <T> Generics parameter. * @return {@link Boolean} value. * @see #isNull(Object) */ public static <T> boolean nonNull(@NotNull Iterable<T> objects) { for (Object object : objects) { if (isNull(object)) { return false; } } return true; } /** * Check if all {@link Object}s within a varargs Array is not null. * @param objects A varargs of {@link Object}. * @return {@link Boolean} value. * @see #nonNull(Iterable) */ public static boolean nonNull(@NotNull Object...objects) { return nonNull(Arrays.asList(objects)); } /** * Check if {@link Object} is null. * @param object {@link Nullable} {@link Object}. * @return {@link Boolean} value. */ public static boolean isNull(@Nullable Object object) { return object == null; } /** * Check if any {@link Object}s within {@link Iterable} is null. * @param objects {@link Iterable} of {@link T}. * @param <T> Generics parameter. * @return {@link Boolean} value. * @see #nonNull(Object) */ public static <T> boolean isNull(@NotNull Iterable<T> objects) { for (Object object : objects) { if (isNull(object)) { return true; } } return false; } /** * Check if any {@link Object}s within a varargs Array is null. * @param objects A varargs of {@link Object}. * @return {@link Boolean} value. * @see #isNull(Iterable) */ public static boolean isNull(@NotNull Object...objects) { return isNull(Arrays.asList(objects)); } /** * Cast {@link Object} to {@link Object}. * @param object {@link Object}. * @return {@link Object}. */ @Nullable public static Object toObject(@Nullable Object object) { return object; } /** * Return the same {@link T} instance. * @param object {@link T} instance. * @param <T> Generics parameter. * @return {@link T} instance. */ @Nullable public static <T> T eq(@Nullable T object) { return object; } private ObjectUtil() {} }
package py.una.med.base.util; import java.util.Collections; import java.util.List; import javax.faces.model.SelectItem; import py.una.med.base.dao.restrictions.Where; import py.una.med.base.dao.search.ISearchParam; public class SIGHListHelperInMemory<T> implements KarakuListHelperProvider<T> { private List<T> listMemory; private SimpleFilter simpleFilter; private PagingHelper pagingHelper; public SIGHListHelperInMemory(List<T> list) { this(new SimpleFilter(), list); } public SIGHListHelperInMemory(SimpleFilter simpleFilter, List<T> list) { setListMemory(list); this.simpleFilter = simpleFilter; } @Override public List<T> getEntities() { List<T> toShow = doFilter(listMemory, getSimpleFilter().getOption(), getSimpleFilter().getValue()); long size = toShow.size(); getHelper().udpateCount(size); ISearchParam isp = getHelper().getISearchparam(); int from = isp.getOffset(); int to = isp.getOffset() + isp.getLimit(); if (to > toShow.size()) { to = toShow.size(); } return toShow.subList(from, to); } @Override public void reloadEntities() { // nada que hacer, la lista esta en memoria. } public List<T> doFilter(List<T> toFilter, String option, String value) { return toFilter; } @Override public SimpleFilter getSimpleFilter() { return simpleFilter; } @Override public List<SelectItem> getFilterOptions() { return Collections.emptyList(); } public List<T> getListMemory() { return listMemory; } public final void setListMemory(List<T> listMemory) { if (listMemory == null) { setListMemory(Collections.<T> emptyList()); return; } this.listMemory = listMemory; } @Override public void setBaseWhere(Where<T> where) { // TODO Auto-generated method stub } @Override public PagingHelper getHelper() { if (pagingHelper == null) { pagingHelper = new PagingHelper(5); } return pagingHelper; } }
package seedu.taskmanager.commons.util; import java.time.LocalDate; import java.time.YearMonth; import java.util.Calendar; import java.util.TimeZone; import seedu.taskmanager.commons.exceptions.IllegalValueException; // @@author A0142418L public class DateTimeUtil { public static final String MESSAGE_DAY_CONSTRAINTS = "Task date should be either " + "a day (e.g. thursday) or a date with the format: DD/MM/YY (e.g. 03/03/17)\n" + "May also include time (e.g. 1400) behind date \n" + "Enter HELP for user guide with detailed explanations of all commands"; public static final String CURRENTDATE_VALIDATION_REGEX_TODAY1 = "Today"; public static final String CURRENTDATE_VALIDATION_REGEX_TODAY2 = "today"; public static final String CURRENTDATE_VALIDATION_REGEX_TOMORROW1 = "Tomorrow"; public static final String CURRENTDATE_VALIDATION_REGEX_TOMORROW2 = "tomorrow"; public static final String CURRENTDATE_VALIDATION_REGEX_TOMORROW3 = "Tmr"; public static final String CURRENTDATE_VALIDATION_REGEX_TOMORROW4 = "tmr"; public static final String CURRENTDATE_VALIDATION_REGEX_MONDAY1 = "Monday"; public static final String CURRENTDATE_VALIDATION_REGEX_MONDAY2 = "monday"; public static final String CURRENTDATE_VALIDATION_REGEX_MONDAY3 = "Mon"; public static final String CURRENTDATE_VALIDATION_REGEX_MONDAY4 = "mon"; public static final String CURRENTDATE_VALIDATION_REGEX_TUESDAY1 = "Tuesday"; public static final String CURRENTDATE_VALIDATION_REGEX_TUESDAY2 = "tuesday"; public static final String CURRENTDATE_VALIDATION_REGEX_TUESDAY3 = "Tues"; public static final String CURRENTDATE_VALIDATION_REGEX_TUESDAY4 = "tues"; public static final String CURRENTDATE_VALIDATION_REGEX_WEDNESDAY1 = "Wednesday"; public static final String CURRENTDATE_VALIDATION_REGEX_WEDNESDAY2 = "wednesday"; public static final String CURRENTDATE_VALIDATION_REGEX_WEDNESDAY3 = "Wed"; public static final String CURRENTDATE_VALIDATION_REGEX_WEDNESDAY4 = "wed"; public static final String CURRENTDATE_VALIDATION_REGEX_THURSDAY1 = "Thursday"; public static final String CURRENTDATE_VALIDATION_REGEX_THURSDAY2 = "thursday"; public static final String CURRENTDATE_VALIDATION_REGEX_THURSDAY3 = "Thurs"; public static final String CURRENTDATE_VALIDATION_REGEX_THURSDAY4 = "thurs"; public static final String CURRENTDATE_VALIDATION_REGEX_FRIDAY1 = "Friday"; public static final String CURRENTDATE_VALIDATION_REGEX_FRIDAY2 = "friday"; public static final String CURRENTDATE_VALIDATION_REGEX_FRIDAY3 = "Fri"; public static final String CURRENTDATE_VALIDATION_REGEX_FRIDAY4 = "fri"; public static final String CURRENTDATE_VALIDATION_REGEX_SATURDAY1 = "Saturday"; public static final String CURRENTDATE_VALIDATION_REGEX_SATURDAY2 = "saturday"; public static final String CURRENTDATE_VALIDATION_REGEX_SATURDAY3 = "Sat"; public static final String CURRENTDATE_VALIDATION_REGEX_SATURDAY4 = "sat"; public static final String CURRENTDATE_VALIDATION_REGEX_SUNDAY1 = "Sunday"; public static final String CURRENTDATE_VALIDATION_REGEX_SUNDAY2 = "sunday"; public static final String CURRENTDATE_VALIDATION_REGEX_SUNDAY3 = "Sun"; public static final String CURRENTDATE_VALIDATION_REGEX_SUNDAY4 = "sun"; public static int currentDay; public static String currentDate = ""; public DateTimeUtil() { currentDay = getCurrentDay(); currentDate = getCurrentDate(); } /** * Checks to see if user has input a valid day, this function includes * different spellings of the same day */ public static boolean isValidDay(String test) { return test.matches(CURRENTDATE_VALIDATION_REGEX_MONDAY1) || test.matches(CURRENTDATE_VALIDATION_REGEX_MONDAY2) || test.matches(CURRENTDATE_VALIDATION_REGEX_MONDAY3) || test.matches(CURRENTDATE_VALIDATION_REGEX_MONDAY4) || test.matches(CURRENTDATE_VALIDATION_REGEX_TUESDAY1) || test.matches(CURRENTDATE_VALIDATION_REGEX_TUESDAY2) || test.matches(CURRENTDATE_VALIDATION_REGEX_TUESDAY3) || test.matches(CURRENTDATE_VALIDATION_REGEX_TUESDAY4) || test.matches(CURRENTDATE_VALIDATION_REGEX_WEDNESDAY1) || test.matches(CURRENTDATE_VALIDATION_REGEX_WEDNESDAY2) || test.matches(CURRENTDATE_VALIDATION_REGEX_WEDNESDAY3) || test.matches(CURRENTDATE_VALIDATION_REGEX_WEDNESDAY4) || test.matches(CURRENTDATE_VALIDATION_REGEX_THURSDAY1) || test.matches(CURRENTDATE_VALIDATION_REGEX_THURSDAY2) || test.matches(CURRENTDATE_VALIDATION_REGEX_THURSDAY3) || test.matches(CURRENTDATE_VALIDATION_REGEX_THURSDAY4) || test.matches(CURRENTDATE_VALIDATION_REGEX_FRIDAY1) || test.matches(CURRENTDATE_VALIDATION_REGEX_FRIDAY2) || test.matches(CURRENTDATE_VALIDATION_REGEX_FRIDAY3) || test.matches(CURRENTDATE_VALIDATION_REGEX_FRIDAY4) || test.matches(CURRENTDATE_VALIDATION_REGEX_SATURDAY1) || test.matches(CURRENTDATE_VALIDATION_REGEX_SATURDAY2) || test.matches(CURRENTDATE_VALIDATION_REGEX_SATURDAY3) || test.matches(CURRENTDATE_VALIDATION_REGEX_SATURDAY4) || test.matches(CURRENTDATE_VALIDATION_REGEX_SUNDAY1) || test.matches(CURRENTDATE_VALIDATION_REGEX_SUNDAY2) || test.matches(CURRENTDATE_VALIDATION_REGEX_SUNDAY3) || test.matches(CURRENTDATE_VALIDATION_REGEX_SUNDAY4) || test.matches(CURRENTDATE_VALIDATION_REGEX_TODAY1) || test.matches(CURRENTDATE_VALIDATION_REGEX_TODAY2) || test.matches(CURRENTDATE_VALIDATION_REGEX_TOMORROW1) || test.matches(CURRENTDATE_VALIDATION_REGEX_TOMORROW2) || test.matches(CURRENTDATE_VALIDATION_REGEX_TOMORROW3) || test.matches(CURRENTDATE_VALIDATION_REGEX_TOMORROW4); } /** * @return Day number relative to the day itself (e.g. Sunday == 1 & * Wednesday == 4) */ public static int getNewDay(String day) { if (isSunday(day)) { return 1; } else { if (isMonday(day)) { return 2; } else { if (isTuesday(day)) { return 3; } else { if (isWednesday(day)) { return 4; } else { if (isThursday(day)) { return 5; } else { if (isFriday(day)) { return 6; } else { if (isSaturday(day)) { return 7; } else { if (isToday(day)) { Calendar calendar = Calendar.getInstance(TimeZone.getDefault()); return calendar.get(Calendar.DAY_OF_WEEK); } else { return getTomorrowDay(); } } } } } } } } } /** * @return Current Day with respect to the date on the computer */ public static int getCurrentDay() { Calendar calendar = Calendar.getInstance(TimeZone.getDefault()); int day = calendar.get(Calendar.DATE); return day; } /** * @return Current Date with respect to the date on the computer */ public static String getCurrentDate() { Calendar calendar = Calendar.getInstance(TimeZone.getDefault()); // getTime() returns the current date in default time zone int day = calendar.get(Calendar.DATE); // Note: +1 the month for current month int month = calendar.get(Calendar.MONTH) + 1; int year = calendar.get(Calendar.YEAR); return getFormattedDate(day, month, year); } public static String getNewDate(String givenDay) throws IllegalValueException { if (!isValidDay(givenDay)) { throw new IllegalValueException(MESSAGE_DAY_CONSTRAINTS); } int inputDay = getNewDay(givenDay); Calendar calendar = Calendar.getInstance(TimeZone.getDefault()); // getTime() returns the current date in default time zone int day = calendar.get(Calendar.DATE); // Note: +1 the month for current month int month = calendar.get(Calendar.MONTH) + 1; int year = calendar.get(Calendar.YEAR); int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); LocalDate testdate = LocalDate.of(year, month, day); int testdays = testdate.lengthOfMonth(); int diffInDays = dayOfWeek - inputDay; if (diffInDays == 0) { return getCurrentDate(); } if (diffInDays > 0) { day += (7 - diffInDays); } if (diffInDays < 0) { day -= diffInDays; } if (day > testdays) { month += 1; day -= testdays; } if (month > 12) { month = 1; year += 1; } return getFormattedDate(day, month, year); } public static int isDateWithin(String date, String startDate, String endDate) { String[] dmy = date.trim().split("/"); int day = Integer.parseInt(dmy[0]); int month = Integer.parseInt(dmy[1]); int year = Integer.parseInt(dmy[2]); String[] dmyStart = startDate.trim().split("/"); int dayStart = Integer.parseInt(dmyStart[0]); int monthStart = Integer.parseInt(dmyStart[1]); int yearStart = Integer.parseInt(dmyStart[2]); String[] dmyEnd = endDate.trim().split("/"); int dayEnd = Integer.parseInt(dmyEnd[0]); int monthEnd = Integer.parseInt(dmyEnd[1]); int yearEnd = Integer.parseInt(dmyEnd[2]); if (year < yearEnd && yearStart < year) { return 1; } else { if (year == yearEnd && year == yearStart) { if (month < monthEnd && monthStart < month) { return 1; } else { if (month == monthEnd && month == monthStart) { if (day < dayEnd && dayStart < day) { return 1; } else { if (day == dayEnd && dayStart == day) { return 2; } } } } } } return 0; } public static boolean isValidDate(String date) { String[] dmy = date.trim().split("/"); int day = Integer.parseInt(dmy[0]); int month = Integer.parseInt(dmy[1]); int year = Integer.parseInt(dmy[2]); YearMonth yearMonthObject = YearMonth.of(2000 + year, month); if (day > yearMonthObject.lengthOfMonth() || month > 12) { return false; } else { return true; } } public static String getFutureDate(int loops, String typeOfRecurrence, String existingDate) { String[] dmy = existingDate.trim().split("/"); int day = Integer.parseInt(dmy[0]); int month = Integer.parseInt(dmy[1]); int year = Integer.parseInt(dmy[2]); String newDate = ""; String newDay = ""; String newMonth = ""; YearMonth yearMonthObject = YearMonth.of(2000 + year, month); if (typeOfRecurrence.equalsIgnoreCase("days") || typeOfRecurrence.equalsIgnoreCase("day")) { day = day + loops; while (day > yearMonthObject.lengthOfMonth()) { day = day - yearMonthObject.lengthOfMonth(); month = month + 01; if (month > 12) { year = year + 1; month = 01; } yearMonthObject = YearMonth.of(2000 + year, month); } } if (typeOfRecurrence.equalsIgnoreCase("weeks") || typeOfRecurrence.equalsIgnoreCase("week")) { day = day + loops * 7; while (day > yearMonthObject.lengthOfMonth()) { day = day - yearMonthObject.lengthOfMonth(); month = month + 01; if (month > 12) { year = year + 1; month = 01; } yearMonthObject = YearMonth.of(2000 + year, month); } } if (typeOfRecurrence.equalsIgnoreCase("months") || typeOfRecurrence.equalsIgnoreCase("month")) { month = month + loops; while (month > 12) { month = month - 12; year = year + 1; } } if (typeOfRecurrence.equalsIgnoreCase("years") || typeOfRecurrence.equalsIgnoreCase("year")) { year = year + loops; } newDay = convertIntegerToTwoCharString(day); newMonth = convertIntegerToTwoCharString(month); newDate = newDay + "/" + newMonth + "/" + year; return newDate; } public static boolean isValidEventTimePeriod(String startDate, String startTime, String endDate, String endTime) throws IllegalValueException { String[] splitedStartDate = (startDate.trim()).split("/"); String[] splitedEndDate = (endDate.trim()).split("/"); boolean isValidStartEnd = true; if (Integer.parseInt(splitedEndDate[2]) <= Integer.parseInt(splitedStartDate[2])) { if (Integer.parseInt(splitedEndDate[2]) < Integer.parseInt(splitedStartDate[2])) { isValidStartEnd = false; } else { if (Integer.parseInt(splitedEndDate[1]) <= Integer.parseInt(splitedStartDate[1])) { if (Integer.parseInt(splitedEndDate[0]) < Integer.parseInt(splitedStartDate[0])) { isValidStartEnd = false; } else { if (Integer.parseInt(splitedEndDate[0]) <= Integer.parseInt(splitedStartDate[0])) { if (Integer.parseInt(splitedEndDate[0]) < Integer.parseInt(splitedStartDate[0])) { isValidStartEnd = false; } else { if (Integer.parseInt(startTime) > Integer.parseInt(endTime)) { throw new IllegalValueException( "Invalid input of time, start time has to be earlier than end time"); } } } } } } } return isValidStartEnd; } public static boolean isValidTime(String value) { return (value.matches("\\d+") && (Integer.parseInt(value) < 2400) && (Integer.parseInt(value) >= 0) && (((Integer.parseInt(value)) % 100) < 60)); } public static String includeOneHourBuffer(String startTime) { String endTime; endTime = Integer.toString(100 + Integer.parseInt(startTime)); if (Integer.parseInt(endTime) < 1000) { endTime = "0" + endTime; } if (!isValidTime(endTime)) { endTime = Integer.toString(Integer.parseInt(endTime) - 2400); endTime = fourDigitTimeFormat(endTime); } return endTime; } public static String fourDigitTimeFormat(String endTime) { if (Integer.parseInt(endTime) >= 10) { StringBuilder stringBuilderTime = new StringBuilder(); stringBuilderTime.append("00"); stringBuilderTime.append(endTime); endTime = stringBuilderTime.toString(); } else { StringBuilder stringBuilderTime = new StringBuilder(); stringBuilderTime.append("000"); stringBuilderTime.append(endTime); endTime = stringBuilderTime.toString(); } return endTime; } // @@author A0142418L /** * @param dayOfWeek * @return Integer day value of tomorrow. */ private static int getTomorrowDay() { Calendar calendar = Calendar.getInstance(TimeZone.getDefault()); int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); if (dayOfWeek + 1 == 8) { return dayOfWeek = 1; } else { return dayOfWeek + 1; } } /** * @param day * @return true if input matches "Today" regex. */ private static boolean isToday(String day) { return day.matches(CURRENTDATE_VALIDATION_REGEX_TODAY1) || day.matches(CURRENTDATE_VALIDATION_REGEX_TODAY2); } /** * @param day * @return true if input matches "Saturday" regex. */ private static boolean isSaturday(String day) { return day.matches(CURRENTDATE_VALIDATION_REGEX_SATURDAY1) || day.matches(CURRENTDATE_VALIDATION_REGEX_SATURDAY2) || day.matches(CURRENTDATE_VALIDATION_REGEX_SATURDAY3) || day.matches(CURRENTDATE_VALIDATION_REGEX_SATURDAY4); } /** * @param day * @return true if input matches "Friday" regex. */ private static boolean isFriday(String day) { return day.matches(CURRENTDATE_VALIDATION_REGEX_FRIDAY1) || day.matches(CURRENTDATE_VALIDATION_REGEX_FRIDAY2) || day.matches(CURRENTDATE_VALIDATION_REGEX_FRIDAY3) || day.matches(CURRENTDATE_VALIDATION_REGEX_FRIDAY4); } /** * @param day * @return true if input matches "Thursday" regex. */ private static boolean isThursday(String day) { return day.matches(CURRENTDATE_VALIDATION_REGEX_THURSDAY1) || day.matches(CURRENTDATE_VALIDATION_REGEX_THURSDAY2) || day.matches(CURRENTDATE_VALIDATION_REGEX_THURSDAY3) || day.matches(CURRENTDATE_VALIDATION_REGEX_THURSDAY4); } /** * @param day * @return true if input matches "Wednesday" regex. */ private static boolean isWednesday(String day) { return day.matches(CURRENTDATE_VALIDATION_REGEX_WEDNESDAY1) || day.matches(CURRENTDATE_VALIDATION_REGEX_WEDNESDAY2) || day.matches(CURRENTDATE_VALIDATION_REGEX_WEDNESDAY3) || day.matches(CURRENTDATE_VALIDATION_REGEX_WEDNESDAY4); } /** * @param day * @return true if input matches "Tuesday" regex. */ private static boolean isTuesday(String day) { return day.matches(CURRENTDATE_VALIDATION_REGEX_TUESDAY1) || day.matches(CURRENTDATE_VALIDATION_REGEX_TUESDAY2) || day.matches(CURRENTDATE_VALIDATION_REGEX_TUESDAY3) || day.matches(CURRENTDATE_VALIDATION_REGEX_TUESDAY4); } /** * @param day * @return true if input matches "Monday" regex. */ private static boolean isMonday(String day) { return day.matches(CURRENTDATE_VALIDATION_REGEX_MONDAY1) || day.matches(CURRENTDATE_VALIDATION_REGEX_MONDAY2) || day.matches(CURRENTDATE_VALIDATION_REGEX_MONDAY3) || day.matches(CURRENTDATE_VALIDATION_REGEX_MONDAY4); } /** * @param day * @return true if input matches "Sunday" regex. */ private static boolean isSunday(String day) { return day.matches(CURRENTDATE_VALIDATION_REGEX_SUNDAY1) || day.matches(CURRENTDATE_VALIDATION_REGEX_SUNDAY2) || day.matches(CURRENTDATE_VALIDATION_REGEX_SUNDAY3) || day.matches(CURRENTDATE_VALIDATION_REGEX_SUNDAY4); } /** * @param day * @return Integer as a 2 character string */ private static String convertIntegerToTwoCharString(int integer) { String string; if (integer < 10) { string = "0" + Integer.toString(integer); } else { string = Integer.toString(integer); } return string; } /** * @param day * @param month * @param year * @return Date formatted in defined format for application */ private static String getFormattedDate(int day, int month, int year) { String updatedDate; String stringDay; String stringMonth; String stringYear; stringDay = convertIntegerToTwoCharString(day); stringMonth = convertIntegerToTwoCharString(month); stringYear = Integer.toString(year).substring(Math.max(Integer.toString(year).length() - 2, 0)); updatedDate = stringDay + "/" + stringMonth + "/" + stringYear; return updatedDate; } }
package org.codehaus.groovy.runtime; import groovy.lang.*; import groovy.util.CharsetToolkit; import groovy.util.ClosureComparator; import groovy.util.OrderBy; import java.io.*; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.net.MalformedURLException; import java.net.ServerSocket; import java.net.Socket; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.*; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * This class defines all the new groovy methods which appear on normal JDK * classes inside the Groovy environment. Static methods are used with the * first parameter the destination class. * * @author <a href="mailto:james@coredevelopers.net">James Strachan</a> * @author Jeremy Rayner * @author Sam Pullara * @author Rod Cope * @author Guillaume Laforge * @author John Wilson * @version $Revision$ */ public class DefaultGroovyMethods { private static Logger log = Logger.getLogger(DefaultGroovyMethods.class.getName()); private static final Integer ONE = new Integer(1); private static final char ZERO_CHAR = '\u0000'; /** * Allows the subscript operator to be used to lookup dynamic property values. * <code>bean[somePropertyNameExpression]</code>. The normal property notation * of groovy is neater and more concise but only works with compile time known * property names. * * @param self * @return */ public static Object getAt(Object self, String property) { return InvokerHelper.getProperty(self, property); } /** * Allows the subscript operator to be used to set dynamically named property values. * <code>bean[somePropertyNameExpression] = foo</code>. The normal property notation * of groovy is neater and more concise but only works with compile time known * property names. * * @param self */ public static void putAt(Object self, String property, Object newValue) { InvokerHelper.setProperty(self, property, newValue); } /** * Generates a detailed dump string of an object showing its class, * hashCode and fields */ public static String dump(Object self) { if (self == null) { return "null"; } StringBuffer buffer = new StringBuffer("<"); Class klass = self.getClass(); buffer.append(klass.getName()); buffer.append("@"); buffer.append(Integer.toHexString(self.hashCode())); boolean groovyObject = self instanceof GroovyObject; /*jes this may be rewritten to use the new allProperties() stuff * but the original pulls out private variables, whereas allProperties() * does not. What's the real use of dump() here? */ while (klass != null) { Field[] fields = klass.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { final Field field = fields[i]; if ((field.getModifiers() & Modifier.STATIC) == 0) { if (groovyObject && field.getName().equals("metaClass")) { continue; } AccessController.doPrivileged(new PrivilegedAction() { public Object run() { field.setAccessible(true); return null; } }); buffer.append(" "); buffer.append(field.getName()); buffer.append("="); try { buffer.append(InvokerHelper.toString(field.get(self))); } catch (Exception e) { buffer.append(e); } } } klass = klass.getSuperclass(); } /* here is a different implementation that uses allProperties(). I have left * it commented out because it returns a slightly different list of properties; * ie it does not return privates. I don't know what dump() really should be doing, * although IMO showing private fields is a no-no */ /* List props = allProperties(self); for(Iterator itr = props.iterator(); itr.hasNext(); ) { PropertyValue pv = (PropertyValue) itr.next(); // the original skipped this, so I will too if(pv.getName().equals("metaClass")) continue; if(pv.getName().equals("class")) continue; buffer.append(" "); buffer.append(pv.getName()); buffer.append("="); try { buffer.append(InvokerHelper.toString(pv.getValue())); } catch (Exception e) { buffer.append(e); } } */ buffer.append(">"); return buffer.toString(); } public static void eachPropertyName(Object self, Closure closure) { List props = allProperties(self); for (Iterator itr = props.iterator(); itr.hasNext();) { PropertyValue pv = (PropertyValue) itr.next(); closure.call(pv.getName()); } } public static void eachProperty(Object self, Closure closure) { List props = allProperties(self); for (Iterator itr = props.iterator(); itr.hasNext();) { PropertyValue pv = (PropertyValue) itr.next(); closure.call(pv); } } public static List allProperties(Object self) { List props = new ArrayList(); MetaClass metaClass = InvokerHelper.getMetaClass(self); List mps; if (self instanceof groovy.util.Expando) { mps = ((groovy.util.Expando) self).getProperties(); } else { // get the MetaProperty list from the MetaClass mps = metaClass.getProperties(); } for (Iterator itr = mps.iterator(); itr.hasNext();) { MetaProperty mp = (MetaProperty) itr.next(); PropertyValue pv = new PropertyValue(self, mp); props.add(pv); } return props; } /** * Scoped use method */ public static void use(Object self, Class categoryClass, Closure closure) { GroovyCategorySupport.use(categoryClass, closure); } /** * Scoped use method with list of categories */ public static void use(Object self, List categoryClassList, Closure closure) { GroovyCategorySupport.use(categoryClassList, closure); } /** * Print to a console in interactive format */ public static void print(Object self, Object value) { System.out.print(InvokerHelper.toString(value)); } /** * Print a linebreak to the standard out. */ public static void println(Object self) { System.out.println(); } /** * Print to a console in interactive format along with a newline */ public static void println(Object self, Object value) { System.out.println(InvokerHelper.toString(value)); } /** * Printf to a console. Only works with JDK1.5 or alter. * * @author Russel Winder * @version 2005.02.01.15.53 */ public static void printf(final Object self, final String format, final Object[] values) { if ( System.getProperty("java.version").charAt(2) == '5' ) { // Cannot just do: // System.out.printf(format, values) ; // because this fails to compile on JDK1.4.x and earlier. So until the entire world is using // JDK1.5 or later then we have to do things by reflection so as to hide the use of printf // from the compiler. In JDK1.5 you might try: // System.out.getClass().getMethod("printf", String.class, Object[].class).invoke(System.out, format, values) ; // but of course this doesn't work on JDK1.4 as it relies on varargs. argh. So we are // forced into: try { System.out.getClass().getMethod("printf", new Class[] {String.class, Object[].class}).invoke(System.out, new Object[] {format, values}) ; } catch ( NoSuchMethodException nsme ) { throw new RuntimeException ("getMethod threw a NoSuchMethodException. This is impossible.") ; } catch ( IllegalAccessException iae ) { throw new RuntimeException ("invoke threw a IllegalAccessException. This is impossible.") ; } catch ( java.lang.reflect.InvocationTargetException ite ) { throw new RuntimeException ("invoke threw a InvocationTargetException. This is impossible.") ; } } else { throw new RuntimeException ("printf requires JDK1.5 or later.") ; } } /** * @return a String that matches what would be typed into a terminal to * create this object. e.g. [1, 'hello'].inspect() -> [1, "hello"] */ public static String inspect(Object self) { return InvokerHelper.inspect(self); } /** * Print to a console in interactive format */ public static void print(Object self, PrintWriter out) { if (out == null) { out = new PrintWriter(System.out); } out.print(InvokerHelper.toString(self)); } /** * Print to a console in interactive format * * @param out the PrintWriter used for printing */ public static void println(Object self, PrintWriter out) { if (out == null) { out = new PrintWriter(System.out); } InvokerHelper.invokeMethod(self, "print", out); out.println(); } /** * Provide a dynamic method invocation method which can be overloaded in * classes to implement dynamic proxies easily. */ public static Object invokeMethod(Object object, String method, Object arguments) { return InvokerHelper.invokeMethod(object, method, arguments); } // isCase methods public static boolean isCase(Object caseValue, Object switchValue) { return caseValue.equals(switchValue); } public static boolean isCase(String caseValue, Object switchValue) { if (switchValue == null) { return caseValue == null; } return caseValue.equals(switchValue.toString()); } public static boolean isCase(Class caseValue, Object switchValue) { return caseValue.isInstance(switchValue); } public static boolean isCase(Collection caseValue, Object switchValue) { return caseValue.contains(switchValue); } public static boolean isCase(Pattern caseValue, Object switchValue) { Matcher matcher = caseValue.matcher(switchValue.toString()); if (matcher.matches()) { RegexSupport.setLastMatcher(matcher); return true; } else { return false; } } // Collection based methods /** * Allows objects to be iterated through using a closure * * @param self the object over which we iterate * @param closure the closure applied on each element found */ public static void each(Object self, Closure closure) { for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) { closure.call(iter.next()); } } /** * Allows object to be iterated through a closure with a counter * * @param self an Object * @param closure a Closure */ public static void eachWithIndex(Object self, Closure closure) { int counter = 0; for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) { closure.call(new Object[]{iter.next(), new Integer(counter++)}); } } /** * Allows objects to be iterated through using a closure * * @param self the collection over which we iterate * @param closure the closure applied on each element of the collection */ public static void each(Collection self, Closure closure) { for (Iterator iter = self.iterator(); iter.hasNext();) { closure.call(iter.next()); } } /** * Allows a Map to be iterated through using a closure. If the * closure takes one parameter then it will be passed the Map.Entry * otherwise if the closure takes two parameters then it will be * passed the key and the value. * * @param self the map over which we iterate * @param closure the closure applied on each entry of the map */ public static void each(Map self, Closure closure) { if (closure.getParameterTypes().length == 2) { for (Iterator iter = self.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); closure.call(new Object[]{entry.getKey(), entry.getValue()}); } } else { for (Iterator iter = self.entrySet().iterator(); iter.hasNext();) { closure.call(iter.next()); } } } /** * Iterates over every element of a collection, and check whether a predicate is valid for all elements. * * @param self the object over which we iterate * @param closure the closure predicate used for matching * @return true if every item in the collection matches the closure * predicate */ public static boolean every(Object self, Closure closure) { for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) { if (!InvokerHelper.asBool(closure.call(iter.next()))) { return false; } } return true; } /** * Iterates over every element of a collection, and check whether a predicate is valid for at least one element * * @param self the object over which we iterate * @param closure the closure predicate used for matching * @return true if any item in the collection matches the closure predicate */ public static boolean any(Object self, Closure closure) { for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) { if (InvokerHelper.asBool(closure.call(iter.next()))) { return true; } } return false; } /** * Iterates over every element of the collection and return each object that matches * the given filter - calling the isCase() method used by switch statements. * This method can be used with different kinds of filters like regular expresions, classes, ranges etc. * * @param self the object over which we iterate * @param filter the filter to perform on the collection (using the isCase(object) method) * @return a list of objects which match the filter */ public static List grep(Object self, Object filter) { List answer = new ArrayList(); MetaClass metaClass = InvokerHelper.getMetaClass(filter); for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) { Object object = iter.next(); if (InvokerHelper.asBool(metaClass.invokeMethod(filter, "isCase", object))) { answer.add(object); } } return answer; } /** * Counts the number of occurencies of the given value inside this collection * * @param self the collection within which we count the number of occurencies * @param value the value * @return the number of occurrencies */ public static int count(Collection self, Object value) { int answer = 0; for (Iterator iter = self.iterator(); iter.hasNext();) { if (InvokerHelper.compareEqual(iter.next(), value)) { ++answer; } } return answer; } /** * Convert a collection to a List. * * @param self a collection * @return a List */ public static List toList(Collection self) { List answer = new ArrayList(self.size()); answer.addAll(self); return answer; } /** * Iterates through this object transforming each object into a new value using the closure * as a transformer, returning a list of transformed values. * * @param self the values of the object to map * @param closure the closure used to map each element of the collection * @return a List of the mapped values */ public static List collect(Object self, Closure closure) { return (List) collect(self, new ArrayList(), closure); } /** * Iterates through this object transforming each object into a new value using the closure * as a transformer and adding it to the collection, returning the resulting collection. * * @param self the values of the object to map * @param collection the Collection to which the mapped values are added * @param closure the closure used to map each element of the collection * @return the resultant collection */ public static Collection collect(Object self, Collection collection, Closure closure) { for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) { collection.add(closure.call(iter.next())); } return collection; } /** * Iterates through this collection transforming each entry into a new value using the closure * as a transformer, returning a list of transformed values. * * @param self a collection * @param closure the closure used for mapping * @return a List of the mapped values */ public static List collect(Collection self, Closure closure) { return (List) collect(self, new ArrayList(self.size()), closure); } /** * Iterates through this collection transforming each entry into a new value using the closure * as a transformer, returning a list of transformed values. * * @param self a collection * @param collection the Collection to which the mapped values are added * @param closure the closure used to map each element of the collection * @return the resultant collection */ public static Collection collect(Collection self, Collection collection, Closure closure) { for (Iterator iter = self.iterator(); iter.hasNext();) { collection.add(closure.call(iter.next())); if (closure.getDirective() == Closure.DONE) { break; } } return collection; } /** * Iterates through this Map transforming each entry into a new value using the closure * as a transformer, returning a list of transformed values. * * @param self a Map * @param closure the closure used for mapping * @return a List of the mapped values */ public static Collection collect(Map self, Collection collection, Closure closure) { for (Iterator iter = self.entrySet().iterator(); iter.hasNext();) { collection.add(closure.call(iter.next())); } return collection; } /** * Iterates through this Map transforming each entry into a new value using the closure * as a transformer, returning a list of transformed values. * * @param self a Map * @param collection the Collection to which the mapped values are added * @param closure the closure used to map each element of the collection * @return the resultant collection */ public static List collect(Map self, Closure closure) { return (List) collect(self, new ArrayList(self.size()), closure); } /** * Finds the first value matching the closure condition * * @param self an Object with an iterator returning its values * @param closure a closure condition * @return the first Object found */ public static Object find(Object self, Closure closure) { for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) { Object value = iter.next(); if (InvokerHelper.asBool(closure.call(value))) { return value; } } return null; } /** * Finds the first value matching the closure condition * * @param self a Collection * @param closure a closure condition * @return the first Object found */ public static Object find(Collection self, Closure closure) { for (Iterator iter = self.iterator(); iter.hasNext();) { Object value = iter.next(); if (InvokerHelper.asBool(closure.call(value))) { return value; } } return null; } /** * Finds the first value matching the closure condition * * @param self a Map * @param closure a closure condition * @return the first Object found */ public static Object find(Map self, Closure closure) { for (Iterator iter = self.entrySet().iterator(); iter.hasNext();) { Object value = iter.next(); if (InvokerHelper.asBool(closure.call(value))) { return value; } } return null; } /** * Finds all values matching the closure condition * * @param self an Object with an Iterator returning its values * @param closure a closure condition * @return a List of the values found */ public static List findAll(Object self, Closure closure) { List answer = new ArrayList(); for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) { Object value = iter.next(); if (InvokerHelper.asBool(closure.call(value))) { answer.add(value); } } return answer; } /** * Finds all values matching the closure condition * * @param self a Collection * @param closure a closure condition * @return a List of the values found */ public static List findAll(Collection self, Closure closure) { List answer = new ArrayList(self.size()); for (Iterator iter = self.iterator(); iter.hasNext();) { Object value = iter.next(); if (InvokerHelper.asBool(closure.call(value))) { answer.add(value); } } return answer; } /** * Finds all values matching the closure condition * * @param self a Map * @param closure a closure condition applying on the keys * @return a List of keys */ public static List findAll(Map self, Closure closure) { List answer = new ArrayList(self.size()); for (Iterator iter = self.entrySet().iterator(); iter.hasNext();) { Object value = iter.next(); if (InvokerHelper.asBool(closure.call(value))) { answer.add(value); } } return answer; } /** * Iterates through the given collection, passing in the initial value to * the closure along with the current iterated item then passing into the * next iteration the value of the previous closure. * * @param self a Collection * @param value a value * @param closure a closure * @return the last value of the last iteration */ public static Object inject(Collection self, Object value, Closure closure) { Object[] params = new Object[2]; for (Iterator iter = self.iterator(); iter.hasNext();) { Object item = iter.next(); params[0] = value; params[1] = item; value = closure.call(params); } return value; } /** * Concatenates all of the items of the collection together with the given String as a separator * * @param self a Collection of objects * @param separator a String separator * @return the joined String */ public static String join(Collection self, String separator) { StringBuffer buffer = new StringBuffer(); boolean first = true; for (Iterator iter = self.iterator(); iter.hasNext();) { Object value = iter.next(); if (first) { first = false; } else { buffer.append(separator); } buffer.append(InvokerHelper.toString(value)); } return buffer.toString(); } /** * Concatenates all of the elements of the array together with the given String as a separator * * @param self an array of Object * @param separator a String separator * @return the joined String */ public static String join(Object[] self, String separator) { StringBuffer buffer = new StringBuffer(); boolean first = true; for (int i = 0; i < self.length; i++) { String value = InvokerHelper.toString(self[i]); if (first) { first = false; } else { buffer.append(separator); } buffer.append(value); } return buffer.toString(); } /** * Selects the maximum value found in the collection * * @param self a Collection * @return the maximum value */ public static Object max(Collection self) { Object answer = null; for (Iterator iter = self.iterator(); iter.hasNext();) { Object value = iter.next(); if (value != null) { if (answer == null || InvokerHelper.compareGreaterThan(value, answer)) { answer = value; } } } return answer; } /** * Selects the maximum value found in the collection using the given comparator * * @param self a Collection * @param comparator a Comparator * @return the maximum value */ public static Object max(Collection self, Comparator comparator) { Object answer = null; for (Iterator iter = self.iterator(); iter.hasNext();) { Object value = iter.next(); if (answer == null || comparator.compare(value, answer) > 0) { answer = value; } } return answer; } /** * Selects the minimum value found in the collection * * @param self a Collection * @return the minimum value */ public static Object min(Collection self) { Object answer = null; for (Iterator iter = self.iterator(); iter.hasNext();) { Object value = iter.next(); if (value != null) { if (answer == null || InvokerHelper.compareLessThan(value, answer)) { answer = value; } } } return answer; } /** * Selects the minimum value found in the collection using the given comparator * * @param self a Collection * @param comparator a Comparator * @return the minimum value */ public static Object min(Collection self, Comparator comparator) { Object answer = null; for (Iterator iter = self.iterator(); iter.hasNext();) { Object value = iter.next(); if (answer == null || comparator.compare(value, answer) < 0) { answer = value; } } return answer; } /** * Selects the minimum value found in the collection using the given closure as a comparator * * @param self a Collection * @param closure a closure used as a comparator * @return the minimum value */ public static Object min(Collection self, Closure closure) { return min(self, new ClosureComparator(closure)); } /** * Selects the maximum value found in the collection using the given closure as a comparator * * @param self a Collection * @param closure a closure used as a comparator * @return the maximum value */ public static Object max(Collection self, Closure closure) { return max(self, new ClosureComparator(closure)); } /** * Selects the item in a collection that maximizies the given closure * * @param self a Collection * @param c a Closure * @return the maximizing item */ public static Object maximize(Collection self, Closure c) { Object answer = null; Object answer_value = null; for (Iterator iter = self.iterator(); iter.hasNext();) { Object item = iter.next(); Object value = c.call(item); if (answer == null || InvokerHelper.compareGreaterThan(value, answer_value)) { answer = item; answer_value = value; } } return answer; } /** * Selects the item in a collection that minimizes the given closure * * @param self a Collection * @param c a Closure * @return the minimizing item */ public static Object minimize(Collection self, Closure c) { Object answer = null; Object answer_value = null; for (Iterator iter = self.iterator(); iter.hasNext();) { Object item = iter.next(); Object value = c.call(item); if (answer == null || InvokerHelper.compareLessThan(value, answer_value)) { answer = item; answer_value = value; } } return answer; } /** * Makes a String look like a Collection by adding support for the size() method * * @param text a String * @return the length of the String */ public static int size(String text) { return text.length(); } /** * Makes an Array look like a Collection by adding support for the size() method * * @param self an Array of Object * @return the size of the Array */ public static int size(Object[] self) { return self.length; } /** * Support the subscript operator for String. * * @param text a String * @param index the index of the Character to get * @return the Character at the given index */ public static CharSequence getAt(CharSequence text, int index) { index = normaliseIndex(index, text.length()); return text.subSequence(index, index + 1); } /** * Support the subscript operator for String * * @param text a String * @return the Character object at the given index */ public static String getAt(String text, int index) { index = normaliseIndex(index, text.length()); return text.substring(index, index + 1); } /** * Support the range subscript operator for CharSequence * * @param text a CharSequence * @param range a Range * @return the subsequence CharSequence */ public static CharSequence getAt(CharSequence text, Range range) { int from = normaliseIndex(InvokerHelper.asInt(range.getFrom()), text.length()); int to = normaliseIndex(InvokerHelper.asInt(range.getTo()), text.length()); // if this is a backwards range, reverse the arguments to substring if (from > to) { int tmp = from; from = to; to = tmp; } return text.subSequence(from, to + 1); } /** * Support the range subscript operator for String * * @param text a String * @param range a Range * @return a substring corresponding to the Range */ public static String getAt(String text, Range range) { int from = normaliseIndex(InvokerHelper.asInt(range.getFrom()), text.length()); int to = normaliseIndex(InvokerHelper.asInt(range.getTo()), text.length()); // if this is a backwards range, reverse the arguments to substring boolean reverse = range.isReverse(); if (from > to) { int tmp = to; to = from; from = tmp; reverse = !reverse; } String answer = text.substring(from, to + 1); if (reverse) { answer = reverse(answer); } return answer; } /** * Creates a new string which is the reverse (backwards) of this string * * @param self a String * @return a new string with all the characters reversed. */ public static String reverse(String self) { int size = self.length(); StringBuffer buffer = new StringBuffer(size); for (int i = size - 1; i >= 0; i buffer.append(self.charAt(i)); } return buffer.toString(); } /** * Transforms a String representing a URL into a URL object. * * @param self the String representing a URL * @return a URL * @throws MalformedURLException is thrown if the URL is not well formed. */ public static URL toURL(String self) throws MalformedURLException { return new URL(self); } private static String getPadding(String padding, int length) { if (padding.length() < length) { return multiply(padding, new Integer(length / padding.length() + 1)).substring(0, length); } else { return padding.substring(0, length); } } /** * Pad a String with the characters appended to the left * * @param numberOfChars the total number of characters * @param padding the charaters used for padding * @return the String padded to the left */ public static String padLeft(String self, Number numberOfChars, String padding) { int numChars = numberOfChars.intValue(); if (numChars <= self.length()) { return self; } else { return getPadding(padding, numChars - self.length()) + self; } } /** * Pad a String with the spaces appended to the left * * @param numberOfChars the total number of characters * @return the String padded to the left */ public static String padLeft(String self, Number numberOfChars) { return padLeft(self, numberOfChars, " "); } /** * Pad a String with the characters appended to the right * * @param numberOfChars the total number of characters * @param padding the charaters used for padding * @return the String padded to the right */ public static String padRight(String self, Number numberOfChars, String padding) { int numChars = numberOfChars.intValue(); if (numChars <= self.length()) { return self; } else { return self + getPadding(padding, numChars - self.length()); } } /** * Pad a String with the spaces appended to the right * * @param numberOfChars the total number of characters * @return the String padded to the right */ public static String padRight(String self, Number numberOfChars) { return padRight(self, numberOfChars, " "); } /** * Center a String and padd it with the characters appended around it * * @param numberOfChars the total number of characters * @param padding the charaters used for padding * @return the String centered with padded character around */ public static String center(String self, Number numberOfChars, String padding) { int numChars = numberOfChars.intValue(); if (numChars <= self.length()) { return self; } else { int charsToAdd = numChars - self.length(); String semiPad = charsToAdd % 2 == 1 ? getPadding(padding, charsToAdd / 2 + 1) : getPadding(padding, charsToAdd / 2); if (charsToAdd % 2 == 0) return semiPad + self + semiPad; else return semiPad.substring(0, charsToAdd / 2) + self + semiPad; } } /** * Center a String and padd it with spaces appended around it * * @param numberOfChars the total number of characters * @return the String centered with padded character around */ public static String center(String self, Number numberOfChars) { return center(self, numberOfChars, " "); } /** * Support the subscript operator for a regex Matcher * * @param matcher a Matcher * @param idx an index * @return the group at the given index */ public static String getAt(Matcher matcher, int idx) { matcher.reset(); idx = normaliseIndex(idx, matcher.groupCount()); // are we using groups? if (matcher.groupCount() > 0) { // yes, so return the specified group matcher.find(); return matcher.group(idx); } else { // not using groups, so return the nth // occurrence of the pattern for (int i = 0; i <= idx; i++) { matcher.find(); } return matcher.group(); } } /** * Support the range subscript operator for a List * * @param self a List * @param range a Range * @return a range of a list from the range's from index up to but not including the ranges's to value */ public static List getAt(List self, Range range) { int size = self.size(); int from = normaliseIndex(InvokerHelper.asInt(range.getFrom()), size); int to = normaliseIndex(InvokerHelper.asInt(range.getTo()), size); boolean reverse = range.isReverse(); if (from > to) { int tmp = to; to = from; from = tmp; reverse = !reverse; } if (++to > size) { to = size; } List answer = self.subList(from, to); if (reverse) { answer = reverse(answer); } return answer; } /** * Allows a List to be used as the indices to be used on a List * * @param self a List * @param indices a Collection of indices * @return a new list of the values at the given indices */ public static List getAt(List self, Collection indices) { List answer = new ArrayList(indices.size()); for (Iterator iter = indices.iterator(); iter.hasNext();) { Object value = iter.next(); if (value instanceof Range) { answer.addAll(getAt(self, (Range) value)); } else if (value instanceof List) { answer.addAll(getAt(self, (List) value)); } else { int idx = InvokerHelper.asInt(value); answer.add(getAt(self, idx)); } } return answer; } /** * Allows a List to be used as the indices to be used on a List * * @param self an Array of Objects * @param indices a Collection of indices * @return a new list of the values at the given indices */ public static List getAt(Object[] self, Collection indices) { List answer = new ArrayList(indices.size()); for (Iterator iter = indices.iterator(); iter.hasNext();) { Object value = iter.next(); if (value instanceof Range) { answer.addAll(getAt(self, (Range) value)); } else if (value instanceof Collection) { answer.addAll(getAt(self, (Collection) value)); } else { int idx = InvokerHelper.asInt(value); answer.add(getAt(self, idx)); } } return answer; } /** * Allows a List to be used as the indices to be used on a CharSequence * * @param self a CharSequence * @param indices a Collection of indices * @return a String of the values at the given indices */ public static CharSequence getAt(CharSequence self, Collection indices) { StringBuffer answer = new StringBuffer(); for (Iterator iter = indices.iterator(); iter.hasNext();) { Object value = iter.next(); if (value instanceof Range) { answer.append(getAt(self, (Range) value)); } else if (value instanceof Collection) { answer.append(getAt(self, (Collection) value)); } else { int idx = InvokerHelper.asInt(value); answer.append(getAt(self, idx)); } } return answer.toString(); } /** * Allows a List to be used as the indices to be used on a String * * @param self a String * @param indices a Collection of indices * @return a String of the values at the given indices */ public static String getAt(String self, Collection indices) { return (String) getAt((CharSequence) self, indices); } /** * Allows a List to be used as the indices to be used on a Matcher * * @param self a Matcher * @param indices a Collection of indices * @return a String of the values at the given indices */ public static String getAt(Matcher self, Collection indices) { StringBuffer answer = new StringBuffer(); for (Iterator iter = indices.iterator(); iter.hasNext();) { Object value = iter.next(); if (value instanceof Range) { answer.append(getAt(self, (Range) value)); } else if (value instanceof Collection) { answer.append(getAt(self, (Collection) value)); } else { int idx = InvokerHelper.asInt(value); answer.append(getAt(self, idx)); } } return answer.toString(); } /** * Creates a sub-Map containing the given keys. This method is similar to * List.subList() but uses keys rather than index ranges. * * @param map a Map * @param keys a Collection of keys * @return a new Map containing the given keys */ public static Map subMap(Map map, Collection keys) { Map answer = new HashMap(keys.size()); for (Iterator iter = keys.iterator(); iter.hasNext();) { Object key = iter.next(); answer.put(key, map.get(key)); } return answer; } /** * Looks up an item in a Map for the given key and returns the value - unless * there is no entry for the given key in which case add the default value * to the map and return that. * * @param map a Map * @param key the key to lookup the value of * @param defaultValue the value to return and add to the map for this key if * there is no entry for the given key * @return the value of the given key or the default value, added to the map if the * key did not exist */ public static Object get(Map map, Object key, Object defaultValue) { Object answer = map.get(key); if (answer == null) { answer = defaultValue; map.put(key, answer); } return answer; } /** * Support the range subscript operator for an Array * * @param array an Array of Objects * @param range a Range * @return a range of a list from the range's from index up to but not * including the ranges's to value */ public static List getAt(Object[] array, Range range) { List list = Arrays.asList(array); return getAt(list, range); } /** * Support the subscript operator for an Array * * @param array an Array of Objects * @param idx an index * @return the value at the given index */ public static Object getAt(Object[] array, int idx) { return array[normaliseIndex(idx, array.length)]; } /** * Support the subscript operator for an Array * * @param array an Array of Objects * @param idx an index * @param value an Object to put at the given index */ public static void putAt(Object[] array, int idx, Object value) { if (value instanceof Number) { Class arrayComponentClass = array.getClass().getComponentType(); if (!arrayComponentClass.equals(value.getClass())) { Object newVal = InvokerHelper.asType(value, arrayComponentClass); array[normaliseIndex(idx, array.length)] = newVal; return; } } array[normaliseIndex(idx, array.length)] = value; } /** * Allows conversion of arrays into a mutable List * * @param array an Array of Objects * @return the array as a List */ public static List toList(Object[] array) { int size = array.length; List list = new ArrayList(size); for (int i = 0; i < size; i++) { list.add(array[i]); } return list; } /** * Support the subscript operator for a List * * @param self a List * @param idx an index * @return the value at the given index */ public static Object getAt(List self, int idx) { int size = self.size(); int i = normaliseIndex(idx, size); if (i < size) { return self.get(i); } else { return null; } } /** * A helper method to allow lists to work with subscript operators * * @param self a List * @param idx an index * @param value the value to put at the given index */ public static void putAt(List self, int idx, Object value) { int size = self.size(); idx = normaliseIndex(idx, size); if (idx < size) { self.set(idx, value); } else { while (size < idx) { self.add(size++, null); } self.add(idx, value); } } /** * Support the subscript operator for a List * * @param self a Map * @param key an Object as a key for the map * @return the value corresponding to the given key */ public static Object getAt(Map self, Object key) { return self.get(key); } /** * A helper method to allow lists to work with subscript operators * * @param self a Map * @param key an Object as a key for the map * @return the value corresponding to the given key */ public static Object putAt(Map self, Object key, Object value) { return self.put(key, value); } /** * This converts a possibly negative index to a real index into the array. * * @param i * @param size * @return */ protected static int normaliseIndex(int i, int size) { int temp = i; if (i < 0) { i += size; } if (i < 0) { throw new ArrayIndexOutOfBoundsException("Negative array index [" + temp + "] too large for array size " + size); } return i; } /** * Support the subscript operator for List * * @param coll a Collection * @param property a String * @return a List */ public static List getAt(Collection coll, String property) { List answer = new ArrayList(coll.size()); for (Iterator iter = coll.iterator(); iter.hasNext();) { Object item = iter.next(); Object value = InvokerHelper.getProperty(item, property); if (value instanceof Collection) { answer.addAll((Collection) value); } else { answer.add(value); } } return answer; } /** * A convenience method for creating an immutable map * * @param self a Map * @return an immutable Map */ public static Map asImmutable(Map self) { return Collections.unmodifiableMap(self); } /** * A convenience method for creating an immutable sorted map * * @param self a SortedMap * @return an immutable SortedMap */ public static SortedMap asImmutable(SortedMap self) { return Collections.unmodifiableSortedMap(self); } /** * A convenience method for creating an immutable list * * @param self a List * @return an immutable List */ public static List asImmutable(List self) { return Collections.unmodifiableList(self); } /** * A convenience method for creating an immutable list * * @param self a Set * @return an immutable Set */ public static Set asImmutable(Set self) { return Collections.unmodifiableSet(self); } /** * A convenience method for creating an immutable sorted set * * @param self a SortedSet * @return an immutable SortedSet */ public static SortedSet asImmutable(SortedSet self) { return Collections.unmodifiableSortedSet(self); } /** * A convenience method for creating an immutable Collection * * @param self a Collection * @return an immutable Collection */ public static Collection asImmutable(Collection self) { return Collections.unmodifiableCollection(self); } /** * A convenience method for creating a synchronized Map * * @param self a Map * @return a synchronized Map */ public static Map asSynchronized(Map self) { return Collections.synchronizedMap(self); } /** * A convenience method for creating a synchronized SortedMap * * @param self a SortedMap * @return a synchronized SortedMap */ public static SortedMap asSynchronized(SortedMap self) { return Collections.synchronizedSortedMap(self); } /** * A convenience method for creating a synchronized Collection * * @param self a Collection * @return a synchronized Collection */ public static Collection asSynchronized(Collection self) { return Collections.synchronizedCollection(self); } /** * A convenience method for creating a synchronized List * * @param self a List * @return a synchronized List */ public static List asSynchronized(List self) { return Collections.synchronizedList(self); } /** * A convenience method for creating a synchronized Set * * @param self a Set * @return a synchronized Set */ public static Set asSynchronized(Set self) { return Collections.synchronizedSet(self); } /** * A convenience method for creating a synchronized SortedSet * * @param self a SortedSet * @return a synchronized SortedSet */ public static SortedSet asSynchronized(SortedSet self) { return Collections.synchronizedSortedSet(self); } /** * Sorts the given collection into a sorted list * * @param self the collection to be sorted * @return the sorted collection as a List */ public static List sort(Collection self) { List answer = asList(self); Collections.sort(answer); return answer; } /** * Avoids doing unnecessary work when sorting an already sorted set * * @param self * @return the sorted set */ public static SortedSet sort(SortedSet self) { return self; } /** * A convenience method for sorting a List * * @param self a List to be sorted * @return the sorted List */ public static List sort(List self) { Collections.sort(self); return self; } /** * Removes the last item from the List. Using add() and pop() * is similar to push and pop on a Stack. * * @param self a List * @return the item removed from the List * @throws UnsupportedOperationException if the list is empty and you try to pop() it. */ public static Object pop(List self) { if (self.isEmpty()) { throw new UnsupportedOperationException("Cannot pop() an empty List"); } return self.remove(self.size() - 1); } /** * A convenience method for sorting a List with a specific comparator * * @param self a List * @param comparator a Comparator used for the comparison * @return a sorted List */ public static List sort(List self, Comparator comparator) { Collections.sort(self, comparator); return self; } /** * A convenience method for sorting a Collection with a specific comparator * * @param self a collection to be sorted * @param comparator a Comparator used for the comparison * @return a newly created sorted List */ public static List sort(Collection self, Comparator comparator) { return sort(asList(self), comparator); } /** * A convenience method for sorting a List using a closure as a comparator * * @param self a List * @param closure a Closure used as a comparator * @return a sorted List */ public static List sort(List self, Closure closure) { // use a comparator of one item or two Class[] params = closure.getParameterTypes(); if (params.length == 1) { Collections.sort(self, new OrderBy(closure)); } else { Collections.sort(self, new ClosureComparator(closure)); } return self; } /** * A convenience method for sorting a Collection using a closure as a comparator * * @param self a Collection to be sorted * @param closure a Closure used as a comparator * @return a newly created sorted List */ public static List sort(Collection self, Closure closure) { return sort(asList(self), closure); } /** * Converts the given collection into a List * * @param self a collection to be converted into a List * @return a newly created List if this collection is not already a List */ public static List asList(Collection self) { if (self instanceof List) { return (List) self; } else { return new ArrayList(self); } } /** * Reverses the list * * @param self a List * @return a reversed List */ public static List reverse(List self) { int size = self.size(); List answer = new ArrayList(size); ListIterator iter = self.listIterator(size); while (iter.hasPrevious()) { answer.add(iter.previous()); } return answer; } /** * Create a List as a union of both Collections * * @param left the left Collection * @param right the right Collection * @return a List */ public static List plus(Collection left, Collection right) { List answer = new ArrayList(left.size() + right.size()); answer.addAll(left); answer.addAll(right); return answer; } /** * Create a List as a union of a Collection and an Object * * @param left a Collection * @param right an object to append * @return a List */ public static List plus(Collection left, Object right) { List answer = new ArrayList(left.size() + 1); answer.addAll(left); answer.add(right); return answer; } /** * Create a List composed of the same elements repeated a certain number of times. * * @param self a Collection * @param factor the number of times to append * @return a List */ public static List multiply(Collection self, Number factor) { int size = factor.intValue(); List answer = new ArrayList(self.size() * size); for (int i = 0; i < size; i++) { answer.addAll(self); } return answer; } /** * Create a List composed of the intersection of both collections * * @param left a List * @param right a Collection * @return a List as an intersection of both collections */ public static List intersect(List left, Collection right) { if (left.size() == 0) return new ArrayList(); boolean nlgnSort = sameType(new Collection[]{left, right}); ArrayList result = new ArrayList(); //creates the collection to look for values. Collection pickFrom = nlgnSort ? (Collection) new TreeSet(left) : left; for (Iterator iter = right.iterator(); iter.hasNext();) { final Object o = iter.next(); if (pickFrom.contains(o)) result.add(o); } return result; } /** * Create a List composed of the elements of the first list minus the elements of the collection * * @param self a List * @param removeMe a Collection of elements to remove * @return a List with the common elements removed */ public static List minus(List self, Collection removeMe) { if (self.size() == 0) return new ArrayList(); boolean nlgnSort = sameType(new Collection[]{self, removeMe}); //we can't use the same tactic as for intersection //since AbstractCollection only does a remove on the first //element it encounter. if (nlgnSort) { //n*log(n) version Set answer = new TreeSet(self); answer.removeAll(removeMe); return new ArrayList(answer); } else { //n*n version List tmpAnswer = new LinkedList(self); for (Iterator iter = tmpAnswer.iterator(); iter.hasNext();) { Object element = iter.next(); //boolean removeElement = false; for (Iterator iterator = removeMe.iterator(); iterator.hasNext();) { if (element.equals(iterator.next())) { iter.remove(); } } } //remove duplicates //can't use treeset since the base classes are different List answer = new LinkedList(); Object[] array = tmpAnswer.toArray(new Object[tmpAnswer.size()]); for (int i = 0; i < array.length; i++) { if (array[i] != null) { for (int j = i + 1; j < array.length; j++) { if (array[i].equals(array[j])) { array[j] = null; } } answer.add(array[i]); } } return new ArrayList(answer); } } /** * Flatten a list * * @param self a List * @return a flattened List */ public static List flatten(List self) { return new ArrayList(flatten(self, new LinkedList())); } /** * Iterate over each element of the list in the reverse order. * * @param self a List * @param closure a closure */ public static void reverseEach(List self, Closure closure) { List reversed = reverse(self); for (Iterator iter = reversed.iterator(); iter.hasNext();) { closure.call(iter.next()); } } private static List flatten(Collection elements, List addTo) { Iterator iter = elements.iterator(); while (iter.hasNext()) { Object element = iter.next(); if (element instanceof Collection) { flatten((Collection) element, addTo); } else if (element instanceof Map) { flatten(((Map) element).values(), addTo); } else { addTo.add(element); } } return addTo; } /** * Overloads the left shift operator to provide an easy way to append objects to a list * * @param self a Collection * @param value an Object to be added to the collection. * @return a Collection with an Object added to it. */ public static Collection leftShift(Collection self, Object value) { self.add(value); return self; } /** * Overloads the left shift operator to provide an easy way to append multiple * objects as string representations to a String * * @param self a String * @param value an Obect * @return a StringWriter */ public static StringWriter leftShift(String self, Object value) { StringWriter answer = createStringWriter(self); try { leftShift(answer, value); } catch (IOException e) { throw new StringWriterIOException(e); } return answer; } protected static StringWriter createStringWriter(String self) { StringWriter answer = new StringWriter(); answer.write(self); return answer; } protected static StringBufferWriter createStringBufferWriter(StringBuffer self) { return new StringBufferWriter(self); } /** * Overloads the left shift operator to provide an easy way to append multiple * objects as string representations to a StringBuffer * * @param self a StringBuffer * @param value a value to append * @return a StringWriter */ public static Writer leftShift(StringBuffer self, Object value) { StringBufferWriter answer = createStringBufferWriter(self); try { leftShift(answer, value); } catch (IOException e) { throw new StringWriterIOException(e); } return answer; } /** * Overloads the left shift operator to provide an append mechanism to add things to a writer * * @param self a Writer * @param value a value to append * @return a StringWriter */ public static Writer leftShift(Writer self, Object value) throws IOException { InvokerHelper.write(self, value); return self; } /** * Implementation of the left shift operator for integral types. Non integral * Number types throw UnsupportedOperationException. */ public static Number leftShift(Number left, Number right) { return NumberMath.leftShift(left, right); } /** * Implementation of the right shift operator for integral types. Non integral * Number types throw UnsupportedOperationException. */ public static Number rightShift(Number left, Number right) { return NumberMath.rightShift(left, right); } /** * Implementation of the right shift (unsigned) operator for integral types. Non integral * Number types throw UnsupportedOperationException. */ public static Number rightShiftUnsigned(Number left, Number right) { return NumberMath.rightShiftUnsigned(left, right); } /** * A helper method so that dynamic dispatch of the writer.write(object) method * will always use the more efficient Writable.writeTo(writer) mechanism if the * object implements the Writable interface. * * @param self a Writer * @param writable an object implementing the Writable interface */ public static void write(Writer self, Writable writable) throws IOException { writable.writeTo(self); } /** * Overloads the left shift operator to provide an append mechanism to add things to a stream * * @param self an OutputStream * @param value a value to append * @return a Writer */ public static Writer leftShift(OutputStream self, Object value) throws IOException { OutputStreamWriter writer = new FlushingStreamWriter(self); leftShift(writer, value); return writer; } /** * Overloads the left shift operator to provide an append mechanism to add bytes to a stream * * @param self an OutputStream * @param value a value to append * @return an OutputStream */ public static OutputStream leftShift(OutputStream self, byte[] value) throws IOException { self.write(value); self.flush(); return self; } private static boolean sameType(Collection[] cols) { List all = new LinkedList(); for (int i = 0; i < cols.length; i++) { all.addAll(cols[i]); } if (all.size() == 0) return true; Object first = all.get(0); //trying to determine the base class of the collections //special case for Numbers Class baseClass; if (first instanceof Number) { baseClass = Number.class; } else { baseClass = first.getClass(); } for (int i = 0; i < cols.length; i++) { for (Iterator iter = cols[i].iterator(); iter.hasNext();) { if (!baseClass.isInstance(iter.next())) { return false; } } } return true; } // Primitive type array methods public static Object getAt(byte[] array, int idx) { return primitiveArrayGet(array, idx); } public static Object getAt(char[] array, int idx) { return primitiveArrayGet(array, idx); } public static Object getAt(short[] array, int idx) { return primitiveArrayGet(array, idx); } public static Object getAt(int[] array, int idx) { return primitiveArrayGet(array, idx); } public static Object getAt(long[] array, int idx) { return primitiveArrayGet(array, idx); } public static Object getAt(float[] array, int idx) { return primitiveArrayGet(array, idx); } public static Object getAt(double[] array, int idx) { return primitiveArrayGet(array, idx); } public static Object getAt(byte[] array, Range range) { return primitiveArrayGet(array, range); } public static Object getAt(char[] array, Range range) { return primitiveArrayGet(array, range); } public static Object getAt(short[] array, Range range) { return primitiveArrayGet(array, range); } public static Object getAt(int[] array, Range range) { return primitiveArrayGet(array, range); } public static Object getAt(long[] array, Range range) { return primitiveArrayGet(array, range); } public static Object getAt(float[] array, Range range) { return primitiveArrayGet(array, range); } public static Object getAt(double[] array, Range range) { return primitiveArrayGet(array, range); } public static Object getAt(byte[] array, Collection indices) { return primitiveArrayGet(array, indices); } public static Object getAt(char[] array, Collection indices) { return primitiveArrayGet(array, indices); } public static Object getAt(short[] array, Collection indices) { return primitiveArrayGet(array, indices); } public static Object getAt(int[] array, Collection indices) { return primitiveArrayGet(array, indices); } public static Object getAt(long[] array, Collection indices) { return primitiveArrayGet(array, indices); } public static Object getAt(float[] array, Collection indices) { return primitiveArrayGet(array, indices); } public static Object getAt(double[] array, Collection indices) { return primitiveArrayGet(array, indices); } public static void putAt(byte[] array, int idx, Object newValue) { primitiveArrayPut(array, idx, newValue); } public static void putAt(char[] array, int idx, Object newValue) { primitiveArrayPut(array, idx, newValue); } public static void putAt(short[] array, int idx, Object newValue) { primitiveArrayPut(array, idx, newValue); } public static void putAt(int[] array, int idx, Object newValue) { primitiveArrayPut(array, idx, newValue); } public static void putAt(long[] array, int idx, Object newValue) { primitiveArrayPut(array, idx, newValue); } public static void putAt(float[] array, int idx, Object newValue) { primitiveArrayPut(array, idx, newValue); } public static void putAt(double[] array, int idx, Object newValue) { primitiveArrayPut(array, idx, newValue); } public static int size(byte[] array) { return Array.getLength(array); } public static int size(char[] array) { return Array.getLength(array); } public static int size(short[] array) { return Array.getLength(array); } public static int size(int[] array) { return Array.getLength(array); } public static int size(long[] array) { return Array.getLength(array); } public static int size(float[] array) { return Array.getLength(array); } public static int size(double[] array) { return Array.getLength(array); } public static List toList(byte[] array) { return InvokerHelper.primitiveArrayToList(array); } public static List toList(char[] array) { return InvokerHelper.primitiveArrayToList(array); } public static List toList(short[] array) { return InvokerHelper.primitiveArrayToList(array); } public static List toList(int[] array) { return InvokerHelper.primitiveArrayToList(array); } public static List toList(long[] array) { return InvokerHelper.primitiveArrayToList(array); } public static List toList(float[] array) { return InvokerHelper.primitiveArrayToList(array); } public static List toList(double[] array) { return InvokerHelper.primitiveArrayToList(array); } private static final char[] tTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray(); public static Writable encodeBase64(final Byte[] data) { return encodeBase64(InvokerHelper.convertToByteArray(data)); } /** * Produce a Writable object which writes the base64 encoding of the byte array * Calling toString() on the result rerurns the encoding as a String * * @param data byte array to be encoded * @return object which will write the base64 encoding of the byte array */ public static Writable encodeBase64(final byte[] data) { return new Writable() { public Writer writeTo(final Writer writer) throws IOException { int charCount = 0; final int dLimit = (data.length / 3) * 3; for (int dIndex = 0; dIndex != dLimit; dIndex += 3) { int d = ((data[dIndex] & 0XFF) << 16) | ((data[dIndex + 1] & 0XFF) << 8) | (data[dIndex + 2] & 0XFF); writer.write(tTable[d >> 18]); writer.write(tTable[(d >> 12) & 0X3F]); writer.write(tTable[(d >> 6) & 0X3F]); writer.write(tTable[d & 0X3F]); if (++charCount == 18) { writer.write('\n'); charCount = 0; } } if (dLimit != data.length) { int d = (data[dLimit] & 0XFF) << 16; if (dLimit + 1 != data.length) { d |= (data[dLimit + 1] & 0XFF) << 8; } writer.write(tTable[d >> 18]); writer.write(tTable[(d >> 12) & 0X3F]); writer.write((dLimit + 1 < data.length) ? tTable[(d >> 6) & 0X3F] : '='); writer.write('='); } return writer; } public String toString() { StringWriter buffer = new StringWriter(); try { writeTo(buffer); } catch (IOException e) { throw new RuntimeException(e); // TODO: change this exception type } return buffer.toString(); } }; } private static final byte[] translateTable = ( "\u0042\u0042\u0042\u0042\u0042\u0042\u0042\u0042" // \t \n \r + "\u0042\u0042\u0041\u0041\u0042\u0042\u0041\u0042" + "\u0042\u0042\u0042\u0042\u0042\u0042\u0042\u0042" + "\u0042\u0042\u0042\u0042\u0042\u0042\u0042\u0042" // sp ! " + "\u0041\u0042\u0042\u0042\u0042\u0042\u0042\u0042" + "\u0042\u0042\u0042\u003E\u0042\u0042\u0042\u003F" // 0 1 2 3 4 5 6 7 + "\u0034\u0035\u0036\u0037\u0038\u0039\u003A\u003B" // 8 9 : ; < = > ? + "\u003C\u003D\u0042\u0042\u0042\u0040\u0042\u0042" // @ A B C D E F G + "\u0042\u0000\u0001\u0002\u0003\u0004\u0005\u0006" // H I J K L M N O + "\u0007\u0008\t\n\u000B\u000C\r\u000E" // P Q R S T U V W + "\u000F\u0010\u0011\u0012\u0013\u0014\u0015\u0016" // X Y Z [ \ ] ^ _ + "\u0017\u0018\u0019\u0042\u0042\u0042\u0042\u0042" // ' a b c d e f g + "\u0042\u001A\u001B\u001C\u001D\u001E\u001F\u0020" // h i j k l m n o p + "\u0021\"\u0023\u0024\u0025\u0026\u0027\u0028" // p q r s t u v w + "\u0029\u002A\u002B\u002C\u002D\u002E\u002F\u0030" // x y z + "\u0031\u0032\u0033").getBytes(); /** * Decode the Sting from base64 into a byte array * * @param value the string to be decoded * @return the decoded bytes as an array */ public static byte[] decodeBase64(final String value) { int byteShift = 4; int tmp = 0; boolean done = false; final StringBuffer buffer = new StringBuffer(); for (int i = 0; i != value.length(); i++) { final char c = value.charAt(i); final int sixBit = (c < 123) ? translateTable[c] : 66; if (sixBit < 64) { if (done) throw new RuntimeException("= character not at end of base64 value"); // TODO: change this exception type tmp = (tmp << 6) | sixBit; if (byteShift buffer.append((char) ((tmp >> (byteShift * 2)) & 0XFF)); } } else if (sixBit == 64) { byteShift done = true; } else if (sixBit == 66) { // RFC 2045 says that I'm allowed to take the presence of // these characters as evedence of data corruption // So I will throw new RuntimeException("bad character in base64 value"); // TODO: change this exception type } if (byteShift == 0) byteShift = 4; } try { return buffer.toString().getBytes("ISO-8859-1"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Base 64 decode produced byte values > 255"); // TODO: change this exception type } } /** * Implements the getAt(int) method for primitve type arrays */ protected static Object primitiveArrayGet(Object array, int idx) { return Array.get(array, normaliseIndex(idx, Array.getLength(array))); } /** * Implements the getAt(Range) method for primitve type arrays */ protected static List primitiveArrayGet(Object array, Range range) { List answer = new ArrayList(); for (Iterator iter = range.iterator(); iter.hasNext();) { int idx = InvokerHelper.asInt(iter.next()); answer.add(primitiveArrayGet(array, idx)); } return answer; } /** * Implements the getAt(Collection) method for primitve type arrays */ protected static List primitiveArrayGet(Object self, Collection indices) { List answer = new ArrayList(); for (Iterator iter = indices.iterator(); iter.hasNext();) { Object value = iter.next(); if (value instanceof Range) { answer.addAll(primitiveArrayGet(self, (Range) value)); } else if (value instanceof List) { answer.addAll(primitiveArrayGet(self, (List) value)); } else { int idx = InvokerHelper.asInt(value); answer.add(primitiveArrayGet(self, idx)); } } return answer; } /** * Implements the set(int idx) method for primitve type arrays */ protected static void primitiveArrayPut(Object array, int idx, Object newValue) { Array.set(array, normaliseIndex(idx, Array.getLength(array)), newValue); } // String methods /** * Converts the given string into a Character object * using the first character in the string * * @param self a String * @return the first Character */ public static Character toCharacter(String self) { /** @todo use cache? */ return new Character(self.charAt(0)); } /** * Tokenize a String * * @param self a String * @param token the delimiter * @return a List of tokens */ public static List tokenize(String self, String token) { return InvokerHelper.asList(new StringTokenizer(self, token)); } /** * Tokenize a String (with a whitespace as delimiter) * * @param self a String * @return a List of tokens */ public static List tokenize(String self) { return InvokerHelper.asList(new StringTokenizer(self)); } /** * Appends a String * * @param left a String * @param value a String * @return a String */ public static String plus(String left, Object value) { //return left + value; return left + toString(value); } /** * Appends a String * * @param value a Number * @param right a String * @return a String */ public static String plus(Number value, String right) { return toString(value) + right; } /** * Appends a String * * @param left a StringBuffer * @param value a String * @return a String */ public static String plus(StringBuffer left, String value) { return left + value; } /** * Remove a part of a String * * @param left a String * @param value a String part to remove * @return a String minus the part to be removed */ public static String minus(String left, Object value) { String text = toString(value); return left.replaceFirst(text, ""); } /** * Provide an implementation of contains() like Collection to make Strings more polymorphic * This method is not required on JDK 1.5 onwards * * @param self a String * @param text a String to look for * @return true if this string contains the given text */ public static boolean contains(String self, String text) { int idx = self.indexOf(text); return idx >= 0; } /** * Count the number of occurencies of a substring * * @param self a String * @param text a substring * @return the number of occurrencies of the given string inside this String */ public static int count(String self, String text) { int answer = 0; for (int idx = 0; true; idx++) { idx = self.indexOf(text, idx); if (idx >= 0) { ++answer; } else { break; } } return answer; } /** * This method is called by the ++ operator for the class String. * It increments the last character in the given string. If the * character in the string is Character.MAX_VALUE a Character.MIN_VALUE * will be appended. The empty string is incremented to a string * consisting of the character Character.MIN_VALUE. * * @param self a String * @return an incremented String */ public static String next(String self) { StringBuffer buffer = new StringBuffer(self); if (buffer.length()==0) { buffer.append(Character.MIN_VALUE); } else { char last = buffer.charAt(buffer.length()-1); if (last==Character.MAX_VALUE) { buffer.append(Character.MIN_VALUE); } else { char next = last; next++; buffer.setCharAt(buffer.length()-1,next); } } return buffer.toString(); } /** * This method is called by the -- operator for the class String. * It decrements the last character in the given string. If the * character in the string is Character.MIN_VALUE it will be deleted. * The empty string can't be decremented. * * @param self a String * @return a String with a decremented digit at the end */ public static String previous(String self) { StringBuffer buffer = new StringBuffer(self); if (buffer.length()==0) throw new IllegalArgumentException("the string is empty"); char last = buffer.charAt(buffer.length()-1); if (last==Character.MIN_VALUE) { buffer.deleteCharAt(buffer.length()-1); } else { char next = last; next buffer.setCharAt(buffer.length()-1,next); } return buffer.toString(); } /** * Executes the given string as a command line process. For more control * over the process mechanism in JDK 1.5 you can use java.lang.ProcessBuilder. * * @param self a command line String * @return the Process which has just started for this command line string */ public static Process execute(String self) throws IOException { return Runtime.getRuntime().exec(self); } public static String multiply(String self, Number factor) { int size = factor.intValue(); if (size == 0) return ""; else if (size < 0) { throw new IllegalArgumentException("multiply() should be called with a number of 0 or greater not: " + size); } StringBuffer answer = new StringBuffer(self); for (int i = 1; i < size; i++) { answer.append(self); } return answer.toString(); } protected static String toString(Object value) { return (value == null) ? "null" : value.toString(); } // Number based methods /** * Increment a Character by one * * @param self a Character * @return an incremented Number */ public static Number next(Character self) { return plus(self, ONE); } /** * Increment a Number by one * * @param self a Number * @return an incremented Number */ public static Number next(Number self) { return plus(self, ONE); } /** * Decrement a Character by one * * @param self a Character * @return a decremented Number */ public static Number previous(Character self) { return minus(self, ONE); } /** * Decrement a Number by one * * @param self a Number * @return a decremented Number */ public static Number previous(Number self) { return minus(self, ONE); } /** * Add a Character and a Number * * @param left a Character * @param right a Number * @return the addition of the Character and the Number */ public static Number plus(Character left, Number right) { return plus(new Integer(left.charValue()), right); } /** * Add a Number and a Character * * @param left a Number * @param right a Character * @return the addition of the Character and the Number */ public static Number plus(Number left, Character right) { return plus(left, new Integer(right.charValue())); } /** * Add two Characters * * @param left a Character * @param right a Character * @return the addition of both Characters */ public static Number plus(Character left, Character right) { return plus(new Integer(left.charValue()), right); } /** * Add two Numbers * * @param left a Number * @param right another Number to add * @return the addition of both Numbers */ public static Number plus(Number left, Number right) { return NumberMath.add(left, right); } /** * Compare a Character and a Number * * @param left a Character * @param right a Number * @return the result of the comparison */ public static int compareTo(Character left, Number right) { return compareTo(new Integer(left.charValue()), right); } /** * Compare a Number and a Character * * @param left a Number * @param right a Character * @return the result of the comparison */ public static int compareTo(Number left, Character right) { return compareTo(left, new Integer(right.charValue())); } /** * Compare two Characters * * @param left a Character * @param right a Character * @return the result of the comparison */ public static int compareTo(Character left, Character right) { return compareTo(new Integer(left.charValue()), right); } /** * Compare two Numbers * * @param left a Number * @param right another Number to compare to * @return the comparision of both numbers */ public static int compareTo(Number left, Number right) { /** @todo maybe a double dispatch thing to handle new large numbers? */ return NumberMath.compareTo(left, right); } /** * Subtract a Number from a Character * * @param left a Character * @param right a Number * @return the addition of the Character and the Number */ public static Number minus(Character left, Number right) { return minus(new Integer(left.charValue()), right); } /** * Subtract a Character from a Number * * @param left a Number * @param right a Character * @return the addition of the Character and the Number */ public static Number minus(Number left, Character right) { return minus(left, new Integer(right.charValue())); } /** * Subtraction two Characters * * @param left a Character * @param right a Character * @return the addition of both Characters */ public static Number minus(Character left, Character right) { return minus(new Integer(left.charValue()), right); } /** * Substraction of two Numbers * * @param left a Number * @param right another Number to substract to the first one * @return the substraction */ public static Number minus(Number left, Number right) { return NumberMath.subtract(left, right); } /** * Multiply a Character by a Number * * @param left a Character * @param right a Number * @return the multiplication of both */ public static Number multiply(Character left, Number right) { return multiply(new Integer(left.charValue()), right); } /** * Multiply a Number by a Character * * @param left a Number * @param right a Character * @return the multiplication of both */ public static Number multiply(Number left, Character right) { return multiply(left, new Integer(right.charValue())); } /** * Multiply two Characters * * @param left a Character * @param right another Character * @return the multiplication of both */ public static Number multiply(Character left, Character right) { return multiply(new Integer(left.charValue()), right); } /** * Multiply two Numbers * * @param left a Number * @param right another Number * @return the multiplication of both */ //Note: This method is NOT called if left AND right are both BigIntegers or BigDecimals because //those classes implement a method with a better exact match. public static Number multiply(Number left, Number right) { return NumberMath.multiply(left, right); } /** * Power of a Number to a certain exponent * * @param self a Number * @param exponent a Number exponent * @return a Number to the power of a certain exponent */ public static Number power(Number self, Number exponent) { double answer = Math.pow(self.doubleValue(), exponent.doubleValue()); if (NumberMath.isFloatingPoint(self) || NumberMath.isFloatingPoint(exponent) || answer < 1) { return new Double(answer); } else if (NumberMath.isLong(self) || NumberMath.isLong(exponent) || answer > Integer.MAX_VALUE) { return new Long((long) answer); } else { return new Integer((int) answer); } } /** * Divide a Character by a Number * * @param left a Character * @param right a Number * @return the multiplication of both */ public static Number div(Character left, Number right) { return div(new Integer(left.charValue()), right); } /** * Divide a Number by a Character * * @param left a Number * @param right a Character * @return the multiplication of both */ public static Number div(Number left, Character right) { return div(left, new Integer(right.charValue())); } /** * Divide two Characters * * @param left a Character * @param right another Character * @return the multiplication of both */ public static Number div(Character left, Character right) { return div(new Integer(left.charValue()), right); } /** * Divide two Numbers * * @param left a Number * @param right another Number * @return a Number resulting of the divide operation */ //Method name changed from 'divide' to avoid collision with BigInteger method that has //different semantics. We want a BigDecimal result rather than a BigInteger. public static Number div(Number left, Number right) { return NumberMath.divide(left, right); } /** * Integer Divide a Character by a Number * * @param left a Character * @param right a Number * @return the integer division of both */ public static Number intdiv(Character left, Number right) { return intdiv(new Integer(left.charValue()), right); } /** * Integer Divide a Number by a Character * * @param left a Number * @param right a Character * @return the integer division of both */ public static Number intdiv(Number left, Character right) { return intdiv(left, new Integer(right.charValue())); } /** * Integer Divide two Characters * * @param left a Character * @param right another Character * @return the integer division of both */ public static Number intdiv(Character left, Character right) { return intdiv(new Integer(left.charValue()), right); } /** * Integer Divide two Numbers * * @param left a Number * @param right another Number * @return a Number (an Integer) resulting of the integer division operation */ public static Number intdiv(Number left, Number right) { return NumberMath.intdiv(left, right); } /** * Bitwise OR together two numbers * * @param left a Number * @param right another Number to bitwise OR * @return the bitwise OR of both Numbers */ public static Number or(Number left, Number right) { return NumberMath.or(left, right); } /** * Bitwise AND together two Numbers * * @param left a Number * @param right another Number to bitwse AND * @return the bitwise AND of both Numbers */ public static Number and(Number left, Number right) { return NumberMath.and(left, right); } /** * Performs a division modulus operation * * @param left a Number * @param right another Number to mod * @return the modulus result */ public static Number mod(Number left, Number right) { return NumberMath.mod(left, right); } /** * Negates the number * * @param left a Number * @return the negation of the number */ public static Number negate(Number left) { return NumberMath.negate(left); } /** * Iterates a number of times * * @param self a Number * @param closure the closure to call a number of times */ public static void times(Number self, Closure closure) { for (int i = 0, size = self.intValue(); i < size; i++) { closure.call(new Integer(i)); if (closure.getDirective() == Closure.DONE) { break; } } } /** * Iterates from this number up to the given number * * @param self a Number * @param to another Number to go up to * @param closure the closure to call */ public static void upto(Number self, Number to, Closure closure) { for (int i = self.intValue(), size = to.intValue(); i <= size; i++) { closure.call(new Integer(i)); } } /** * Iterates from this number up to the given number using a step increment * * @param self a Number to start with * @param to a Number to go up to * @param stepNumber a Number representing the step increment * @param closure the closure to call */ public static void step(Number self, Number to, Number stepNumber, Closure closure) { for (int i = self.intValue(), size = to.intValue(), step = stepNumber.intValue(); i < size; i += step) { closure.call(new Integer(i)); } } /** * Get the absolute value * * @param number a Number * @return the absolute value of that Number */ //Note: This method is NOT called if number is a BigInteger or BigDecimal because //those classes implement a method with a better exact match. public static int abs(Number number) { return Math.abs(number.intValue()); } /** * Get the absolute value * * @param number a Long * @return the absolute value of that Long */ public static long abs(Long number) { return Math.abs(number.longValue()); } /** * Get the absolute value * * @param number a Float * @return the absolute value of that Float */ public static float abs(Float number) { return Math.abs(number.floatValue()); } /** * Get the absolute value * * @param number a Double * @return the absolute value of that Double */ public static double abs(Double number) { return Math.abs(number.doubleValue()); } /** * Get the absolute value * * @param number a Float * @return the absolute value of that Float */ public static int round(Float number) { return Math.round(number.floatValue()); } /** * Round the value * * @param number a Double * @return the absolute value of that Double */ public static long round(Double number) { return Math.round(number.doubleValue()); } /** * Parse a String into an Integer * * @param self a String * @return an Integer */ public static Integer toInteger(String self) { return Integer.valueOf(self); } /** * Parse a String into a Long * * @param self a String * @return a Long */ public static Long toLong(String self) { return Long.valueOf(self); } /** * Parse a String into a Float * * @param self a String * @return a Float */ public static Float toFloat(String self) { return Float.valueOf(self); } /** * Parse a String into a Double * * @param self a String * @return a Double */ public static Double toDouble(String self) { return Double.valueOf(self); } /** * Transform a Number into an Integer * * @param self a Number * @return an Integer */ public static Integer toInteger(Number self) { return new Integer(self.intValue()); } // Date methods /** * Increments a Date by a day * * @param self a Date * @return the next days date */ public static Date next(Date self) { return plus(self, 1); } /** * Decrement a Date by a day * * @param self a Date * @return the previous days date */ public static Date previous(Date self) { return minus(self, 1); } /** * Adds a number of days to this date and returns the new date * * @param self a Date * @param days the number of days to increase * @return the new date */ public static Date plus(Date self, int days) { Calendar calendar = (Calendar) Calendar.getInstance().clone(); calendar.setTime(self); calendar.add(Calendar.DAY_OF_YEAR, days); return calendar.getTime(); } /** * Subtracts a number of days from this date and returns the new date * * @param self a Date * @return the new date */ public static Date minus(Date self, int days) { return plus(self, -days); } // File and stream based methods /** * Iterates through the given file line by line * * @param self a File * @param closure a closure * @throws IOException */ public static void eachLine(File self, Closure closure) throws IOException { eachLine(newReader(self), closure); } /** * Iterates through the given reader line by line * * @param self a Reader * @param closure a closure * @throws IOException */ public static void eachLine(Reader self, Closure closure) throws IOException { BufferedReader br = null; if (self instanceof BufferedReader) br = (BufferedReader) self; else br = new BufferedReader(self); try { while (true) { String line = br.readLine(); if (line == null) { break; } else { closure.call(line); } } br.close(); } catch (IOException e) { if (self != null) { try { br.close(); } catch (Exception e2) { // ignore as we're already throwing } throw e; } } } /** * Iterates through the given file line by line, splitting on the seperator * * @param self a File * @param sep a String separator * @param closure a closure * @throws IOException */ public static void splitEachLine(File self, String sep, Closure closure) throws IOException { splitEachLine(newReader(self), sep, closure); } /** * Iterates through the given reader line by line, splitting on the seperator * * @param self a Reader * @param sep a String separator * @param closure a closure * @throws IOException */ public static void splitEachLine(Reader self, String sep, Closure closure) throws IOException { BufferedReader br = null; if (self instanceof BufferedReader) br = (BufferedReader) self; else br = new BufferedReader(self); List args = new ArrayList(); try { while (true) { String line = br.readLine(); if (line == null) { break; } else { List vals = Arrays.asList(line.split(sep)); args.clear(); args.add(vals); closure.call(args); } } br.close(); } catch (IOException e) { if (self != null) { try { br.close(); } catch (Exception e2) { // ignore as we're already throwing } throw e; } } } /** * Read a single, whole line from the given Reader * * @param self a Reader * @return a line * @throws IOException */ public static String readLine(Reader self) throws IOException { BufferedReader br = null; if (self instanceof BufferedReader) { br = (BufferedReader) self; } else { br = new BufferedReader(self); } return br.readLine(); } /** * Read a single, whole line from the given InputStream * * @param stream an InputStream * @return a line * @throws IOException */ public static String readLine(InputStream stream) throws IOException { return readLine(new InputStreamReader(stream)); } /** * Reads the file into a list of Strings for each line * * @param file a File * @return a List of lines * @throws IOException */ public static List readLines(File file) throws IOException { IteratorClosureAdapter closure = new IteratorClosureAdapter(file); eachLine(file, closure); return closure.asList(); } /** * Reads the content of the File opened with the specified encoding and returns it as a String * * @param file the file whose content we want to read * @param charset the charset used to read the content of the file * @return a String containing the content of the file * @throws IOException */ public static String getText(File file, String charset) throws IOException { BufferedReader reader = newReader(file, charset); return getText(reader); } /** * Reads the content of the File and returns it as a String * * @param file the file whose content we want to read * @return a String containing the content of the file * @throws IOException */ public static String getText(File file) throws IOException { BufferedReader reader = newReader(file); return getText(reader); } /** * Reads the content of this URL and returns it as a String * * @param url URL to read content from * @return the text from that URL * @throws IOException */ public static String getText(URL url) throws IOException { return getText(url, CharsetToolkit.getDefaultSystemCharset().toString()); } /** * Reads the content of this URL and returns it as a String * * @param url URL to read content from * @param charset opens the stream with a specified charset * @return the text from that URL * @throws IOException */ public static String getText(URL url, String charset) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream(), charset)); return getText(reader); } /** * Reads the content of this InputStream and returns it as a String * * @param is an input stream * @return the text from that URL * @throws IOException */ public static String getText(InputStream is) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); return getText(reader); } /** * Reads the content of this InputStream with a specified charset and returns it as a String * * @param is an input stream * @param charset opens the stream with a specified charset * @return the text from that URL * @throws IOException */ public static String getText(InputStream is, String charset) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is, charset)); return getText(reader); } /** * Reads the content of the Reader and returns it as a String * * @param reader a Reader whose content we want to read * @return a String containing the content of the buffered reader * @throws IOException */ public static String getText(Reader reader) throws IOException { BufferedReader bufferedReader = new BufferedReader(reader); return getText(bufferedReader); } /** * Reads the content of the BufferedReader and returns it as a String * * @param reader a BufferedReader whose content we want to read * @return a String containing the content of the buffered reader * @throws IOException */ public static String getText(BufferedReader reader) throws IOException { StringBuffer answer = new StringBuffer(); // reading the content of the file within a char buffer allow to keep the correct line endings char[] charBuffer = new char[4096]; int nbCharRead = 0; while ((nbCharRead = reader.read(charBuffer)) != -1) { // appends buffer answer.append(charBuffer, 0, nbCharRead); } reader.close(); return answer.toString(); } /** * Write the text and append a new line (depending on the platform line-ending) * * @param writer a BufferedWriter * @param line the line to write * @throws IOException */ public static void writeLine(BufferedWriter writer, String line) throws IOException { writer.write(line); writer.newLine(); } /** * Write the text to the File. * * @param file a File * @param text the text to write to the File * @throws IOException */ public static void write(File file, String text) throws IOException { BufferedWriter writer = newWriter(file); writer.write(text); writer.close(); } /** * Write the text to the File with a specified encoding. * * @param file a File * @param text the text to write to the File * @param charset the charset used * @throws IOException */ public static void write(File file, String text, String charset) throws IOException { BufferedWriter writer = newWriter(file, charset); writer.write(text); writer.close(); } /** * Append the text at the end of the File * * @param file a File * @param text the text to append at the end of the File * @throws IOException */ public static void append(File file, String text) throws IOException { BufferedWriter writer = newWriter(file, true); writer.write(text); writer.close(); } /** * Append the text at the end of the File with a specified encoding * * @param file a File * @param text the text to append at the end of the File * @param charset the charset used * @throws IOException */ public static void append(File file, String text, String charset) throws IOException { BufferedWriter writer = newWriter(file, charset, true); writer.write(text); writer.close(); } /** * Reads the reader into a list of Strings for each line * * @param reader a Reader * @return a List of lines * @throws IOException */ public static List readLines(Reader reader) throws IOException { IteratorClosureAdapter closure = new IteratorClosureAdapter(reader); eachLine(reader, closure); return closure.asList(); } /** * Invokes the closure for each file in the given directory * * @param self a File * @param closure a closure */ public static void eachFile(File self, Closure closure) { File[] files = self.listFiles(); for (int i = 0; i < files.length; i++) { closure.call(files[i]); } } /** * Invokes the closure for each file in the given directory and recursively. * It is a depth-first exploration, directories are included in the search. * * @param self a File * @param closure a closure */ public static void eachFileRecurse(File self, Closure closure) { File[] files = self.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { closure.call(files[i]); eachFileRecurse(files[i], closure); } else { closure.call(files[i]); } } } /** * Helper method to create a buffered reader for a file * * @param file a File * @return a BufferedReader * @throws IOException */ public static BufferedReader newReader(File file) throws IOException { CharsetToolkit toolkit = new CharsetToolkit(file); return toolkit.getReader(); } /** * Helper method to create a buffered reader for a file, with a specified charset * * @param file a File * @param charset the charset with which we want to write in the File * @return a BufferedReader * @throws FileNotFoundException if the File was not found * @throws UnsupportedEncodingException if the encoding specified is not supported */ public static BufferedReader newReader(File file, String charset) throws FileNotFoundException, UnsupportedEncodingException { return new BufferedReader(new InputStreamReader(new FileInputStream(file), charset)); } /** * Provides a reader for an arbitrary input stream * * @param self an input stream * @return a reader */ public static BufferedReader newReader(final InputStream self) { return new BufferedReader(new InputStreamReader(self)); } /** * Helper method to create a new BufferedReader for a file and then * passes it into the closure and ensures its closed again afterwords * * @param file * @throws FileNotFoundException */ public static void withReader(File file, Closure closure) throws IOException { withReader(newReader(file), closure); } /** * Helper method to create a buffered output stream for a file * * @param file * @return * @throws FileNotFoundException */ public static BufferedOutputStream newOutputStream(File file) throws IOException { return new BufferedOutputStream(new FileOutputStream(file)); } /** * Helper method to create a new OutputStream for a file and then * passes it into the closure and ensures its closed again afterwords * * @param file a File * @throws FileNotFoundException */ public static void withOutputStream(File file, Closure closure) throws IOException { withStream(newOutputStream(file), closure); } /** * Helper method to create a new InputStream for a file and then * passes it into the closure and ensures its closed again afterwords * * @param file a File * @throws FileNotFoundException */ public static void withInputStream(File file, Closure closure) throws IOException { withStream(newInputStream(file), closure); } /** * Helper method to create a buffered writer for a file * * @param file a File * @return a BufferedWriter * @throws FileNotFoundException */ public static BufferedWriter newWriter(File file) throws IOException { return new BufferedWriter(new FileWriter(file)); } /** * Helper method to create a buffered writer for a file in append mode * * @param file a File * @param append true if in append mode * @return a BufferedWriter * @throws FileNotFoundException */ public static BufferedWriter newWriter(File file, boolean append) throws IOException { return new BufferedWriter(new FileWriter(file, append)); } /** * Helper method to create a buffered writer for a file * * @param file a File * @param charset the name of the encoding used to write in this file * @param append true if in append mode * @return a BufferedWriter * @throws FileNotFoundException */ public static BufferedWriter newWriter(File file, String charset, boolean append) throws IOException { if (append) { return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, append), charset)); } else { // first write the Byte Order Mark for Unicode encodings FileOutputStream stream = new FileOutputStream(file); if ("UTF-16BE".equals(charset)) { writeUtf16Bom(stream, true); } else if ("UTF-16LE".equals(charset)) { writeUtf16Bom(stream, false); } return new BufferedWriter(new OutputStreamWriter(stream, charset)); } } /** * Helper method to create a buffered writer for a file * * @param file a File * @param charset the name of the encoding used to write in this file * @return a BufferedWriter * @throws FileNotFoundException */ public static BufferedWriter newWriter(File file, String charset) throws IOException { return newWriter(file, charset, false); } /** * Write a Byte Order Mark at the begining of the file * * @param stream the FileOuputStream to write the BOM to * @param bigEndian true if UTF 16 Big Endian or false if Low Endian * @throws IOException */ private static void writeUtf16Bom(FileOutputStream stream, boolean bigEndian) throws IOException { if (bigEndian) { stream.write(-2); stream.write(-1); } else { stream.write(-1); stream.write(-2); } } /** * Helper method to create a new BufferedWriter for a file and then * passes it into the closure and ensures it is closed again afterwords * * @param file a File * @param closure a closure * @throws FileNotFoundException */ public static void withWriter(File file, Closure closure) throws IOException { withWriter(newWriter(file), closure); } /** * Helper method to create a new BufferedWriter for a file in a specified encoding * and then passes it into the closure and ensures it is closed again afterwords * * @param file a File * @param charset the charset used * @param closure a closure * @throws FileNotFoundException */ public static void withWriter(File file, String charset, Closure closure) throws IOException { withWriter(newWriter(file, charset), closure); } /** * Helper method to create a new BufferedWriter for a file in a specified encoding * in append mode and then passes it into the closure and ensures it is closed again afterwords * * @param file a File * @param charset the charset used * @param closure a closure * @throws FileNotFoundException */ public static void withWriterAppend(File file, String charset, Closure closure) throws IOException { withWriter(newWriter(file, charset, true), closure); } /** * Helper method to create a new PrintWriter for a file * * @param file a File * @throws FileNotFoundException */ public static PrintWriter newPrintWriter(File file) throws IOException { return new PrintWriter(newWriter(file)); } /** * Helper method to create a new PrintWriter for a file with a specified charset * * @param file a File * @param charset the charset * @return a PrintWriter * @throws FileNotFoundException */ public static PrintWriter newPrintWriter(File file, String charset) throws IOException { return new PrintWriter(newWriter(file, charset)); } /** * Helper method to create a new PrintWriter for a file and then * passes it into the closure and ensures its closed again afterwords * * @param file a File * @throws FileNotFoundException */ public static void withPrintWriter(File file, Closure closure) throws IOException { withWriter(newPrintWriter(file), closure); } /** * Allows a writer to be used, calling the closure with the writer * and then ensuring that the writer is closed down again irrespective * of whether exceptions occur or the * * @param writer the writer which is used and then closed * @param closure the closure that the writer is passed into * @throws IOException */ public static void withWriter(Writer writer, Closure closure) throws IOException { try { closure.call(writer); // lets try close the writer & throw the exception if it fails // but not try to reclose it in the finally block Writer temp = writer; writer = null; temp.close(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { log.warning("Caught exception closing writer: " + e); } } } } /** * Allows a Reader to be used, calling the closure with the writer * and then ensuring that the writer is closed down again irrespective * of whether exceptions occur or the * * @param writer the writer which is used and then closed * @param closure the closure that the writer is passed into * @throws IOException */ public static void withReader(Reader writer, Closure closure) throws IOException { try { closure.call(writer); // lets try close the writer & throw the exception if it fails // but not try to reclose it in the finally block Reader temp = writer; writer = null; temp.close(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { log.warning("Caught exception closing writer: " + e); } } } } /** * Allows a InputStream to be used, calling the closure with the stream * and then ensuring that the stream is closed down again irrespective * of whether exceptions occur or the * * @param stream the stream which is used and then closed * @param closure the closure that the stream is passed into * @throws IOException */ public static void withStream(InputStream stream, Closure closure) throws IOException { try { closure.call(stream); // lets try close the stream & throw the exception if it fails // but not try to reclose it in the finally block InputStream temp = stream; stream = null; temp.close(); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { log.warning("Caught exception closing stream: " + e); } } } } /** * Reads the stream into a list of Strings for each line * * @param stream a stream * @return a List of lines * @throws IOException */ public static List readLines(InputStream stream) throws IOException { return readLines(new BufferedReader(new InputStreamReader(stream))); } /** * Iterates through the given stream line by line * * @param stream a stream * @param closure a closure * @throws IOException */ public static void eachLine(InputStream stream, Closure closure) throws IOException { eachLine(new InputStreamReader(stream), closure); } /** * Iterates through the lines read from the URL's associated input stream * * @param url a URL to open and read * @param closure a closure to apply on each line * @throws IOException */ public static void eachLine(URL url, Closure closure) throws IOException { eachLine(url.openConnection().getInputStream(), closure); } /** * Helper method to create a new BufferedReader for a URL and then * passes it into the closure and ensures its closed again afterwords * * @param url a URL * @throws FileNotFoundException */ public static void withReader(URL url, Closure closure) throws IOException { withReader(url.openConnection().getInputStream(), closure); } /** * Helper method to create a new BufferedReader for a stream and then * passes it into the closure and ensures its closed again afterwords * * @param in a stream * @throws FileNotFoundException */ public static void withReader(InputStream in, Closure closure) throws IOException { withReader(new InputStreamReader(in), closure); } /** * Allows an output stream to be used, calling the closure with the output stream * and then ensuring that the output stream is closed down again irrespective * of whether exceptions occur * * @param stream the stream which is used and then closed * @param closure the closure that the writer is passed into * @throws IOException */ public static void withWriter(OutputStream stream, Closure closure) throws IOException { withWriter(new OutputStreamWriter(stream), closure); } /** * Allows an output stream to be used, calling the closure with the output stream * and then ensuring that the output stream is closed down again irrespective * of whether exceptions occur. * * @param stream the stream which is used and then closed * @param charset the charset used * @param closure the closure that the writer is passed into * @throws IOException */ public static void withWriter(OutputStream stream, String charset, Closure closure) throws IOException { withWriter(new OutputStreamWriter(stream, charset), closure); } /** * Allows a OutputStream to be used, calling the closure with the stream * and then ensuring that the stream is closed down again irrespective * of whether exceptions occur. * * @param stream the stream which is used and then closed * @param closure the closure that the stream is passed into * @throws IOException */ public static void withStream(OutputStream stream, Closure closure) throws IOException { try { closure.call(stream); // lets try close the stream & throw the exception if it fails // but not try to reclose it in the finally block OutputStream temp = stream; stream = null; temp.close(); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { log.warning("Caught exception closing stream: " + e); } } } } /** * Helper method to create a buffered input stream for a file * * @param file a File * @return a BufferedInputStream of the file * @throws FileNotFoundException */ public static BufferedInputStream newInputStream(File file) throws FileNotFoundException { return new BufferedInputStream(new FileInputStream(file)); } /** * Traverse through each byte of the specified File * * @param self a File * @param closure a closure */ public static void eachByte(File self, Closure closure) throws IOException { BufferedInputStream is = newInputStream(self); eachByte(is, closure); } /** * Traverse through each byte of the specified stream * * @param is stream to iterate over * @param closure closure to apply to each byte * @throws IOException */ public static void eachByte(InputStream is, Closure closure) throws IOException { try { while (true) { int b = is.read(); if (b == -1) { break; } else { closure.call(new Byte((byte) b)); } } is.close(); } catch (IOException e) { if (is != null) { try { is.close(); } catch (Exception e2) { // ignore as we're already throwing } throw e; } } } /** * Traverse through each byte of the specified URL * * @param url url to iterate over * @param closure closure to apply to each byte * @throws IOException */ public static void eachByte(URL url, Closure closure) throws IOException { InputStream is = url.openConnection().getInputStream(); eachByte(is, closure); } /** * Transforms the characters from a reader with a Closure and write them to a writer * * @param reader * @param writer * @param closure */ public static void transformChar(Reader reader, Writer writer, Closure closure) { int c; try { char[] chars = new char[1]; while ((c = reader.read()) != -1) { chars[0] = (char) c; writer.write((String) closure.call(new String(chars))); } } catch (IOException e) { } } /** * Transforms the lines from a reader with a Closure and write them to a writer * * @param reader * @param writer * @param closure */ public static void transformLine(Reader reader, Writer writer, Closure closure) throws IOException { BufferedReader br = new BufferedReader(reader); BufferedWriter bw = new BufferedWriter(writer); String line; while ((line = br.readLine()) != null) { Object o = closure.call(line); if (o != null) { bw.write(o.toString()); bw.newLine(); } } } /** * Filter the lines from a reader and write them on the writer, according to a closure * which returns true or false. * * @param reader a reader * @param writer a writer * @param closure the closure which returns booleans * @throws IOException */ public static void filterLine(Reader reader, Writer writer, Closure closure) throws IOException { BufferedReader br = new BufferedReader(reader); BufferedWriter bw = new BufferedWriter(writer); String line; while ((line = br.readLine()) != null) { if (InvokerHelper.asBool(closure.call(line))) { bw.write(line); bw.newLine(); } } bw.flush(); } /** * Filters the lines of a File and creates a Writeable in return to stream the filtered lines * * @param self a File * @param closure a closure which returns a boolean indicating to filter the line or not * @return a Writable closure * @throws IOException if <code>self</code> is not readable */ public static Writable filterLine(final File self, final Closure closure) throws IOException { return filterLine(newReader(self), closure); } /** * Filter the lines from a File and write them on a writer, according to a closure * which returns true or false * * @param self a File * @param writer a writer * @param closure a closure which returns a boolean value and takes a line as input * @throws IOException if <code>self</code> is not readable */ public static void filterLine(final File self, final Writer writer, final Closure closure) throws IOException { filterLine(newReader(self), writer, closure); } /** * Filter the lines of a Reader and create a Writable in return to stream the filtered lines * * @param reader a reader * @param closure a closure returning a boolean indicating to filter or not a line * @return a Writable closure */ public static Writable filterLine(Reader reader, final Closure closure) { final BufferedReader br = new BufferedReader(reader); return new Writable() { public Writer writeTo(Writer out) throws IOException { BufferedWriter bw = new BufferedWriter(out); String line; while ((line = br.readLine()) != null) { if (InvokerHelper.asBool(closure.call(line))) { bw.write(line); bw.newLine(); } } bw.flush(); return out; } public String toString() { StringWriter buffer = new StringWriter(); try { writeTo(buffer); } catch (IOException e) { throw new RuntimeException(e); // TODO: change this exception type } return buffer.toString(); } }; } /** * Filter lines from an input stream using a closure predicate * * @param self an input stream * @param predicate a closure which returns boolean and takes a line * @return a filtered writer */ public static Writable filterLine(final InputStream self, final Closure predicate) { return filterLine(newReader(self), predicate); } /** * Filters lines from an input stream, writing to a writer, using a closure which * returns boolean and takes a line. * * @param self an InputStream * @param writer a writer to write output to * @param predicate a closure which returns a boolean and takes a line as input */ public static void filterLine(final InputStream self, final Writer writer, final Closure predicate) throws IOException { filterLine(newReader(self), writer, predicate); } /** * Reads the content of the file into an array of byte * * @param file a File * @return a List of Bytes */ public static byte[] readBytes(File file) throws IOException { byte[] bytes = new byte[(int) file.length()]; FileInputStream fileInputStream = new FileInputStream(file); DataInputStream dis = new DataInputStream(fileInputStream); dis.readFully(bytes); dis.close(); return bytes; } // Socket and ServerSocket methods /** * Allows an InputStream and an OutputStream from a Socket to be used, * calling the closure with the streams and then ensuring that the streams are closed down again * irrespective of whether exceptions occur. * * @param socket a Socket * @param closure a Closure * @throws IOException */ public static void withStreams(Socket socket, Closure closure) throws IOException { InputStream input = socket.getInputStream(); OutputStream output = socket.getOutputStream(); try { closure.call(new Object[]{input, output}); } finally { try { input.close(); } catch (IOException e) { // noop } try { output.close(); } catch (IOException e) { // noop } } } /** * Overloads the left shift operator to provide an append mechanism * to add things to the output stream of a socket * * @param self a Socket * @param value a value to append * @return a Writer */ public static Writer leftShift(Socket self, Object value) throws IOException { return leftShift(self.getOutputStream(), value); } /** * Overloads the left shift operator to provide an append mechanism * to add bytes to the output stream of a socket * * @param self a Socket * @param value a value to append * @return an OutputStream */ public static OutputStream leftShift(Socket self, byte[] value) throws IOException { return leftShift(self.getOutputStream(), value); } /** * Allow to pass a Closure to the accept methods of ServerSocket * * @param serverSocket a ServerSocket * @param closure a Closure * @return a Socket * @throws IOException */ public static Socket accept(ServerSocket serverSocket, final Closure closure) throws IOException { final Socket socket = serverSocket.accept(); new Thread(new Runnable() { public void run() { try { closure.call(socket); } finally { try { socket.close(); } catch (IOException e) { // noop } } } }).start(); return socket; } /** * @param file a File * @return a File which wraps the input file and which implements Writable */ public static File asWritable(File file) { return new WritableFile(file); } /** * @param file a File * @param encoding the encoding to be used when reading the file's contents * @return File which wraps the input file and which implements Writable */ public static File asWritable(File file, String encoding) { return new WritableFile(file, encoding); } /** * Converts the given String into a List of strings of one character * * @param self a String * @return a List of characters (a 1-character String) */ public static List toList(String self) { int size = self.length(); List answer = new ArrayList(size); for (int i = 0; i < size; i++) { answer.add(self.substring(i, i + 1)); } return answer; } // Process methods /** * An alias method so that a process appears similar to System.out, System.in, System.err; * you can use process.in, process.out, process.err in a similar way * * @return an InputStream */ public static InputStream getIn(Process self) { return self.getInputStream(); } /** * Read the text of the output stream of the Process. * * @param self a Process * @return the text of the output * @throws IOException */ public static String getText(Process self) throws IOException { return getText(new BufferedReader(new InputStreamReader(self.getInputStream()))); } /** * An alias method so that a process appears similar to System.out, System.in, System.err; * you can use process.in, process.out, process.err in a similar way * * @return an InputStream */ public static InputStream getErr(Process self) { return self.getErrorStream(); } /** * An alias method so that a process appears similar to System.out, System.in, System.err; * you can use process.in, process.out, process.err in a similar way * * @return an OutputStream */ public static OutputStream getOut(Process self) { return self.getOutputStream(); } /** * Overloads the left shift operator to provide an append mechanism * to pipe into a Process * * @param self a Process * @param value a value to append * @return a Writer */ public static Writer leftShift(Process self, Object value) throws IOException { return leftShift(self.getOutputStream(), value); } /** * Overloads the left shift operator to provide an append mechanism * to pipe into a Process * * @param self a Process * @param value a value to append * @return an OutputStream */ public static OutputStream leftShift(Process self, byte[] value) throws IOException { return leftShift(self.getOutputStream(), value); } /** * Wait for the process to finish during a certain amount of time, otherwise stops the process. * * @param self a Process * @param numberOfMillis the number of milliseconds to wait before stopping the process */ public static void waitForOrKill(Process self, long numberOfMillis) { ProcessRunner runnable = new ProcessRunner(self); Thread thread = new Thread(runnable); thread.start(); runnable.waitForOrKill(numberOfMillis); } /** * process each regex matched substring of a string object. The object * passed to the closure is a matcher with rich information of the last * successful match * * @param str the target string * @param regex a Regex string * @param closure a closure * @author bing ran */ public static void eachMatch(String str, String regex, Closure closure) { Pattern p = Pattern.compile(regex); Matcher m = p.matcher(str); while (m.find()) { int count = m.groupCount(); ArrayList groups = new ArrayList(); for (int i = 0; i <= count; i++) { groups.add(m.group(i)); } closure.call(groups); } } public static void each(Matcher matcher, Closure closure) { Matcher m = matcher; while (m.find()) { int count = m.groupCount(); ArrayList groups = new ArrayList(); for (int i = 0; i <= count; i++) { groups.add(m.group(i)); } closure.call(groups); } } /** * Iterates over every element of the collection and return the index of the first object * that matches the condition specified in the closure * * @param self the iteration object over which we iterate * @param closure the filter to perform a match on the collection * @return an integer that is the index of the first macthed object. */ public static int findIndexOf(Object self, Closure closure) { int i = 0; for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); i++) { Object value = iter.next(); if (InvokerHelper.asBool(closure.call(value))) { break; } } return i; } /** * A Runnable which waits for a process to complete together with a notification scheme * allowing another thread to wait a maximum number of seconds for the process to complete * before killing it. */ protected static class ProcessRunner implements Runnable { Process process; private boolean finished; public ProcessRunner(Process process) { this.process = process; } public void run() { try { process.waitFor(); } catch (InterruptedException e) { } synchronized (this) { notifyAll(); finished = true; } } public synchronized void waitForOrKill(long millis) { if (!finished) { try { wait(millis); } catch (InterruptedException e) { } if (!finished) { process.destroy(); } } } } }
package com.mapswithme.maps.location; import android.content.ContentResolver; import android.content.Context; import android.hardware.GeomagneticField; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.Location; import android.os.Build; import android.preference.PreferenceManager; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.mapswithme.maps.LocationState; import com.mapswithme.maps.MwmApplication; import com.mapswithme.maps.R; import com.mapswithme.maps.bookmarks.data.MapObject; import com.mapswithme.util.LocationUtils; import com.mapswithme.util.concurrency.UiThread; import com.mapswithme.util.log.Logger; import com.mapswithme.util.log.SimpleLogger; public enum LocationHelper implements SensorEventListener { INSTANCE; protected final Logger mLogger; // These constants should correspond to values defined in platform/location.hpp // Leave 0-value as no any error. public static final int ERROR_NOT_SUPPORTED = 1; public static final int ERROR_DENIED = 2; public static final int ERROR_GPS_OFF = 3; public static final String LOCATION_PREDICTOR_PROVIDER = "LocationPredictorProvider"; private static final long STOP_DELAY = 5000; public interface LocationListener { void onLocationUpdated(final Location l); void onCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy); void onLocationError(int errorCode); } private final Set<LocationListener> mListeners = new LinkedHashSet<>(); private final List<LocationListener> mListenersToRemove = new ArrayList<>(); private boolean mIteratingListener; private Location mLastLocation; private MapObject.MyPosition mMyPosition; private long mLastLocationTime; private final SensorManager mSensorManager; private Sensor mAccelerometer; private Sensor mMagnetometer; private GeomagneticField mMagneticField; private BaseLocationProvider mLocationProvider; private float[] mGravity; private float[] mGeomagnetic; private final float[] mR = new float[9]; private final float[] mI = new float[9]; private final float[] mOrientation = new float[3]; private final Runnable mStopLocationTask = new Runnable() { @Override public void run() { mLocationProvider.stopUpdates(); mMagneticField = null; if (mSensorManager != null) mSensorManager.unregisterListener(LocationHelper.this); } }; LocationHelper() { mLogger = SimpleLogger.get(LocationHelper.class.getName()); initLocationProvider(false); mSensorManager = (SensorManager) MwmApplication.get().getSystemService(Context.SENSOR_SERVICE); if (mSensorManager != null) { mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mMagnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); } } @SuppressWarnings("deprecation") public void initLocationProvider(boolean forceNativeProvider) { boolean isLocationTurnedOn = false; final MwmApplication application = MwmApplication.get(); // If location is turned off(by user in system settings), google client( = fused provider) api doesn't work at all // but external gps receivers still can work. In that case we prefer native provider instead of fused - it works. final ContentResolver resolver = application.getContentResolver(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { final String providers = Settings.Secure.getString(resolver, Settings.Secure.LOCATION_PROVIDERS_ALLOWED); isLocationTurnedOn = !TextUtils.isEmpty(providers); } else { try { final int mode = Settings.Secure.getInt(resolver, Settings.Secure.LOCATION_MODE); isLocationTurnedOn = mode != Settings.Secure.LOCATION_MODE_OFF; } catch (Settings.SettingNotFoundException e) { e.printStackTrace(); } } if (isLocationTurnedOn && !forceNativeProvider && GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(application) == ConnectionResult.SUCCESS && PreferenceManager.getDefaultSharedPreferences(application).getBoolean(application.getString(R.string.pref_play_services), false)) { mLogger.d("Use fused provider."); mLocationProvider = new GoogleFusedLocationProvider(); } else { mLogger.d("Use native provider."); mLocationProvider = new AndroidNativeProvider(); } if (!mListeners.isEmpty()) mLocationProvider.startUpdates(); } public @Nullable MapObject.MyPosition getMyPosition() { if (!LocationState.isTurnedOn()) { mMyPosition = null; return null; } if (mLastLocation == null) return null; if (mMyPosition == null) mMyPosition = new MapObject.MyPosition(mLastLocation.getLatitude(), mLastLocation.getLongitude()); return mMyPosition; } public Location getLastLocation() { return mLastLocation; } public long getLastLocationTime() { return mLastLocationTime; } public void setLastLocation(@NonNull Location loc) { mLastLocation = loc; mMyPosition = null; mLastLocationTime = System.currentTimeMillis(); notifyLocationUpdated(); } private void startIteratingListeners() { mIteratingListener = true; } private void finishIteratingListeners() { mIteratingListener = false; if (!mListenersToRemove.isEmpty()) { mListeners.removeAll(mListenersToRemove); mListenersToRemove.clear(); } } void notifyLocationUpdated() { if (mLastLocation == null) return; startIteratingListeners(); for (LocationListener listener : mListeners) listener.onLocationUpdated(mLastLocation); finishIteratingListeners(); } void notifyLocationError(int errCode) { startIteratingListeners(); for (LocationListener listener : mListeners) listener.onLocationError(errCode); finishIteratingListeners(); } private void notifyCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy) { startIteratingListeners(); for (LocationListener listener : mListeners) listener.onCompassUpdated(time, magneticNorth, trueNorth, accuracy); finishIteratingListeners(); } @android.support.annotation.UiThread public void addLocationListener(LocationListener listener) { UiThread.cancelDelayedTasks(mStopLocationTask); if (mListeners.isEmpty()) mLocationProvider.startUpdates(); mListeners.add(listener); notifyLocationUpdated(); } @android.support.annotation.UiThread public void removeLocationListener(LocationListener listener) { boolean empty = false; if (mIteratingListener) { if (mListeners.contains(listener)) { mListenersToRemove.add(listener); empty = (mListeners.size() == 1); } } else { mListeners.remove(listener); empty = mListeners.isEmpty(); } if (empty) // Make a delay with disconnection from location providers, so that orientation changes and short app sleeps // doesn't take long time to connect again. UiThread.runLater(mStopLocationTask, STOP_DELAY); } void registerSensorListeners() { if (mSensorManager != null) { final int COMPASS_REFRESH_MKS = SensorManager.SENSOR_DELAY_UI; if (mAccelerometer != null) mSensorManager.registerListener(this, mAccelerometer, COMPASS_REFRESH_MKS); if (mMagnetometer != null) mSensorManager.registerListener(this, mMagnetometer, COMPASS_REFRESH_MKS); } } @Override public void onSensorChanged(SensorEvent event) { boolean hasOrientation = false; switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: mGravity = nativeUpdateCompassSensor(0, event.values); break; case Sensor.TYPE_MAGNETIC_FIELD: mGeomagnetic = nativeUpdateCompassSensor(1, event.values); break; } if (mGravity != null && mGeomagnetic != null) { if (SensorManager.getRotationMatrix(mR, mI, mGravity, mGeomagnetic)) { hasOrientation = true; SensorManager.getOrientation(mR, mOrientation); } } if (hasOrientation) { final double magneticHeading = LocationUtils.correctAngle(mOrientation[0], 0.0); if (mMagneticField == null) notifyCompassUpdated(event.timestamp, magneticHeading, -1.0, -1.0); // -1.0 - as default parameters else { // positive 'offset' means the magnetic field is rotated east that match from true north final double offset = Math.toRadians(mMagneticField.getDeclination()); final double trueHeading = LocationUtils.correctAngle(magneticHeading, offset); notifyCompassUpdated(event.timestamp, magneticHeading, trueHeading, offset); } } } private native float[] nativeUpdateCompassSensor(int ind, float[] arr); @Override public void onAccuracyChanged(Sensor sensor, int accuracy) {} public void initMagneticField(Location newLocation) { if (mSensorManager != null) { // Recreate magneticField if location has changed significantly if (mMagneticField == null || mLastLocation == null || newLocation.distanceTo(mLastLocation) > BaseLocationProvider.DISTANCE_TO_RECREATE_MAGNETIC_FIELD_M) mMagneticField = new GeomagneticField((float) newLocation.getLatitude(), (float) newLocation.getLongitude(), (float) newLocation.getAltitude(), newLocation.getTime()); } } }
package com.mapswithme.maps.api; import android.content.Context; import android.content.Intent; // TODO add javadoc for public interface public class MWMResponse { private MWMPoint mPoint; public MWMPoint getPoint() { return mPoint; } public boolean hasPoint() { return mPoint != null; } @Override public String toString() { return "MWMResponse [mSelectedPoint=" + mPoint + "]"; } public static MWMResponse extractFromIntent(Context context, Intent intent) { final MWMResponse response = new MWMResponse(); // parse status // parse point final double lat = intent.getDoubleExtra(Const.EXTRA_MWM_RESPONSE_POINT_LAT, 0); final double lon = intent.getDoubleExtra(Const.EXTRA_MWM_RESPONSE_POINT_LON, 0); final String name = intent.getStringExtra(Const.EXTRA_MWM_RESPONSE_POINT_NAME); final String id = intent.getStringExtra(Const.EXTRA_MWM_RESPONSE_POINT_ID); response.mPoint = new MWMPoint(lat, lon, name, id); return response; } private MWMResponse() {} }
package org.apidesign.html.leaflet.api; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.function.Function; import net.java.html.js.JavaScriptBody; import net.java.html.js.JavaScriptResource; /** * Abstract class which implements basic Layer functionality. Derive from this * class to implement custom layers. Do not forget to register the new layer * type using registerLayerType. */ @JavaScriptResource("/org/apidesign/html/leaflet/api/leaflet-src.js") public abstract class ILayer { final Object jsObj; private final static HashMap<String, Function<Object, ILayer>> registeredLayerTypes = new HashMap<>(); /** * Registers a layer to allow correct type mapping * * @param layerTypeName The global accessible JS layer type name * @param creator A function returning a new Layer instance from a JS object */ protected static void registerLayerType(String layerTypeName, Function<Object, ILayer> creator) { registeredLayerTypes.putIfAbsent(layerTypeName, creator); } protected static void unregisterLayerType(String layerTypeName) { if (registeredLayerTypes.containsKey(layerTypeName)) registeredLayerTypes.remove(layerTypeName); } @JavaScriptBody(args = {"jsObj", "layerTypeName"}, body = "return jsObj instanceof eval(layerTypeName);") private static native boolean checkLayerType(Object jsObj, String layerTypeName); @JavaScriptBody(args = {"classAName", "classBName"}, body = "return eval(classAName).prototype instanceof eval(classBName);") private static native boolean isSubclassOf(String classAName, String classBName); protected static ILayer createLayer(Object jsObj) { List<String> compatibleTypes = new ArrayList<>(); for (String layerName : registeredLayerTypes.keySet()) { if (checkLayerType(jsObj, layerName)) { compatibleTypes.add(layerName); } } if (compatibleTypes.isEmpty()) { return new UnknownLayer(jsObj); } compatibleTypes.sort((a, b) -> isSubclassOf(b, a) ? 1 : -1); return registeredLayerTypes.get(compatibleTypes.get(0)).apply(jsObj); } ILayer(Object jsObj) { this.jsObj = jsObj; } Object getJSObj() { return jsObj; } }
package org.openmrs.api; import java.util.Date; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.openmrs.Concept; import org.openmrs.Patient; import org.openmrs.activelist.ActiveListItem; import org.openmrs.activelist.ActiveListType; import org.openmrs.activelist.Allergy; import org.openmrs.activelist.AllergySeverity; import org.openmrs.activelist.AllergyType; import org.openmrs.activelist.Problem; import org.openmrs.activelist.ProblemModifier; import org.openmrs.api.context.Context; import org.openmrs.test.BaseContextSensitiveTest; public class ActiveListServiceTest extends BaseContextSensitiveTest { private static final String ACTIVE_LIST_INITIAL_XML = "org/openmrs/api/include/ActiveListTest.xml"; protected static PatientService patientService = null; protected static ActiveListService activeListService = null; @Before public void runBeforeAllTests() throws Exception { if (patientService == null) { patientService = Context.getPatientService(); activeListService = Context.getActiveListService(); } executeDataSet(ACTIVE_LIST_INITIAL_XML); } // public List<ActiveListItem> getActiveListItems(Person p, ActiveListType type) throws Exception; @Test public void should_getActiveListItems() throws Exception { Patient p = patientService.getPatient(2); List<ActiveListItem> items = activeListService.getActiveListItems(p, new ActiveListType(2)); assertEquals(1, items.size()); System.out.println("instance=" + items.get(0).getClass().toString()); } // public <T extends ActiveListItem> List<T> getActiveListItems(Class<T> clazz, Person p, ActiveListType type) throws Exception; @Test public void should_getActiveListItems_withProblem() throws Exception { Patient p = patientService.getPatient(2); List<Problem> items = activeListService.getActiveListItems(Problem.class, p, new ActiveListType(2)); assertEquals(1, items.size()); } @Test public void should_getActiveListItems_withAllergy() throws Exception { Patient p = patientService.getPatient(2); List<Allergy> items = activeListService.getActiveListItems(Allergy.class, p, new ActiveListType(1)); assertEquals(1, items.size()); } // public <T extends ActiveListItem> T getActiveListItem(Class<T> clazz, Integer activeListItemId) throws Exception; @Test public void should_getActiveListItem_Allergy() throws Exception { Allergy item = activeListService.getActiveListItem(Allergy.class, 1); Assert.assertNotNull(item); Assert.assertTrue(item instanceof Allergy); } // public ActiveListItem getActiveListItemByUuid(String uuid) throws Exception; // public ActiveListItem saveActiveListItem(ActiveListItem item) throws Exception; @Test public void should_saveActiveListItem_Problem() throws Exception { Patient p = patientService.getPatient(2); List<Problem> items = activeListService.getActiveListItems(Problem.class, p, new ActiveListType(2)); assertEquals(1, items.size()); Concept concept = Context.getConceptService().getConcept(88);//Aspirin Problem problem = new Problem(p, concept, new Date(), ProblemModifier.HISTORY_OF, "", null); activeListService.saveActiveListItem(problem); items = activeListService.getActiveListItems(Problem.class, p, new ActiveListType(2)); assertEquals(2, items.size()); } @Test public void should_saveActiveListItem_Allergy() throws Exception { Patient p = patientService.getPatient(2); List<Allergy> items = activeListService.getActiveListItems(Allergy.class, p, new ActiveListType(1)); assertEquals(1, items.size()); Concept concept = Context.getConceptService().getConcept(88);//Aspirin Allergy allergy = new Allergy(p, concept, new Date(), AllergyType.ANIMAL, null, AllergySeverity.INTOLERANCE); activeListService.saveActiveListItem(allergy); items = activeListService.getActiveListItems(Allergy.class, p, new ActiveListType(1)); assertEquals(2, items.size()); } // public ActiveListItem removeActiveListItem(ActiveListItem item, Date endDate) throws Exception; @Test public void should_removeActiveListItem_Allergy() throws Exception { Allergy item = activeListService.getActiveListItem(Allergy.class, 1); activeListService.removeActiveListItem(item, null); item = activeListService.getActiveListItem(Allergy.class, 1); Assert.assertNotNull(item); Assert.assertNotNull(item.getEndDate()); } // public ActiveListItem voidActiveListItem(ActiveListItem item, String reason) throws Exception; @Test public void should_voidActiveListItem_Allergy() throws Exception { Allergy item = activeListService.getActiveListItem(Allergy.class, 1); item = (Allergy) activeListService.voidActiveListItem(item, "Because"); Assert.assertTrue(item.isVoided()); Patient p = patientService.getPatient(2); List<Allergy> items = activeListService.getActiveListItems(Allergy.class, p, new ActiveListType(1)); assertEquals(0, items.size()); } /** * @see ActiveListService#purgeActiveListItem(ActiveListItem) * @verifies purge active list item from database */ @Test public void purgeActiveListItem_shouldPurgeActiveListItemFromDatabase() throws Exception { ActiveListItem item = activeListService.getActiveListItem(Allergy.class, 1); activeListService.purgeActiveListItem(item); item = activeListService.getActiveListItem(ActiveListItem.class, 1); Assert.assertNull(item); } private void assertEquals(int i1, int i2) { Assert.assertEquals(Integer.valueOf(i1), Integer.valueOf(i2)); } }
package org.exist.xquery.functions.transform; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.dom.persistent.BinaryDocument; import org.exist.dom.persistent.DocumentImpl; import org.exist.security.Permission; import org.exist.security.PermissionDeniedException; import org.exist.storage.DBBroker; import org.exist.xmldb.XmldbURI; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import java.io.IOException; import java.lang.reflect.Array; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; /** * Implementation of URIResolver which * will resolve paths from the eXist database * * @Deprecated use {@link org.exist.xslt.EXistURIResolver} */ public class EXistURIResolver implements URIResolver { private static final Logger LOG = LogManager.getLogger(EXistURIResolver.class); final DBBroker broker; final String basePath; public EXistURIResolver(final DBBroker broker, final String docPath) { this.broker = broker; this.basePath = docPath; LOG.debug("EXistURIResolver base path set to " + basePath); } /** * Simplify a path removing any "." and ".." path elements. * Assumes an absolute path is given. */ private String normalizePath(final String path) { if (!path.startsWith("/")) { throw new IllegalArgumentException("normalizePath may only be applied to an absolute path; " + "argument was: " + path + "; base: " + basePath); } final String[] pathComponents = path.substring(1).split("/"); final int numPathComponents = Array.getLength(pathComponents); final String[] simplifiedComponents = new String[numPathComponents]; int numSimplifiedComponents = 0; for(final String s : pathComponents) { if (s.length() == 0) {continue;} // Remove empty elements ("//") if (".".equals(s)) {continue;} // Remove identity elements ("/./") if ("..".equals(s)) { // Remove parent elements ("/../") unless at the root if (numSimplifiedComponents > 0) {numSimplifiedComponents continue; } simplifiedComponents[numSimplifiedComponents++] = s; } if (numSimplifiedComponents == 0) { return "/"; } final StringBuilder b = new StringBuilder(path.length()); for(int x = 0; x < numSimplifiedComponents; x++) { b.append("/").append(simplifiedComponents[x]); } if (path.endsWith("/")) { b.append("/"); } return b.toString(); } @Override public Source resolve(final String href, String base) throws TransformerException { String path; if (href.isEmpty()) { path = base; } else { URI hrefURI = null; try { hrefURI = new URI(href); } catch (final URISyntaxException e) { } if (hrefURI != null && hrefURI.isAbsolute()) { path = href; } else { if (href.startsWith("/")) { path = href; } else if (href.startsWith(XmldbURI.EMBEDDED_SERVER_URI_PREFIX)) { path = href.substring(XmldbURI.EMBEDDED_SERVER_URI_PREFIX.length()); } else if (base == null || base.length() == 0) { path = basePath + "/" + href; } else { // Maybe base never contains this prefix? Check to be sure. if (base.startsWith(XmldbURI.EMBEDDED_SERVER_URI_PREFIX)) { base = base.substring(XmldbURI.EMBEDDED_SERVER_URI_PREFIX.length()); } path = base.substring(0, base.lastIndexOf("/") + 1) + href; } } } LOG.debug("Resolving path " + href + " with base " + base + " to " + path);// + " (URI = " + uri.toASCIIString() + ")"); if (path.startsWith("/")) { path = normalizePath(path); return databaseSource(path); } else { return urlSource(path); } } private Source urlSource(final String path) throws TransformerException { try { final URL url = new URL(path); return new StreamSource(url.openStream()); } catch (final IOException e) { throw new TransformerException(e.getMessage(), e); } } private Source databaseSource(final String path) throws TransformerException { final XmldbURI uri = XmldbURI.create(path); final DocumentImpl doc; try { doc = broker.getResource(uri, Permission.READ); if (doc == null) { LOG.error("Document " + path + " not found"); throw new TransformerException("Resource " + path + " not found in database."); } final Source source; if (doc instanceof BinaryDocument) { final Path p = broker.getBinaryFile((BinaryDocument) doc); source = new StreamSource(p.toFile()); source.setSystemId(p.toUri().toString()); return source; } else { source = new DOMSource(doc); source.setSystemId(uri.toASCIIString()); return source; } } catch (final PermissionDeniedException | IOException e) { throw new TransformerException(e.getMessage(), e); } } }
package org.vitrivr.cineast.core.importer; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Optional; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.vitrivr.cineast.core.data.Pair; import org.vitrivr.cineast.core.data.entities.SimpleFulltextFeatureDescriptor; import org.vitrivr.cineast.core.data.providers.primitive.PrimitiveTypeProvider; import sun.util.locale.provider.LocaleServiceProviderPool.LocalizedObjectGetter; public class CaptionTextImporter implements Importer<Pair<String, String>> { private final String objectID; private final Iterator<Entry<String, JsonNode>> elements; private static final Logger LOGGER = LogManager.getLogger(); private Iterator<JsonNode> currentDescriptions; private String currentSegmentID; public CaptionTextImporter(Path input) throws IOException { objectID = input.getFileName().toString().replace(".json", ""); ObjectMapper mapper = new ObjectMapper(); JsonParser parser = mapper.getFactory().createParser(input.toFile()); if (parser.nextToken() == JsonToken.START_OBJECT) { ObjectNode node = mapper.readTree(parser); elements = node.fields(); if (elements == null) { throw new IOException("Empty file"); } } else { throw new IOException("Empty file"); } } private synchronized Optional<Pair<String, String>> nextPair() { while (currentDescriptions == null || !currentDescriptions.hasNext()) { Entry<String, JsonNode> next = elements.next(); currentSegmentID = next.getKey(); currentDescriptions = next.getValue().iterator(); return Optional.of(new Pair<>(currentSegmentID, currentDescriptions.next().asText())); } return Optional.of(new Pair<>(currentSegmentID, currentDescriptions.next().asText())); } /** * @return Pair mapping a segmentID to a List of Descriptions */ @Override public Pair<String, String> readNext() { try { Optional<Pair<String, String>> node = nextPair(); if (!node.isPresent()) { return null; } return node.get(); } catch (NoSuchElementException e) { return null; } } @Override public Map<String, PrimitiveTypeProvider> convert(Pair<String, String> data) { final HashMap<String, PrimitiveTypeProvider> map = new HashMap<>(2); String id = "v_" + objectID + "_" + data.first; map.put(SimpleFulltextFeatureDescriptor.FIELDNAMES[0], PrimitiveTypeProvider.fromObject(id)); map.put(SimpleFulltextFeatureDescriptor.FIELDNAMES[1], PrimitiveTypeProvider.fromObject(data.second)); LOGGER.debug("Converting to {}:{}", id, data.second); return map; } }
package agersant.polaris.api.remote; import android.content.Context; import android.content.SharedPreferences; import android.media.MediaDataSource; import android.preference.PreferenceManager; import com.android.volley.Response; import org.json.JSONArray; import org.json.JSONObject; import java.io.IOException; import java.net.URLConnection; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import agersant.polaris.CollectionItem; import agersant.polaris.R; import agersant.polaris.api.IPolarisAPI; public class ServerAPI implements IPolarisAPI { private static ServerAPI instance; private RequestQueue requestQueue; private SharedPreferences preferences; private Auth auth; private String serverAddressKey; private String usernameKey; private String passwordKey; private ServerAPI(Context context) { this.requestQueue = RequestQueue.getInstance(context); this.preferences = PreferenceManager.getDefaultSharedPreferences(context); this.auth = new Auth(this); serverAddressKey = context.getString(R.string.pref_key_server_url); usernameKey = context.getString(R.string.pref_key_username); passwordKey = context.getString(R.string.pref_key_password); } public static void init(Context context) { instance = new ServerAPI(context); } public static ServerAPI getInstance() { return instance; } String getURL() { String address = this.preferences.getString(serverAddressKey, ""); address = address.replaceAll("/$", ""); return address + "/api"; } String getUsername() { return this.preferences.getString(usernameKey, ""); } String getPassword() { return this.preferences.getString(passwordKey, ""); } RequestQueue getRequestQueue() { return this.requestQueue; } private String getMediaURL(String path) { String serverAddress = this.getURL(); return serverAddress + "/serve/" + path; } @Override public MediaDataSource getAudio(CollectionItem item) throws IOException { DownloadQueue downloadQueue = DownloadQueue.getInstance(); return downloadQueue.getAudio(item); } // Can block! public URLConnection serve(String path) throws InterruptedException, ExecutionException, TimeoutException, IOException { String url = getMediaURL(path); return auth.connect(url); } public void browse(String path, final Response.Listener<ArrayList<CollectionItem>> success, Response.ErrorListener failure) { String serverAddress = this.getURL(); String requestURL = serverAddress + "/browse/" + path; Response.Listener<JSONArray> successWrapper = new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { ArrayList<CollectionItem> items = new ArrayList<>(response.length()); for (int i = 0; i < response.length(); i++) { try { JSONObject item = response.getJSONObject(i); CollectionItem browseItem = CollectionItem.parse(item); items.add(browseItem); } catch (Exception e) { } } success.onResponse(items); } }; this.auth.doJsonArrayRequest(requestURL, successWrapper, failure); } public void getRandomAlbums(final Response.Listener<ArrayList<CollectionItem>> success, Response.ErrorListener failure) { String serverAddress = this.getURL(); String requestURL = serverAddress + "/random/"; Response.Listener<JSONArray> successWrapper = new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { ArrayList<CollectionItem> items = new ArrayList<>(response.length()); for (int i = 0; i < response.length(); i++) { try { JSONObject item = response.getJSONObject(i); CollectionItem browseItem = CollectionItem.parseDirectory(item); items.add(browseItem); } catch (Exception e) { } } success.onResponse(items); } }; this.auth.doJsonArrayRequest(requestURL, successWrapper, failure); } public void flatten(String path, final Response.Listener<ArrayList<CollectionItem>> success, Response.ErrorListener failure) { String serverAddress = this.getURL(); String requestURL = serverAddress + "/flatten/" + path; Response.Listener<JSONArray> successWrapper = new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { ArrayList<CollectionItem> items = new ArrayList<>(response.length()); for (int i = 0; i < response.length(); i++) { try { JSONObject item = response.getJSONObject(i); CollectionItem browseItem = CollectionItem.parseSong(item); items.add(browseItem); } catch (Exception e) { } } success.onResponse(items); } }; this.auth.doJsonArrayRequest(requestURL, successWrapper, failure); } }
package com.almoturg.sprog.data; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Environment; import java.io.File; import java.util.Calendar; import java.util.TimeZone; public class UpdateHelpers { // These are the times when an update should be available on the server private static final int FIRST_UPDATE_HOUR = 2; private static final int SECOND_UPDATE_HOUR = 14; private static final long MIN_HOURS_BETWEEN_UPDATES = 11; // some margin if it runs faster private static final long MAX_DAYS_BETWEEN_LOADING_POEMS = 3; private static final long MAX_DAYS_BETWEEN_FULL_UPDATES = 30; // minimum length of poems.json file in bytes such that it is assumed to be complete // and therefore the cancel button is shown when updating private static final int MIN_FILE_LENGTH = 1000 * 1000; public static boolean isUpdateTime(Calendar now, long last_update_tstamp, long last_fcm_tstamp) { // Always load JSON when more than MAX_DAYS_BETWEEN_LOADING_POEMS days have passed // This is mainly to get updated scores/gold counts and to remove deleted poems. if (now.getTimeInMillis() - last_update_tstamp > MAX_DAYS_BETWEEN_LOADING_POEMS * 24 * 60 * 60 * 1000) { return true; } // last_fcm_tstamp is the time when the last FCM message was sent // if it showed that updates were available this function would not have been called if (now.getTimeInMillis() - last_fcm_tstamp < MIN_HOURS_BETWEEN_UPDATES * 60 * 60 * 1000) { return false; } Calendar last_update_cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); last_update_cal.setTimeInMillis(last_update_tstamp); long diff_in_ms = now.getTimeInMillis() - last_update_tstamp; long ms_today = now.get(Calendar.HOUR_OF_DAY) * 60 * 60 * 1000 + now.get(Calendar.MINUTE) * 60 * 1000 + now.get(Calendar.SECOND) * 1000 + now.get(Calendar.MILLISECOND); return (now.get(Calendar.HOUR_OF_DAY) >= FIRST_UPDATE_HOUR && diff_in_ms > ms_today - FIRST_UPDATE_HOUR * 60 * 60 * 1000) || (now.get(Calendar.HOUR_OF_DAY) >= SECOND_UPDATE_HOUR && diff_in_ms > ms_today - SECOND_UPDATE_HOUR * 60 * 60 * 1000); } public static boolean poemsFullFileExists(Context context) { File file = new File(context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS), PoemsLoader.getFilename( PoemsLoader.UpdateType.FULL, PoemsLoader.FileType.CURRENT)); File old_file = new File(context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS), PoemsLoader.getFilename( PoemsLoader.UpdateType.FULL, PoemsLoader.FileType.PREV)); return (file.exists() && file.length() > MIN_FILE_LENGTH) || (old_file.exists() && old_file.length() > MIN_FILE_LENGTH); } public static boolean poems60DaysFileExists(Context context) { File file = new File(context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS), PoemsLoader.getFilename( PoemsLoader.UpdateType.PARTIAL, PoemsLoader.FileType.CURRENT)); File old_file = new File(context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS), PoemsLoader.getFilename( PoemsLoader.UpdateType.PARTIAL, PoemsLoader.FileType.PREV)); return (file.exists() && file.length() > 1) || (old_file.exists() && old_file.length() > 1); } public static boolean isConnected(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnected(); } public static PoemsLoader.UpdateType getUpdateType(Calendar now, long last_full_update_tstamp) { if (now.getTimeInMillis() - last_full_update_tstamp > MAX_DAYS_BETWEEN_FULL_UPDATES * 24 * 60 * 60 * 1000) { return PoemsLoader.UpdateType.FULL; } return PoemsLoader.UpdateType.PARTIAL; } }
package com.cojisoft.tfm_demo; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Random; public class DetalleActivity extends ActionBarActivity implements View.OnClickListener { ImageView imagen; TextView titulo; TextView lugar; TextView descripcion; ImageView icTitulo; ImageView icLugar; ImageView icDescripcion; View separador1; View separador2; ProgressBar spinner; TextView tituloSpinner; String figura; Button boton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detalle); ActionBar actionBar = (ActionBar) getSupportActionBar(); Bundle extras = getIntent().getExtras(); figura = extras.getString("figura"); boton = (Button) findViewById(R.id.detalle_boton); boton.setOnClickListener(this); spinner = (ProgressBar) findViewById(R.id.detalle_progress); spinner.setVisibility(View.GONE); tituloSpinner = (TextView) findViewById(R.id.detalle_titulo_progress); tituloSpinner.setVisibility(View.GONE); icTitulo = (ImageView) findViewById(R.id.detalle_titulo_ic); icLugar = (ImageView) findViewById(R.id.detalle_lugar_ic); icDescripcion = (ImageView) findViewById(R.id.detalle_descripcion_ic); separador1 = (View) findViewById(R.id.detalle_separator_1); separador2 = (View) findViewById(R.id.detalle_separator_2); imagen = (ImageView) findViewById(R.id.detalle_imagen); titulo = (TextView) findViewById(R.id.detalle_titulo); lugar = (TextView) findViewById(R.id.detalle_lugar); descripcion = (TextView) findViewById(R.id.detalle_descripcion); if (figura.equals("citara")) { actionBar.setTitle(getString(R.string.citara_titulo)); imagen.setImageResource(R.drawable.portada_citara); titulo.setText(getString(R.string.citara_titulo)); lugar.setText(getString(R.string.citara_lugar)); descripcion.setText(getString(R.string.citara_descripcion)); } else if (figura.equals("estanislao")) { actionBar.setTitle(getString(R.string.estanislao_titulo)); imagen.setImageResource(R.drawable.portada_estanislao); titulo.setText(getString(R.string.estanislao_titulo)); lugar.setText(getString(R.string.estanislao_lugar)); descripcion.setText(getString(R.string.estanislao_descripcion)); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onClick(View view) { Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); startActivityForResult(intent, 0); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { imagen.setVisibility(View.GONE); titulo.setVisibility(View.GONE); lugar.setVisibility(View.GONE); descripcion.setVisibility(View.GONE); boton.setVisibility(View.GONE); icTitulo.setVisibility(View.GONE); icLugar.setVisibility(View.GONE); icDescripcion.setVisibility(View.GONE); separador1.setVisibility(View.GONE); separador2.setVisibility(View.GONE); spinner.setVisibility(View.VISIBLE); tituloSpinner.setVisibility(View.VISIBLE); new RetrieveFeedTask().execute(); } class RetrieveFeedTask extends AsyncTask<String, String, Integer> { protected Integer doInBackground(String... urls) { return UploadFile(); } } public int UploadFile(){ HttpURLConnection connection = null; DataOutputStream outputStream = null; DataInputStream inputStream = null; Random randomGenerator = new Random(); int randomInt = randomGenerator.nextInt(2); String nombreFichero = ""; if (figura.equals("citara")) nombreFichero = randomInt == 0 ? "cita1_negra.bmp" : "cita2_negra.bmp"; else if (figura.equals("estanislao")) nombreFichero = randomInt == 0 ? "esta1_negra.bmp" : "esta5_negra.bmp"; String pathBase = Environment.getExternalStorageDirectory().toString()+"/DCIM/" + nombreFichero; Log.v("CACA", pathBase); String pathModelo = Environment.getExternalStorageDirectory().toString()+"/DCIM/" + "respuesta.png"; String urlServer = "http://192.168.1.108:8080/TFM_Servidor/Lanzador"; String lineEnd = "\r\n"; String twoHyphens = " String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1*1024*1024; try { FileInputStream fileInputStream = new FileInputStream(new File(pathBase) ); URL url = new URL(urlServer); connection = (HttpURLConnection) url.openConnection(); // Allow Inputs &amp; Outputs. connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); // Set HTTP method to POST. connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary); outputStream = new DataOutputStream( connection.getOutputStream() ); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + figura +"\"" + lineEnd); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // Leer fichero bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { outputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } outputStream.writeBytes(lineEnd); outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); int serverResponseCode = connection.getResponseCode(); String serverResponseMessage = connection.getResponseMessage(); InputStream fileContent = connection.getInputStream(); OutputStream os = new FileOutputStream(pathModelo); byte[] b = new byte[2048]; int length; while ((length = fileContent.read(b)) != -1) os.write(b, 0, length); fileContent.close(); os.close(); fileInputStream.close(); outputStream.flush(); outputStream.close(); } catch (Exception ex) { Log.e("Err", ex.toString()); return -1; } // Se lanza la actividad detalle Intent intent = new Intent(this, ResultadoActivity.class); intent.putExtra("pathBase", pathBase); intent.putExtra("pathModelo", pathModelo); startActivity(intent); return 0; } }
package com.vangent.hieos.empi.match; import com.vangent.hieos.empi.config.EMPIConfig; import com.vangent.hieos.empi.config.FieldConfig; import com.vangent.hieos.empi.config.TransformFunctionConfig; import com.vangent.hieos.empi.transform.TransformFunction; import com.vangent.hieos.hl7v3util.model.subject.Subject; import com.vangent.hieos.empi.exception.EMPIException; import java.util.List; import org.apache.commons.beanutils.PropertyUtils; import org.apache.log4j.Logger; /** * * @author Bernie Thuman */ public class RecordBuilder { private final static Logger logger = Logger.getLogger(RecordBuilder.class); /** * * @param subject * @return * @throws EMPIException */ public Record build(Subject subject) throws EMPIException { EMPIConfig empiConfig = EMPIConfig.getInstance(); Record record = new Record(); record.setId(subject.getInternalId()); // Go through each field (according to configuration). List<FieldConfig> fieldConfigs = empiConfig.getFieldConfigList(); for (FieldConfig fieldConfig : fieldConfigs) { String sourceObjectPath = fieldConfig.getSourceObjectPath(); String fieldName = fieldConfig.getName(); // FIXME: Deal with different types (partially implemented)? if (logger.isTraceEnabled()) { logger.trace("field = " + fieldName); logger.trace(" ... sourceObjectPath = " + sourceObjectPath); } try { Object value; // Access the field value. if (sourceObjectPath.equalsIgnoreCase("subject")) { value = subject; } else { value = PropertyUtils.getProperty(subject, sourceObjectPath); } if (value != null) { if (logger.isTraceEnabled()) { logger.trace(" ... value (before transforms) = " + value.toString()); } // Now run any transforms (in order). List<TransformFunctionConfig> transformFunctionConfigs = fieldConfig.getTransformFunctionConfigs(); for (TransformFunctionConfig transformFunctionConfig : transformFunctionConfigs) { if (logger.isTraceEnabled()) { logger.trace(" ... transformFunction = " + transformFunctionConfig.getName()); } TransformFunction transformFunction = transformFunctionConfig.getTransformFunction(); value = transformFunction.transform(value); } if (value != null) { if (logger.isTraceEnabled()) { logger.trace(" ... value (after transforms) = " + value.toString()); } Field field = new Field(fieldName, value.toString()); record.addField(field); } } } catch (Exception ex) { logger.info( "Unable to access '" + sourceObjectPath + "' field: " + ex.getMessage()); } } // Now, get rid of any superseded fields. this.removeSupersededFields(record, fieldConfigs); return record; } /** * * @param record * @param fieldConfigs */ private void removeSupersededFields(Record record, List<FieldConfig> fieldConfigs) { // This should handle the case where a field has been removed along the way. for (FieldConfig fieldConfig : fieldConfigs) { String fieldName = fieldConfig.getName(); Field field = record.getField(fieldName); if (field != null) { String supersedesFieldName = fieldConfig.getSupersedesField(); if (supersedesFieldName != null) { Field supersededField = record.getField(supersedesFieldName); if (logger.isTraceEnabled()) { logger.trace("+++++++++ REMOVING SUPERSEDED FIELD = " + supersedesFieldName); logger.trace(" .... keeping field = " + fieldName); } record.removeField(supersededField); } } } } }
package com.rehivetech.beeeon.network; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Locale; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManagerFactory; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.telephony.TelephonyManager; import com.rehivetech.beeeon.adapter.Adapter; import com.rehivetech.beeeon.adapter.device.Device; import com.rehivetech.beeeon.adapter.device.Device.SaveDevice; import com.rehivetech.beeeon.adapter.device.DeviceLog; import com.rehivetech.beeeon.adapter.device.Facility; import com.rehivetech.beeeon.adapter.location.Location; import com.rehivetech.beeeon.controller.Controller; import com.rehivetech.beeeon.exception.AppException; import com.rehivetech.beeeon.exception.NetworkError; import com.rehivetech.beeeon.household.User; import com.rehivetech.beeeon.network.GoogleAuthHelper.GoogleUserInfo; import com.rehivetech.beeeon.network.xml.CustomViewPair; import com.rehivetech.beeeon.network.xml.FalseAnswer; import com.rehivetech.beeeon.network.xml.ParsedMessage; import com.rehivetech.beeeon.network.xml.XmlCreator; import com.rehivetech.beeeon.network.xml.XmlParsers; import com.rehivetech.beeeon.network.xml.XmlParsers.State; import com.rehivetech.beeeon.network.xml.action.ComplexAction; import com.rehivetech.beeeon.network.xml.condition.Condition; import com.rehivetech.beeeon.pair.LogDataPair; import com.rehivetech.beeeon.util.Log; /** * Network service that handles communication with server. * * @author ThinkDeep * @author Robyer */ public class Network implements INetwork { private static final String TAG = Network.class.getSimpleName(); /** * Name of CA certificate located in assets */ private static final String ASSEST_CA_CERT = "cacert.crt"; /** * Alias (tag) for CA certificate */ private static final String ALIAS_CA_CERT = "ca"; /** * Address and port of debug server */ private static final String SERVER_ADDR_DEBUG = "ant-2.fit.vutbr.cz"; private static final int SERVER_PORT_DEBUG = 4566; /** * Address and port of production server */ private static final String SERVER_ADDR_PRODUCTION = "iotpro.fit.vutbr.cz"; private static final int SERVER_PORT_PRODUCTION = 4565; /** * CN value to be verified in server certificate */ private static final String SERVER_CN_CERTIFICATE = "ant-2.fit.vutbr.cz"; private final Context mContext; private String mUserID = ""; private final boolean mUseDebugServer; private static final int SSLTIMEOUT = 35000; private SSLSocket permaSocket = null; private PrintWriter permaWriter = null; private BufferedReader permaReader = null; private static final String EOF = "</com>"; //FIXME: temporary solution private boolean mIsMulti = false; /** * Constructor. * * @param context */ public Network(Context context, Controller controller, boolean useDebugServer) { mContext = context; mUseDebugServer = useDebugServer; } @Override public void setUID(String userId) { mUserID = userId; } @Override public GoogleUserInfo getUserInfo() { // FIXME return null; } /** * Method for sending data to server via TLS protocol using own TrustManger to be able to trust self-signed * certificates. CA certificated must be located in assets folder. If no exception is thrown, it returns server * response. * * @param appContext * Application context to get CA certificate from assets * @param request * Request to server to be sent * @return Response from server * @throws IOException * Can't read CA certificate from assets, can't read InputStream or can't write OutputStream. * @throws CertificateException * Unknown certificate format (default X.509), can't generate CA certificate (it shouldn't occur) * @throws KeyStoreException * Bad type of KeyStore, can't set CA certificate to KeyStore * @throws NoSuchAlgorithmException * Unknown SSL/TLS protocol or unknown TrustManager algorithm (it shouldn't occur) * @throws KeyManagementException * general exception, thrown to indicate an exception during processing an operation concerning key * management * @throws UnknownHostException * *IMPORTANT* Server address or hostName wasn't not found * @throws SSLHandshakeException * *IMPORTANT* TLS handshake failed */ private String startCommunication(String request) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnknownHostException, SSLHandshakeException { /* * opening CA certificate from assets */ InputStream inStreamCertTmp = null; inStreamCertTmp = mContext.getAssets().open(ASSEST_CA_CERT); InputStream inStreamCert = new BufferedInputStream(inStreamCertTmp); Certificate ca; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); ca = cf.generateCertificate(inStreamCert); } finally { inStreamCert.close(); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry(ALIAS_CA_CERT, ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); // Open SSLSocket directly to server SSLSocket socket; if (mUseDebugServer) { socket = (SSLSocket) sslContext.getSocketFactory().createSocket(SERVER_ADDR_DEBUG, SERVER_PORT_DEBUG); } else { socket = (SSLSocket) sslContext.getSocketFactory().createSocket(SERVER_ADDR_PRODUCTION, SERVER_PORT_PRODUCTION); } HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier(); socket.setSoTimeout(SSLTIMEOUT); SSLSession s = socket.getSession(); // FIXME: nobody knows why if (!s.isValid()) Log.e(TAG, "Socket is NOT valid!!!!"); // Verify that the certificate hostName // This is due to lack of SNI support in the current SSLSocket. if (!hv.verify(SERVER_CN_CERTIFICATE, s)) { Log.e(TAG, "Certificate is not VERIFIED!!!"); throw new SSLHandshakeException("Expected CN value:" + SERVER_CN_CERTIFICATE + ", found " + s.getPeerPrincipal()); } // At this point SSLSocket performed certificate verification and // we have performed hostName verification, so it is safe to proceed. BufferedWriter w = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); BufferedReader r = new BufferedReader(new InputStreamReader(socket.getInputStream())); w.write(request, 0, request.length()); w.flush(); StringBuilder response = new StringBuilder(); String actRecieved = null; while ((actRecieved = r.readLine()) != null) { response.append(actRecieved); if(actRecieved.endsWith(EOF)) break; } // close socket, writer and reader w.close(); r.close(); socket.close(); // return server response return response.toString(); } private boolean multiSend(String request) throws IOException{ if(permaWriter == null) return false; permaWriter.write(request, 0, request.length()); permaWriter.flush(); return true; } private String multiRecv() throws IOException{ if(permaReader == null) return ""; StringBuilder response = new StringBuilder(); String actRecieved = null; while ((actRecieved = permaReader.readLine()) != null) { response.append(actRecieved); if(actRecieved.endsWith(EOF)) break; } return response.toString(); } //TODO: remove public void test(){ try { String uid = "101"; String aid = "10"; mUserID = uid; multiSessionBegin(); Log.d("test // get 1", getTimeZone(aid)+""); Log.d("test // set 2", setTimeZone(aid, 360)+""); Log.d("test // get 3", getTimeZone(aid)+""); // multiSend(XmlCreator.createGetTimeZone(uid, aid)); // String resp = multiRecv(); // Log.d("TEST one", resp); // multiSend(XmlCreator.createSetTimeZone(uid, aid, 180)); // resp = multiRecv(); // Log.d("TEST two", resp); // multiSend(XmlCreator.createGetTimeZone(uid, aid)); // resp = multiRecv(); // Log.e("baf", resp); // permaSocket.close(); multiSessionEnd(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void multiInit() throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnknownHostException,SSLHandshakeException { InputStream inStreamCertTmp = null; inStreamCertTmp = mContext.getAssets().open(ASSEST_CA_CERT); InputStream inStreamCert = new BufferedInputStream(inStreamCertTmp); Certificate ca; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); ca = cf.generateCertificate(inStreamCert); } finally { inStreamCert.close(); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry(ALIAS_CA_CERT, ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); // Open SSLSocket directly to server if (mUseDebugServer) { permaSocket = (SSLSocket) sslContext.getSocketFactory().createSocket(SERVER_ADDR_DEBUG, SERVER_PORT_DEBUG); } else { permaSocket = (SSLSocket) sslContext.getSocketFactory().createSocket(SERVER_ADDR_PRODUCTION, SERVER_PORT_PRODUCTION); } //perma2 = new Socket("192.168.1.150", 4444); HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier(); //permaSocket.setKeepAlive(true); permaSocket.setSoTimeout(35000); SSLSession s = permaSocket.getSession(); // FIXME: nobody knows why if (!s.isValid()) Log.e(TAG, "Socket is NOT valid!!!!"); // Verify that the certificate hostName // This is due to lack of SNI support in the current SSLSocket. if (!hv.verify(SERVER_CN_CERTIFICATE, s)) { Log.e(TAG, "Certificate is not VERIFIED!!!"); throw new SSLHandshakeException("Expected CN value:" + SERVER_CN_CERTIFICATE + ", found " + s.getPeerPrincipal()); } // At this point SSLSocket performed certificate verification and // we have performed hostName verification, so it is safe to proceed. permaWriter = new PrintWriter(permaSocket.getOutputStream()); permaReader = new BufferedReader(new InputStreamReader(permaSocket.getInputStream())); } /** * Method initiate session for multiple use * @throws AppException */ public void multiSessionBegin() throws AppException { if (!isAvailable()) throw new AppException(NetworkError.NO_CONNECTION); try { multiInit(); mIsMulti = true; } catch (Exception e) { throw AppException.wrap(e, NetworkError.COM_PROBLEMS); } } /** * Method close session to server if it was opened by multiSessionBegin method before * @throws AppException */ public void multiSessionEnd() throws AppException{ if (!mIsMulti) return; try { permaWriter.close(); permaReader.close(); permaSocket.close(); } catch (IOException e) { e.printStackTrace(); throw AppException.wrap(e, NetworkError.CLOSING_ERROR); } permaWriter = null; permaReader = null; permaSocket = null; mIsMulti = false; } /** * Checks if Internet connection is available. * * @return true if available, false otherwise */ @Override public boolean isAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } /** * Method return Mac address of device * @return */ public String getMAC(){ WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); if(wifiManager.isWifiEnabled()) { // WIFI ALREADY ENABLED. GRAB THE MAC ADDRESS HERE WifiInfo info = wifiManager.getConnectionInfo(); return info.getMacAddress(); } else { // ENABLE THE WIFI FIRST wifiManager.setWifiEnabled(true); // WIFI IS NOW ENABLED. GRAB THE MAC ADDRESS HERE WifiInfo info = wifiManager.getConnectionInfo(); String address = info.getMacAddress(); wifiManager.setWifiEnabled(false); return address; } } private ParsedMessage doRequest(String messageToSend) { if (!isAvailable()) throw new AppException(NetworkError.NO_CONNECTION); // ParsedMessage msg = null; // Debug.startMethodTracing("Support_231"); // long ltime = new Date().getTime(); try { String result = ""; if(mIsMulti){ if(multiSend(messageToSend)) result = multiRecv(); }else result = startCommunication(messageToSend); Log.d(TAG + " - fromApp", messageToSend); Log.i(TAG + " - fromSrv", result); return new XmlParsers().parseCommunication(result, false); } catch (Exception e) { throw AppException.wrap(e, NetworkError.COM_PROBLEMS); } finally { // Debug.stopMethodTracing(); // ltime = new Date().getTime() - ltime; // android.util.Log.d("Support_231", ltime+""); } } // /////////////////////////////////////SIGNIN,SIGNUP,ADAPTERS////////////////////// /** * Return actual UID used for communication (= active session) * @return UID for actual communication */ @Override public String getUID() { return mUserID; } /** * Method load UID from server * @return true if everything successful, false otherwise */ @Override public boolean loadUID(GoogleUserInfo googleUserInfo) { TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); String phoneId = tm.getDeviceId(); if (phoneId == null) phoneId = getMAC(); Log.i(TAG, String.format("HW ID (IMEI or MAC): %s", phoneId)); ParsedMessage msg = doRequest(XmlCreator.createGetUID(googleUserInfo.id, googleUserInfo.token, Locale.getDefault().getLanguage(), phoneId)); if (!msg.getUserId().isEmpty() && msg.getState() == State.UID) { mUserID = msg.getUserId(); return true; } FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } /** * Method register adapter to server * * @param adapterID * adapter id * @param adapterName * adapter name * @return true if adapter has been registered, false otherwise */ @Override public boolean addAdapter(String adapterID, String adapterName) { ParsedMessage msg = doRequest(XmlCreator.createAddAdapter(mUserID, adapterID, adapterName)); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } /** * Method ask for list of adapters. User has to be sign in before * * @return list of adapters or empty list */ @Override @SuppressWarnings("unchecked") public List<Adapter> getAdapters() { ParsedMessage msg = doRequest(XmlCreator.createGetAdapters(mUserID)); if (msg.getState() == State.ADAPTERS) return (List<Adapter>) msg.data; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } /** * Method ask for whole adapter data * * @param adapterID * of wanted adapter * @return Adapter */ @Override @SuppressWarnings("unchecked") public List<Facility> initAdapter(String adapterID){ ParsedMessage msg = doRequest(XmlCreator.createGetAllDevices(mUserID, adapterID)); if (msg.getState() == State.ALLDEVICES) return (ArrayList<Facility>) msg.data; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } /** * Method change adapter id * * @param oldId * id to be changed * @param newId * new id * @return true if change has been successfully */ @Override public boolean reInitAdapter(String oldId, String newId){ ParsedMessage msg = doRequest(XmlCreator.createReInitAdapter(mUserID, oldId, newId)); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } // /////////////////////////////////////DEVICES,LOGS//////////////////////////////// /** * Method send updated fields of devices * * @param devices * @return true if everything goes well, false otherwise */ @Override public boolean updateFacilities(String adapterID, List<Facility> facilities, EnumSet<SaveDevice> toSave){ ParsedMessage msg = doRequest(XmlCreator.createSetDevs(mUserID, adapterID, facilities, toSave)); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())).set(fa.getInfo(), fa.troubleMakers); } /** * Method send wanted fields of device to server * * @param adapterID * id of adapter * @param device * to save * @param toSave * ENUMSET specified fields to save * @return true if fields has been updated, false otherwise */ @Override public boolean updateDevice(String adapterID, Device device, EnumSet<SaveDevice> toSave){ ParsedMessage msg = doRequest(XmlCreator.createSetDev(mUserID, adapterID, device, toSave)); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())).set(fa.getInfo(), fa.troubleMakers); } /** * Method toggle or set actor to new value * * @param adapterID * @param device * @return */ @Override public boolean switchState(String adapterID, Device device){ ParsedMessage msg = doRequest(XmlCreator.createSwitch(mUserID, adapterID, device)); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())).set(fa.getInfo(), fa.troubleMakers); } /** * Method make adapter to special state, when listen for new sensors (e.g. 15s) and wait if some sensors has been * shaken to connect * * @param adapterID * @return */ @Override public boolean prepareAdapterToListenNewSensors(String adapterID){ ParsedMessage msg = doRequest(XmlCreator.createAdapterScanMode(mUserID, adapterID)); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())).set(fa.getInfo(), fa.troubleMakers); } /** * Method delete facility from server * * @param adapterID * @param facility * to be deleted * @return true if is deleted, false otherwise */ @Override public boolean deleteFacility(String adapterID, Facility facility){ ParsedMessage msg = doRequest(XmlCreator.createDeleteDevice(mUserID, adapterID, facility)); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())).set(fa.getInfo(), fa.troubleMakers); } /** * Method ask for actual data of facilities * * @param facilities * list of facilities to which needed actual data * @return list of updated facilities fields */ @Override @SuppressWarnings("unchecked") public List<Facility> getFacilities(List<Facility> facilities){ ParsedMessage msg = doRequest(XmlCreator.createGetDevices(mUserID, facilities)); if (msg.getState() == State.DEVICES) return (List<Facility>) msg.data; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())).set(fa.getInfo(), fa.troubleMakers); } /** * Method ask server for actual data of one facility * * @param facility * @return */ @Override public Facility getFacility(Facility facility){ ArrayList<Facility> list = new ArrayList<Facility>(); list.add(facility); return getFacilities(list).get(0); } @Override public boolean updateFacility(String adapterID, Facility facility, EnumSet<SaveDevice> toSave) { ArrayList<Facility> list = new ArrayList<Facility>(); list.add(facility); return updateFacilities(adapterID, list, toSave); } /** * Method get new devices * @param adapterID * @param facilities * @return */ @Override @SuppressWarnings("unchecked") public List<Facility> getNewFacilities(String adapterID) { ParsedMessage msg = doRequest(XmlCreator.createGetNewDevices(mUserID, adapterID)); if (msg.getState() == State.DEVICES) return (List<Facility>) msg.data; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())).set(fa.getInfo(), fa.troubleMakers); } /** * Method ask for data of logs * * @param deviceId * id of wanted device * @param pair * data of log (from, to, type, interval) * @return list of rows with logged data */ @Override public DeviceLog getLog(String adapterID, Device device, LogDataPair pair){ String msgToSend = XmlCreator.createGetLog(mUserID, adapterID, device.getFacility().getAddress(), device.getType().getTypeId(), String.valueOf(pair.interval.getStartMillis() / 1000), String.valueOf(pair.interval.getEndMillis() / 1000), pair.type.getValue(), pair.gap.getValue()); ParsedMessage msg = doRequest(msgToSend); if (msg.getState() == State.LOGDATA) { DeviceLog result = (DeviceLog) msg.data; result.setDataInterval(pair.gap); result.setDataType(pair.type); return result; } FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())).set(fa.getInfo(), fa.troubleMakers); } // /////////////////////////////////////ROOMS/////////////////////////////////////// /** * Method call to server for actual list of locations * * @return List with locations */ @Override @SuppressWarnings("unchecked") public List<Location> getLocations(String adapterID){ ParsedMessage msg = doRequest(XmlCreator.createGetRooms(mUserID, adapterID)); if (msg.getState() == State.ROOMS) return (List<Location>) msg.data; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } /** * Method call to server to update location * * @param locations * to update * @return true if everything is OK, false otherwise */ @Override public boolean updateLocations(String adapterID, List<Location> locations){ ParsedMessage msg = doRequest(XmlCreator.createSetRooms(mUserID, adapterID, locations)); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } /** * Method call to server to update location * * @param adapterID * @param location * @return */ @Override public boolean updateLocation(String adapterID, Location location){ List<Location> list = new ArrayList<Location>(); list.add(location); return updateLocations(adapterID, list); } /** * Method call to server and delete location * * @param location * to delete * @return true room is deleted, false otherwise */ @Override public boolean deleteLocation(String adapterID, Location location){ ParsedMessage msg = doRequest(XmlCreator.createDeleteRoom(mUserID, adapterID, location)); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } @Override public Location createLocation(String adapterID, Location location){ ParsedMessage msg = doRequest(XmlCreator.createAddRoom(mUserID, adapterID, location)); if (msg.getState() == State.ROOMCREATED) { location.setId((String) msg.data); return location; } FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } // /////////////////////////////////////VIEWS/////////////////////////////////////// /** * Method send newly created custom view * * @param viewName * name of new custom view * @param iconID * icon that is assigned to the new view * @param deviceIds * list of devices that are assigned to new view * @return true if everything goes well, false otherwise */ @Override public boolean addView(String viewName, int iconID, List<Device> devices){ ParsedMessage msg = doRequest(XmlCreator.createAddView(mUserID, viewName, iconID, devices)); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } /** * Method ask for list of all custom views * * @return list of defined custom views */ @Override @SuppressWarnings("unchecked") // FIXME: will be edited by ROB demands public List<CustomViewPair> getViews(){ ParsedMessage msg = doRequest(XmlCreator.createGetViews(mUserID)); if (msg.getState() == State.VIEWS) return (List<CustomViewPair>) msg.data; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } /** * Method delete whole custom view from server * * @param viewName * name of view to erase * @return true if view has been deleted, false otherwise */ @Override public boolean deleteView(String viewName){ ParsedMessage msg = doRequest(XmlCreator.createDelView(mUserID, viewName)); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } // FIXME: will be edited by ROB demands @Override public boolean updateView(String viewName, int iconId, Facility facility, NetworkAction action) { ParsedMessage msg = doRequest(XmlCreator.createSetView(mUserID, viewName, iconId, null, action)); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } // /////////////////////////////////////ACCOUNTS//////////////////////////////////// @Override public boolean addAccounts(String adapterID, ArrayList<User> users){ ParsedMessage msg = doRequest(XmlCreator.createAddAccounts(mUserID, adapterID, users)); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; String message = fa.getErrMessage() + "\n"; for (User u : (ArrayList<User>) fa.troubleMakers){ message += u.toDebugString(); } throw new AppException(message, NetworkError.fromValue(fa.getErrCode())); } /** * Method add new user to adapter * * @param adapterID * @param email * @param role * @return */ @Override public boolean addAccount(String adapterID, User user) { ArrayList<User> list = new ArrayList<User>(); list.add(user); return addAccounts(adapterID, list); } /** * Method delete users from actual adapter * * @param users * email of user * @return true if all users has been deleted, false otherwise */ @Override public boolean deleteAccounts(String adapterID, List<User> users){ ParsedMessage msg = doRequest(XmlCreator.createDelAccounts(mUserID, adapterID, users)); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } /** * Method delete on user from adapter * * @param adapterID * @param user * @return */ @Override public boolean deleteAccount(String adapterID, User user){ ArrayList<User> list = new ArrayList<User>(); list.add(user); return deleteAccounts(adapterID, list); } /** * Method ask for list of users of current adapter * * @return Map of users where key is email and value is User object */ @Override @SuppressWarnings("unchecked") public ArrayList<User> getAccounts(String adapterID){ ParsedMessage msg = doRequest(XmlCreator.createGetAccounts(mUserID, adapterID)); if (msg.getState() == State.ACCOUNTS) return (ArrayList<User>) msg.data; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } /** * Method update users roles on server on current adapter * * @param userNrole * map with email as key and role as value * @return true if all accounts has been changed false otherwise */ @Override public boolean updateAccounts(String adapterID, ArrayList<User> users){ ParsedMessage msg = doRequest(XmlCreator.createSetAccounts(mUserID, adapterID, users)); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } /** * Method update users role on adapter * * @param adapterID * @param user * @param role * @return */ @Override public boolean updateAccount(String adapterID, User user){ ArrayList<User> list = new ArrayList<User>(); list.add(user); return updateAccounts(adapterID, list); } // /////////////////////////////////////TIME//////////////////////////////////////// @Override public boolean setTimeZone(String adapterID, int differenceToGMT){ ParsedMessage msg = doRequest(XmlCreator.createSetTimeZone(mUserID, adapterID, differenceToGMT)); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } /** * Method call to server to get actual time zone * * @return integer in range <-12,12> */ @Override public int getTimeZone(String adapterID){ ParsedMessage msg = doRequest(XmlCreator.createGetTimeZone(mUserID, adapterID)); if (msg.getState() == State.TIMEZONE) return (Integer) msg.data; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } // /////////////////////////////////////NOTIFICATIONS/////////////////////////////// /** * Method delete old gcmid to avoid fake notifications * * @param email * of old/last user of gcmid (app+device id) * @param gcmID * - google cloud message id * @return true if id has been deleted, false otherwise */ public boolean deleteGCMID(String email, String gcmID){ ParsedMessage msg = doRequest(XmlCreator.createDeLGCMID(email, gcmID)); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } /** * Method set read flag to notification on server * * @param msgID * id of notification * @return true if server took flag, false otherwise */ @Override public boolean NotificationsRead(ArrayList<String> msgID){ ParsedMessage msg = doRequest(XmlCreator.createNotificaionRead(mUserID, msgID)); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } /** * Method set gcmID to server * @param email of user * @param gcmID to be set * @return true if id has been updated, false otherwise * FIXME: after merge need to by rewrite */ public boolean setGCMID(String email, String gcmID){ ParsedMessage msg = doRequest(XmlCreator.createSetGCMID(mUserID, gcmID)); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } // /////////////////////////////////////CONDITIONS,ACTIONS////////////////////////// @Override public Condition setCondition(Condition condition) { String messageToSend = XmlCreator.createAddCondition(mUserID, condition.getName(), XmlCreator.ConditionType.fromValue(condition.getType()), condition.getFuncs()); ParsedMessage msg = doRequest(messageToSend); if (msg.getState() == State.CONDITIONCREATED) { condition.setId((String) msg.data); return condition; } FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } @Override public boolean connectConditionWithAction(String conditionID, String actionID) { ParsedMessage msg = doRequest(XmlCreator.createConditionPlusAction(mUserID, conditionID, actionID)); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } @Override public Condition getCondition(Condition condition) { ParsedMessage msg = doRequest(XmlCreator.createGetCondition(mUserID, condition.getId())); if (msg.getState() == State.CONDITIONCREATED) { Condition cond = (Condition) msg.data; condition.setType(cond.getType()); condition.setFuncs(cond.getFuncs()); return condition; } FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } @Override @SuppressWarnings("unchecked") public List<Condition> getConditions() { ParsedMessage msg = doRequest(XmlCreator.createGetConditions(mUserID)); if (msg.getState() == State.CONDITIONS) return (List<Condition>) msg.data; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } @Override public boolean updateCondition(Condition condition) { String messageToSend = XmlCreator.createSetCondition(mUserID, condition.getName(), XmlCreator.ConditionType.fromValue(condition.getType()), condition.getId(), condition.getFuncs()); ParsedMessage msg = doRequest(messageToSend); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } @Override public boolean deleteCondition(Condition condition) { ParsedMessage msg = doRequest(XmlCreator.createDelCondition(mUserID, condition.getId())); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } @Override public ComplexAction setAction(ComplexAction action) { ParsedMessage msg = doRequest(XmlCreator.createAddAction(mUserID, action.getName(), action.getActions())); if (msg.getState() == State.ACTIONCREATED) { action.setId((String) msg.data); return action; } FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } @Override @SuppressWarnings("unchecked") public List<ComplexAction> getActions() { ParsedMessage msg = doRequest(XmlCreator.createGetActions(mUserID)); if (msg.getState() == State.ACTIONS) return (List<ComplexAction>) msg.data; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } @Override public ComplexAction getAction(ComplexAction action) { ParsedMessage msg = doRequest(XmlCreator.createGetCondition(mUserID, action.getId())); if (msg.getState() == State.ACTION) { ComplexAction act = (ComplexAction) msg.data; action.setActions(act.getActions()); return action; } FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } @Override public boolean updateAction(ComplexAction action) { String messageToSend = XmlCreator.createSetAction(mUserID, action.getName(), action.getId(), action.getActions()); ParsedMessage msg = doRequest(messageToSend); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } @Override public boolean deleteAction(ComplexAction action) { ParsedMessage msg = doRequest(XmlCreator.createDelAction(mUserID, action.getId())); if (msg.getState() == State.TRUE) return true; FalseAnswer fa = (FalseAnswer) msg.data; throw new AppException(fa.getErrMessage(), NetworkError.fromValue(fa.getErrCode())); } }
package de.ahlfeld.breminale.view; import android.databinding.DataBindingUtil; import android.graphics.Bitmap; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v7.widget.SearchView; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import com.androidmapsextensions.GoogleMap; import com.androidmapsextensions.MapView; import com.androidmapsextensions.Marker; import com.androidmapsextensions.MarkerOptions; import com.androidmapsextensions.OnMapReadyCallback; import com.bumptech.glide.Glide; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import java.util.ArrayList; import java.util.List; import de.ahlfeld.breminale.R; import de.ahlfeld.breminale.core.domain.domain.Location; import de.ahlfeld.breminale.databinding.FragmentBreminaleMapBinding; import de.ahlfeld.breminale.viewmodel.MapViewModel; /** * A simple {@link Fragment} subclass. */ public class MapFragment extends Fragment implements OnMapReadyCallback, MapViewModel.DataListener { private static final String TAG = MapFragment.class.getSimpleName(); private FragmentBreminaleMapBinding binding; private MapViewModel viewModel; private MapView mMapView; private GoogleMap mMap; private List<Location> locations; public MapFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment binding = DataBindingUtil.inflate(inflater, R.layout.fragment_breminale_map, container, false); viewModel = new MapViewModel(getContext(), this); setHasOptionsMenu(true); binding.setViewModel(viewModel); locations = new ArrayList<>(); mMapView = binding.mapView; mMapView.onCreate(savedInstanceState); mMapView.getExtendedMapAsync(this); return binding.getRoot(); } @Override public void onResume() { mMapView.onResume(); super.onResume(); } @Override public void onPause() { super.onPause(); mMapView.onPause(); } @Override public void onDestroy() { super.onDestroy(); mMapView.onDestroy(); viewModel.destroy(); } @Override public void onLowMemory() { super.onLowMemory(); mMapView.onLowMemory(); } public static MapFragment newInstance() { return new MapFragment(); } @Override public void onLocationsChanged(List<Location> locations) { this.locations = locations; drawMarkers(); } private void drawMarkers() { if (mMap != null && locations != null) { LatLngBounds.Builder builder = new LatLngBounds.Builder(); for (Location location : locations) { MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())); markerOptions.draggable(false); Marker marker = mMap.addMarker(markerOptions); marker.setData(location); builder.include(marker.getPosition()); loadMarkerIcon(marker, location); } LatLngBounds bounds = builder.build(); int padding = 0; CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds,padding); mMap.animateCamera(cu); } else { Log.e(TAG, "Map is null or locations is null"); } } private void loadMarkerIcon(@NonNull final Marker marker, @NonNull final Location location) { Glide.with(this).load(location.getMediumImageUrl()).asBitmap().into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(resource); marker.setIcon(icon); } }); } @Override public void onPrepareOptionsMenu(Menu menu) { MenuItem mSearchMenuItem = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) mSearchMenuItem.getActionView(); } @Override public void onMapReady(GoogleMap googleMap) { Log.i(TAG, "map is ready"); mMap = googleMap; mMap.setOnMarkerClickListener(marker -> { if(viewModel != null) { viewModel.onMarkerClick(marker.getData()); } return true; }); drawMarkers(); } }
package de.bitdroid.flooding.ceps; import com.google.common.base.Optional; import org.jvalue.ceps.api.RegistrationApi; import org.jvalue.ceps.api.notifications.Client; import org.jvalue.ceps.api.notifications.ClientDescription; import org.jvalue.ceps.api.notifications.GcmClientDescription; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.inject.Singleton; import de.bitdroid.flooding.gcm.GcmManager; import de.bitdroid.flooding.ods.OdsManager; import de.bitdroid.flooding.ods.Station; import retrofit.client.Response; import rx.Observable; import rx.functions.Func1; import timber.log.Timber; @Singleton public class CepsManager { private static final String PEGEL_ALARM_ABOVE_LEVEL_ADAPTER_ID = "pegelAlarmAboveLevel", PEGEL_ALARM_BELOW_LEVEL_ADAPTER_ID = "pegelAlarmBelowLevel"; private static final String ARGUMENT_UUID = "STATION_UUID", ARGUMENT_LEVEL = "LEVEL"; private final RegistrationApi registrationApi; private final OdsManager odsManager; private final GcmManager gcmManager; private List<Alarm> alarmsCache = null; @Inject CepsManager(RegistrationApi registrationApi, OdsManager odsManager, GcmManager gcmManager) { this.registrationApi = registrationApi; this.odsManager = odsManager; this.gcmManager = gcmManager; } public Observable<List<Alarm>> getAlarms() { if (alarmsCache != null) { List<Alarm> alarms = new ArrayList<>(alarmsCache); return Observable.just(alarms); } else { return Observable .merge( registrationApi.getAllClients(PEGEL_ALARM_ABOVE_LEVEL_ADAPTER_ID) .flatMap(new Func1<List<Client>, Observable<Map.Entry<String, Alarm.Builder>>>() { @Override public Observable<Map.Entry<String, Alarm.Builder>> call(List<Client> clients) { return Observable.from(parseClients(clients, true).entrySet()); } }), registrationApi.getAllClients(PEGEL_ALARM_BELOW_LEVEL_ADAPTER_ID) .flatMap(new Func1<List<Client>, Observable<Map.Entry<String, Alarm.Builder>>>() { @Override public Observable<Map.Entry<String, Alarm.Builder>> call(List<Client> clients) { return Observable.from(parseClients(clients, false).entrySet()); } })) .flatMap(new Func1<Map.Entry<String, Alarm.Builder>, Observable<Alarm>>() { @Override public Observable<Alarm> call(final Map.Entry<String, Alarm.Builder> entry) { return odsManager.getStationByUuid(entry.getKey()) .flatMap(new Func1<Optional<Station>, Observable<Alarm>>() { @Override public Observable<Alarm> call(Optional<Station> stationOptional) { if (!stationOptional.isPresent()) { Timber.e("failed to find station with uuid " + entry.getKey()); return Observable.empty(); } return Observable.just(entry.getValue().setStation(stationOptional.get()).build()); } }); } }) .toList() .flatMap(new Func1<List<Alarm>, Observable<List<Alarm>>>() { @Override public Observable<List<Alarm>> call(List<Alarm> alarms) { CepsManager.this.alarmsCache = new ArrayList<>(alarms); return Observable.just(alarms); } }); } } public Observable<Void> addAlarm(Alarm alarm) { Map<String, Object> args = new HashMap<>(); args.put(ARGUMENT_UUID, alarm.getStation().getUuid()); args.put(ARGUMENT_LEVEL, alarm.getLevel()); ClientDescription clientDescription = new GcmClientDescription(gcmManager.getRegId(), args); String adapterId = alarm.isAlarmWhenAboveLevel() ? PEGEL_ALARM_ABOVE_LEVEL_ADAPTER_ID : PEGEL_ALARM_BELOW_LEVEL_ADAPTER_ID; return registrationApi .registerClient(adapterId, clientDescription) .flatMap(new Func1<Client, Observable<Void>>() { @Override public Observable<Void> call(Client client) { clearAlarmsCache(); return Observable.just(null); } }); } public Observable<Void> removeAlarm(Alarm alarm) { String adapterId = alarm.isAlarmWhenAboveLevel() ? PEGEL_ALARM_ABOVE_LEVEL_ADAPTER_ID : PEGEL_ALARM_BELOW_LEVEL_ADAPTER_ID; String clientId = alarm.getId(); return registrationApi.unregisterClient(adapterId, clientId) .flatMap(new Func1<Response, Observable<Void>>() { @Override public Observable<Void> call(Response response) { clearAlarmsCache(); return Observable.just(null); } }); } public void clearAlarmsCache() { alarmsCache = null; } private Map<String, Alarm.Builder> parseClients(List<Client> clients, boolean alarmWhenAboveLevel) { Map<String, Alarm.Builder> builderMap = new HashMap<>(); // station uuid --> builder for (Client client : clients) { Map<String, Object> args = client.getEplArguments(); Alarm.Builder builder = new Alarm.Builder() .setId(client.getId()) .setLevel((double) args.get(ARGUMENT_LEVEL)) .setAlarmWhenAboveLevel(alarmWhenAboveLevel); builderMap.put((String) args.get(ARGUMENT_UUID), builder); } return builderMap; } }
package ee.shy.cli.command.remote; import ee.shy.cli.Command; import ee.shy.cli.HelptextBuilder; import ee.shy.core.LocalRepository; import ee.shy.core.Remote; import ee.shy.map.Named; import java.io.IOException; /** * Command for listing existing remotes. */ public class ListCommand implements Command { @Override public void execute(String[] args) throws IOException { for(Named<Remote> namedRemote : LocalRepository.newExisting().getRemotes().entrySet()) { System.out.println(namedRemote.getName() + " - " + namedRemote.getValue().getURI().toString()); } } @Override public String getHelp() { return new HelptextBuilder() .addWithoutArgs("List all existing remote URIs") .create(); } @Override public String getHelpBrief() { return "List remote URIs"; } }
package info.izumin.android.sunazuri; import android.app.Application; import android.content.Context; import info.izumin.android.sunazuri.data.DaggerDataComponent; import info.izumin.android.sunazuri.data.DataComponent; import info.izumin.android.sunazuri.infrastructure.DaggerInfrastructureComponent; import info.izumin.android.sunazuri.infrastructure.InfrastructureComponent; import info.izumin.android.sunazuri.infrastructure.InfrastructureModule; import info.izumin.android.sunazuri.infrastructure.api.ApiModule; import info.izumin.android.sunazuri.infrastructure.entity.OauthParams; import timber.log.Timber; import java.util.ArrayList; import java.util.List; public class Sunazuri extends Application { public static final String TAG = Sunazuri.class.getSimpleName(); private AppComponent component; public static Sunazuri get(Context context) { return (Sunazuri) context.getApplicationContext(); } @Override public void onCreate() { super.onCreate(); setupComponent(); setupTimber(); } public AppComponent getComponent() { return component; } private void setupTimber() { if (BuildConfig.DEBUG) { Timber.plant(new Timber.DebugTree()); } } private void setupComponent() { component = DaggerAppComponent.builder() .dataComponent(getDataComponent()) .build(); } private DataComponent getDataComponent() { return DaggerDataComponent.builder() .infrastructureComponent(getInfrastructureComponent()) .build(); } private InfrastructureComponent getInfrastructureComponent() { return DaggerInfrastructureComponent.builder() .infrastructureModule(new InfrastructureModule(this, BuildConfig.KEYSTORE_ALIAS)) .apiModule(new ApiModule(BuildConfig.ESA_API_ENDPOINT, getOauthParams(), getResponseEnvelopeKeys())) .build(); } private OauthParams getOauthParams() { return new OauthParams( BuildConfig.ESA_API_ENDPOINT, BuildConfig.ESA_CLIENT_ID, BuildConfig.ESA_CLIENT_SECRET, BuildConfig.ESA_CALLBACK_URI, BuildConfig.ESA_OAUTH_SCOPE, "code", "/oauth/authorize", BuildConfig.ESA_OAUTH_GRANT_TYPE ); } private List<String> getResponseEnvelopeKeys() { return new ArrayList<String>(){{ add("teams"); }}; } }
package ru.artyushov.jmhPlugin.configuration; import com.intellij.diagnostic.logging.LogConfigurationPanel; import com.intellij.execution.*; import com.intellij.execution.configuration.CompatibilityAwareRunProfile; import com.intellij.execution.configurations.*; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.options.SettingsEditorGroup; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.refactoring.listeners.RefactoringElementAdapter; import com.intellij.refactoring.listeners.RefactoringElementListener; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.HashMap; import java.util.Map; import static ru.artyushov.jmhPlugin.configuration.ConfigurationUtils.isBenchmarkEntryElement; import static ru.artyushov.jmhPlugin.configuration.ConfigurationUtils.toRunParams; public class JmhConfiguration extends ModuleBasedConfiguration<JavaRunConfigurationModule, Object> implements CommonJavaRunConfigurationParameters, CompatibilityAwareRunProfile, RefactoringListenerProvider { public static final String ATTR_VM_PARAMETERS = "vm-parameters"; public static final String ATTR_PROGRAM_PARAMETERS = "program-parameters"; public static final String ATTR_WORKING_DIR = "working-dir"; public static final String ATTR_BENCHMARK_TYPE = "benchmark-type"; public static final String ATTR_BENCHMARK_CLASS = "benchmark-class"; public enum Type { METHOD, CLASS } public static final String JMH_START_CLASS = "org.openjdk.jmh.Main"; private String vmParameters; private boolean isAlternativeJrePathEnabled = false; private String alternativeJrePath; private String programParameters; private String workingDirectory; private Map<String, String> envs = new HashMap<>(0, 1.0f); private boolean passParentEnvs; private String benchmarkClass; private Type type; public JmhConfiguration(final String name, final Project project, ConfigurationFactory configurationFactory) { this(name, new JavaRunConfigurationModule(project, false), configurationFactory); } public JmhConfiguration(String name, JavaRunConfigurationModule configurationModule, ConfigurationFactory factory) { super(name, configurationModule, factory); } @Override public void setVMParameters(String s) { this.vmParameters = s; } @Override public String getVMParameters() { return vmParameters; } @Override public boolean isAlternativeJrePathEnabled() { return isAlternativeJrePathEnabled; } @Override public void setAlternativeJrePathEnabled(boolean b) { this.isAlternativeJrePathEnabled = b; } @Override public String getAlternativeJrePath() { return alternativeJrePath; } @Override public void setAlternativeJrePath(String s) { this.alternativeJrePath = s; } @Nullable @Override public String getRunClass() { return JMH_START_CLASS; } @Nullable @Override public String getPackage() { return null; } @Override public void setProgramParameters(@Nullable String s) { this.programParameters = s; } @Nullable @Override public String getProgramParameters() { return programParameters; } @Override public void setWorkingDirectory(@Nullable String s) { this.workingDirectory = s; } @Nullable @Override public String getWorkingDirectory() { return workingDirectory; } @Override public void setEnvs(@NotNull Map<String, String> map) { envs = new HashMap<>(map); } @NotNull @Override public Map<String, String> getEnvs() { return new HashMap<>(envs); } @Override public void setPassParentEnvs(boolean b) { this.passParentEnvs = b; } @Override public boolean isPassParentEnvs() { return passParentEnvs; } public void setType(Type type) { this.type = type; } public Type getBenchmarkType() { return type; } public void setBenchmarkClass(String benchmarkClass) { this.benchmarkClass = benchmarkClass; } public String getBenchmarkClass() { return benchmarkClass; } @Override public Collection<Module> getValidModules() { return JavaRunConfigurationModule.getModulesForClass(getProject(), getRunClass()); } @NotNull @Override public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() { SettingsEditorGroup<JmhConfiguration> group = new SettingsEditorGroup<JmhConfiguration>(); group.addEditor(ExecutionBundle.message("run.configuration.configuration.tab.title"), new JmhConfigurable()); JavaRunConfigurationExtensionManager.getInstance().appendEditors(this, group); group.addEditor(ExecutionBundle.message("logs.tab.title"), new LogConfigurationPanel<JmhConfiguration>()); return group; } @Nullable @Override public RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment executionEnvironment) throws ExecutionException { return new JmhBenchmarkCommandLineState(executionEnvironment, this); } @Override public void writeExternal(@NotNull Element element) throws WriteExternalException { super.writeExternal(element); if (vmParameters != null) { element.setAttribute(ATTR_VM_PARAMETERS, vmParameters); } if (programParameters != null) { element.setAttribute(ATTR_PROGRAM_PARAMETERS, programParameters); } if (workingDirectory != null) { element.setAttribute(ATTR_WORKING_DIR, workingDirectory); } if (type != null) { element.setAttribute(ATTR_BENCHMARK_TYPE, type.name()); } if (benchmarkClass != null) { element.setAttribute(ATTR_BENCHMARK_CLASS, benchmarkClass); } element.setAttribute("isAlternativeJrePathEnabled", String.valueOf(isAlternativeJrePathEnabled)); if (alternativeJrePath != null) { element.setAttribute("alternativeJrePath", alternativeJrePath); } } @Override public void readExternal(@NotNull Element element) throws InvalidDataException { super.readExternal(element); setVMParameters(element.getAttributeValue(ATTR_VM_PARAMETERS)); setProgramParameters(element.getAttributeValue(ATTR_PROGRAM_PARAMETERS)); setWorkingDirectory(element.getAttributeValue(ATTR_WORKING_DIR)); setBenchmarkClass(element.getAttributeValue(ATTR_BENCHMARK_CLASS)); String typeString = element.getAttributeValue(ATTR_BENCHMARK_TYPE); if (typeString != null) { setType(Type.valueOf(typeString)); } setAlternativeJrePathEnabled(Boolean.parseBoolean(element.getAttributeValue("alternativeJrePathEnabled"))); setAlternativeJrePath(element.getAttributeValue("alternativeJrePath")); readModule(element); } @Override public boolean mustBeStoppedToRun(@NotNull RunConfiguration configuration) { return JmhConfigurationType.TYPE_ID.equals(configuration.getType().getId()); } @Nullable @Override public RefactoringElementListener getRefactoringElementListener(PsiElement element) { if (StringUtil.isEmpty(getProgramParameters())) { return null; } if (!isBenchmarkEntryElement(element)) { return null; } if (!getProgramParameters().startsWith(toRunParams(element, true))) { return null; } return new RefactoringElementAdapter() { @Override protected void elementRenamedOrMoved(@NotNull PsiElement newElement) { // replace benchmark class name at beginning of program params String newRunParams = toRunParams(newElement, true); int firstSpace = getProgramParameters().indexOf(' '); if (firstSpace == -1) { setProgramParameters(newRunParams); } else { setProgramParameters(newRunParams + getProgramParameters().substring(firstSpace)); } //TODO smart update name to change only bench name. But we can't do this because we don't know old class name setName(toRunParams(newElement, false)); if (newElement instanceof PsiClass) { setBenchmarkClass(((PsiClass)newElement).getQualifiedName()); } } @Override public void undoElementMovedOrRenamed(@NotNull PsiElement newElement, @NotNull String oldQualifiedName) { elementRenamedOrMoved(newElement); } }; } }
package jp.uguisu.aikotoba.mmlt; import android.app.Activity; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.media.AudioManager; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import com.txt_nifty.sketch.flmml.FlMML; import com.txt_nifty.sketch.flmml.MEvent; import com.txt_nifty.sketch.flmml.MStatus; import com.txt_nifty.sketch.flmml.MTrack; import java.util.ArrayList; public class TraceActivity extends Activity implements SurfaceHolder.Callback, View.OnTouchListener { SurfaceView mSurface; SurfaceHolder mHolder; ArrayList<MTrack> mTracks; private Runner mRunner; private int preY; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(mSurface = new SurfaceView(this)); setVolumeControlStream(AudioManager.STREAM_MUSIC); mSurface.setOnTouchListener(this); mHolder = mSurface.getHolder(); mHolder.addCallback(this); mTracks = FlMML.getStaticInstance().getRawMML().getRawTracks(); if (mTracks == null || mTracks.size() == 0) finish(); } @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { } @Override public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) { if (mRunner != null) mRunner.finish(); mRunner = new Runner(surfaceHolder, mTracks, new Handler()); new Thread(mRunner).start(); } @Override public void surfaceDestroyed(SurfaceHolder surfaceHolder) { mRunner.finish(); } @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: preY = (int) event.getY(); break; case MotionEvent.ACTION_MOVE: int y = (int) event.getY(); mRunner.scroll(y - preY); preY = y; } return true; } private static class Runner implements Runnable { private static final String[] table = {"c", "c+", "d", "d+", "e", "f", "f+", "g", "g+", "a", "a+", "b"}; private final SurfaceHolder mHolder; private final Handler mHandler; private boolean mFinish; private ArrayList<MTrack> mTracks; private int[] mPointer; private ArrayList<Integer>[] mNumber; private double[] mEvtime; private double mSpt; private byte[] mOctave; private volatile int scroll; Runner(SurfaceHolder sv, ArrayList<MTrack> tracks, Handler handler) { mHolder = sv; mTracks = tracks; mHandler = handler; init(); } private void scroll(int dy) { scroll += dy; if (scroll > 0) scroll = 0; } private void init() { class IntegerArrayList extends ArrayList<Integer> { } mNumber = new IntegerArrayList[mTracks.size()]; for (int i = 0; i < mNumber.length; i++) mNumber[i] = new IntegerArrayList(); mPointer = new int[mTracks.size()]; mOctave = new byte[mTracks.size()]; mEvtime = new double[mTracks.size()]; } private void finish() { mFinish = true; } private void calcSpt(double bpm) { double tps = bpm * 96.0 / 60.0; mSpt = 44100.0 / tps * 1000 / 44100; System.out.println("Spt:" + mSpt); } @Override public void run() { calcSpt(120); while (!mFinish) { int size = mTracks.size(); long now = FlMML.getStaticInstance().getNowMSec(); long start = System.currentTimeMillis(); for (int i = 0; i < size; i++) { ArrayList<MEvent> events = mTracks.get(i).getRawEvents(); int eLen = events.size(); int mae = mPointer[i]; while (mPointer[i] < eLen) { MEvent e = events.get(mPointer[i]); double milli = e.delta * mSpt; if (milli + mEvtime[i] <= now) { mEvtime[i] += milli; switch (e.getStatus()) { case MStatus.TEMPO: calcSpt(e.getTempo()); break; case MStatus.NOTE_ON: // POLY mNumber[i].add(e.getNoteNo()); break; case MStatus.NOTE_OFF: mNumber[i].remove((Integer) e.getNoteNo()); break; case MStatus.NOTE: mNumber[i].clear(); mNumber[i].add(e.getNoteNo()); break; case MStatus.EOT: finish(); Log.v("TraceThread", "finish()"); break; } mPointer[i]++; } else break; } } StringBuilder sb = new StringBuilder(); Canvas c = mHolder.lockCanvas(); if (c == null) continue; float scale = (c.getWidth() / 286f); c.translate(0, scroll); c.scale(scale, scale); c.drawColor(0xFF333333); //octave for (int i = 0; i < mTracks.size(); i++) { for (int key : mNumber[i]) { byte octave = (byte) (key < 0 ? (key + 1) / 12 - 1 : key / 12); if (octave < mOctave[i]) { mOctave[i] = octave; } if (octave > mOctave[i] + 1) { mOctave[i] = (byte) (octave - 1); } } } Paint p = new Paint(); drawKeyboards(c, p); drawPlayedWhiteKeys(c, p); drawKeys(c, p); drawPlayedBlackKeys(c, p); drawOctaves(c, p); p.setColor(0xFFFFFFFF); p.setTextSize(30); for (int i = 1; i < size; i++) { sb.append(i).append(' '); for (int key : mNumber[i]) { byte octave = (byte) (key < 0 ? (key + 1) / 12 - 1 : key / 12); int octavepos = octave - mOctave[i]; if (octavepos != 0 && octavepos != 1) sb.append(table[key % 12 >= 0 ? key % 12 : key % 12 + 12]) .append(key < 0 ? (key + 1) / 12 - 1 : key / 12) .append(' '); } c.drawText(sb.toString(), 150, 17 + 36 * (i) - 14, p); sb.setLength(0); } mHolder.unlockCanvasAndPost(c); try { Thread.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } } } private static final boolean[] KEY_IS_WHITE = new boolean[]{true, false, true, false, true, true, false, true, false, true, false, true}; private static final int[] KEY_DRAW_POS = new int[]{0, 1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 6}; private void drawPlayedWhiteKeys(Canvas c, Paint p) { p.setColor(Color.RED); c.save(); c.translate(0, 17); for (int i = 1, size = mTracks.size(); i < size; i++) { for (int mkey : mNumber[i]) { int key = mkey % 12 >= 0 ? mkey % 12 : mkey % 12 + 12; boolean bottom = KEY_IS_WHITE[key]; if (bottom) { int pos = KEY_DRAW_POS[key]; int x = 3 + pos * 10; byte octave = (byte) (mkey < 0 ? (mkey + 1) / 12 - 1 : mkey / 12); int octavepos = octave - mOctave[i]; if (octavepos != 0 && octavepos != 1) continue; x += octavepos * 70; c.drawRect(x, 0, x + 10, 30, p); } } c.translate(0, 36); } c.restore(); } private void drawPlayedBlackKeys(Canvas c, Paint p) { p.setColor(Color.RED); c.save(); c.translate(0, 17); for (int i = 1, size = mTracks.size(); i < size; i++) { for (int mkey : mNumber[i]) { int key = mkey % 12 >= 0 ? mkey % 12 : mkey % 12 + 12; boolean bottom = KEY_IS_WHITE[key]; if (!bottom) { int pos = KEY_DRAW_POS[key]; int x = 3 + pos * 10; byte octave = (byte) (mkey < 0 ? (mkey + 1) / 12 - 1 : mkey / 12); int octavepos = octave - mOctave[i]; if (octavepos != 0 && octavepos != 1) continue; x += octavepos * 70; c.drawRect(x - 2, 0, x + 3, 18, p); } } c.translate(0, 36); } c.restore(); } private void drawOctaves(Canvas c, Paint p) { p.setColor(Color.BLACK); p.setTextSize(8); c.save(); c.translate(3, 17); for (int i = 1, size = mTracks.size(); i < size; i++) { int octave = mOctave[i]; c.drawText(octave + "", 2.7f, 28, p); c.drawText(octave + 1 + "", 72.7f, 28, p); c.translate(0, 36); } c.restore(); } private void drawKeys(Canvas c, Paint p) { c.save(); c.translate(3, 17); p.setColor(0xFF000000); for (int j = 1, len = mTracks.size(); j < len; j++) { for (int i = 0; i < (14 + 1) * 10; i += 10) { c.drawLine(i, 0, i, 30, p); } for (int i = 0; i < (14 + 1) * 10; i += 10) { int t = i / 10 % 7; if (t != 0 && t != 3) c.drawRect(i - 2, 0, i + 3, 18, p); } c.translate(0, 36); } c.restore(); } private void drawKeyboards(Canvas c, Paint p) { c.save(); c.translate(3, 17); p.setColor(0xFFFFFFFF); for (int j = 1, len = mTracks.size(); j < len; j++) { c.drawRect(0, 0, 140, 30, p); c.translate(0, 36); } c.restore(); } } }
// copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. package org.lembed.bleSerialPort; import android.app.*; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGattCharacteristic; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.os.IBinder; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements BLeSerialPortService.Callback, View.OnClickListener { // UI elements private TextView messages; private EditText input; private Button connect; // BLE serial port instance. This is defined in BLeSerialPortService.java. private BLeSerialPortService serialPort; private final int REQUEST_DEVICE = 3; private final int REQUEST_ENABLE_BT = 2; private int rindex = 0; private ServiceConnection mServiceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder rawBinder) { serialPort = ((BLeSerialPortService.LocalBinder) rawBinder).getService() //register the application context to service for callback .setContext(getApplicationContext()) .registerCallback(MainActivity.this); } public void onServiceDisconnected(ComponentName classname) { serialPort.unregisterCallback(MainActivity.this) //Close the bluetooth gatt connection. .close(); } }; // Write some text to the messages text view. private void writeLine(final CharSequence text) { runOnUiThread(new Runnable() { @Override public void run() { messages.append(text); messages.append("\n"); } }); } // Handler for mouse click on the send button. public void sendView(View view) { String message = input.getText().toString(); serialPort.send(message); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Grab references to UI elements. messages = (TextView) findViewById(R.id.messages); input = (EditText) findViewById(R.id.input); // Enable auto-scroll in the TextView messages.setMovementMethod(new ScrollingMovementMethod()); connect = (Button) findViewById(R.id.connect); connect.setOnClickListener(this); // bind and start the bluetooth service Intent bindIntent = new Intent(this, BLeSerialPortService.class); bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE); } // OnResume, called right before UI is displayed. Connect to the bluetooth device. @Override protected void onResume() { super.onResume(); // set the screen to portrait if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } // if the bluetooth adatper is not support and enabled BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { finish(); } // request to open the bluetooth adapter if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } } // OnStop, close the service connection @Override protected void onStop() { super.onStop(); serialPort.stopSelf(); } @Override protected void onDestroy() { super.onDestroy(); unbindService(mServiceConnection); } @Override public void onBackPressed() { finish(); } @Override public void onClick(View v) { Button bt = (Button) v; if (v.getId() == R.id.connect) { // the device can send data to if (bt.getText().equals(getResources().getString(R.string.send))) { sendView(v); } // if the device is not connectted if (bt.getText().equals(getResources().getString(R.string.connect))) { Intent intent = new Intent(this, DeviceListActivity.class); startActivityForResult(intent, REQUEST_DEVICE); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_about) { return true; } return super.onOptionsItemSelected(item); } // serial port Callback handlers. @Override public void onConnected(Context context) { // when serial port device is connected writeLine("Connected!"); // Enable the send button runOnUiThread(new Runnable() { @Override public void run() { connect = (Button) findViewById(R.id.connect); connect.setText(R.string.send); } }); } @Override public void onConnectFailed(Context context) { // when some error occured which prevented serial port connection from completing. writeLine("Error connecting to device!"); runOnUiThread(new Runnable() { @Override public void run() { connect = (Button) findViewById(R.id.connect); connect.setText(R.string.connect); } }); } @Override public void onDisconnected(Context context) { //when device disconnected. writeLine("Disconnected!"); // update the send button text to connect runOnUiThread(new Runnable() { @Override public void run() { connect = (Button)findViewById(R.id.connect); connect.setText(R.string.connect); } }); } @Override public void onCommunicationError(int status, String msg) { // get the send value bytes if (status > 0) { }// when the send process found error, for example the send thread time out else { writeLine("send error status = " + status); } } @Override public void onReceive(Context context, BluetoothGattCharacteristic rx) { String msg = rx.getStringValue(0); rindex = rindex + msg.length(); writeLine("> " + rindex + ":" + msg); } @Override public void onDeviceFound(BluetoothDevice device) { // Called when a UART device is discovered (after calling startScan). writeLine("Found device : " + device.getAddress()); writeLine("Waiting for a connection ..."); } @Override public void onDeviceInfoAvailable() { writeLine(serialPort.getDeviceInfo()); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQUEST_DEVICE: //When the DeviceListActivity return, with the selected device address if (resultCode == Activity.RESULT_OK && data != null) { String deviceAddress = data.getStringExtra(BluetoothDevice.EXTRA_DEVICE); BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress); serialPort.connect(device); showMessage(device.getName()); } break; case REQUEST_ENABLE_BT: // When the request to enable Bluetooth returns if (resultCode == Activity.RESULT_OK) { Toast.makeText(this, "Bluetooth has turned on ", Toast.LENGTH_SHORT).show(); } else { // User did not enable Bluetooth or an error occurred Toast.makeText(this, "Problem in BT Turning ON ", Toast.LENGTH_SHORT).show(); } break; default: break; } } private void showMessage(String msg) { Log.e(MainActivity.class.getSimpleName(), msg); } }
package org.mozilla.focus.shortcut; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Build; import android.support.annotation.VisibleForTesting; import android.support.v4.content.pm.ShortcutInfoCompat; import android.support.v4.content.pm.ShortcutManagerCompat; import android.support.v4.graphics.drawable.IconCompat; import android.text.TextUtils; import org.mozilla.focus.activity.MainActivity; import org.mozilla.focus.utils.UrlUtils; import java.util.UUID; public class HomeScreen { public static final String ADD_TO_HOMESCREEN_TAG = "add_to_homescreen"; public static final String BLOCKING_ENABLED = "blocking_enabled"; /** * Create a shortcut for the given website on the device's home screen. */ public static void installShortCut(Context context, Bitmap icon, String url, String title, boolean blockingEnabled) { if (TextUtils.isEmpty(title.trim())) { title = generateTitleFromUrl(url); } installShortCutViaManager(context, icon, url, title, blockingEnabled); // Creating shortcut flow is different on Android up to 7, so we want to go // to the home screen manually where the user will see the new shortcut appear if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.N_MR1) { goToHomeScreen(context); } } /** * Create a shortcut via the AppCompat's shortcut manager. * <p> * On Android versions up to 7 shortcut will be created via system broadcast internally. * <p> * On Android 8+ the user will have the ability to add the shortcut manually * or let the system place it automatically. */ private static void installShortCutViaManager(Context context, Bitmap bitmap, String url, String title, boolean blockingEnabled) { if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)) { final ShortcutInfoCompat shortcut = new ShortcutInfoCompat.Builder(context, UUID.randomUUID().toString()) .setShortLabel(title) .setLongLabel(title) .setIcon(IconCompat.createWithBitmap(bitmap)) .setIntent(createShortcutIntent(context, url, blockingEnabled)) .build(); ShortcutManagerCompat.requestPinShortcut(context, shortcut, null); } } private static Intent createShortcutIntent(Context context, String url, boolean blockingEnabled) { final Intent shortcutIntent = new Intent(context, MainActivity.class); shortcutIntent.setAction(Intent.ACTION_VIEW); shortcutIntent.setData(Uri.parse(url)); shortcutIntent.putExtra(BLOCKING_ENABLED, blockingEnabled); shortcutIntent.putExtra(ADD_TO_HOMESCREEN_TAG, ADD_TO_HOMESCREEN_TAG); return shortcutIntent; } @VisibleForTesting static String generateTitleFromUrl(String url) { // For now we just use the host name and strip common subdomains like "www" or "m". return UrlUtils.stripCommonSubdomains(Uri.parse(url).getHost()); } /** * Switch to the the default home screen activity (launcher). */ private static void goToHomeScreen(Context context) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } }
package simonov.pk.myapplication; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.Status; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.location.ActivityRecognition; import com.google.android.gms.location.DetectedActivity; import com.google.android.gms.location.Geofence; import com.google.android.gms.location.GeofencingRequest; import com.google.android.gms.maps.model.LatLng; import android.support.v4.content.LocalBroadcastManager; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Map; public class MainActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback< Status> { protected static final String TAG="activity"; protected ActivityDetectionBroadcastReceiver mBroadcastReceiver; protected GoogleApiClient mGoogleApiClient; private TextView mStatusText; protected ArrayList<Geofence> mGeofenceList; private Button mAddGeofencesButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mStatusText = (TextView) findViewById(R.id.detectedActivities); mBroadcastReceiver = new ActivityDetectionBroadcastReceiver(); buildGoogleApiClient(); } public void requestActivityUpdatesButtonHandler(View view) { if (!mGoogleApiClient.isConnected()) { Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show(); return; } ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates( mGoogleApiClient, Constants.DETECTION_INTERVAL_IN_MILLISECONDS, getActivityDetectionPendingIntent() ).setResultCallback(this); } public void removeActivityUpdatesButtonHandler(View view) { if (!mGoogleApiClient.isConnected()) { Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show(); return; } // Remove all activity updates for the PendingIntent that was used to request activity // updates. ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates( mGoogleApiClient, getActivityDetectionPendingIntent() ).setResultCallback(this); } private PendingIntent getActivityDetectionPendingIntent() { Intent intent = new Intent(this, DetectedActivitiesIntentService.class); // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling // requestActivityUpdates() and removeActivityUpdates(). return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(ActivityRecognition.API) .build(); } public void onResult(Status status) { if (status.isSuccess()) { Log.e(TAG, "Successfully added activity detection."); } else { Log.e(TAG, "Error adding or removing activity detection: " + status.getStatusMessage()); } } @Override protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } @Override protected void onStop() { super.onStop(); mGoogleApiClient.disconnect(); } @Override protected void onResume() { super.onResume(); // Register the broadcast receiver that informs this activity of the DetectedActivity // object broadcast sent by the intent service. LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, new IntentFilter(Constants.BROADCAST_ACTION)); } @Override protected void onPause() { // Unregister the broadcast receiver that was registered during onResume(). LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver); super.onPause(); } @Override public void onConnected(Bundle connectionHint) { Log.i(TAG, "Connected to GoogleApiClient"); } @Override public void onConnectionFailed(ConnectionResult result) { // Refer to the javadoc for ConnectionResult to see what error codes might be returned in // onConnectionFailed. Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode()); } @Override public void onConnectionSuspended(int cause) { // The connection to Google Play services was lost for some reason. We call connect() to // attempt to re-establish the connection. Log.i(TAG, "Connection suspended"); mGoogleApiClient.connect(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * Returns a human readable String corresponding to a detected activity type. */ public String getActivityString(int detectedActivityType) { Resources resources = this.getResources(); switch(detectedActivityType) { case DetectedActivity.IN_VEHICLE: return resources.getString(R.string.in_vehicle); case DetectedActivity.ON_BICYCLE: return resources.getString(R.string.on_bicycle); case DetectedActivity.ON_FOOT: return resources.getString(R.string.on_foot); case DetectedActivity.RUNNING: return resources.getString(R.string.running); case DetectedActivity.STILL: return resources.getString(R.string.still); case DetectedActivity.TILTING: return resources.getString(R.string.tilting); case DetectedActivity.UNKNOWN: return resources.getString(R.string.unknown); case DetectedActivity.WALKING: return resources.getString(R.string.walking); default: return resources.getString(R.string.unidentifiable_activity, detectedActivityType); } } /** * Receiver for intents sent by DetectedActivitiesIntentService via a sendBroadcast(). * Receives a list of one or more DetectedActivity objects associated with the current state of * the device. */ public class ActivityDetectionBroadcastReceiver extends BroadcastReceiver { protected static final String TAG = "receiver"; @Override public void onReceive(Context context, Intent intent) { ArrayList<DetectedActivity> updatedActivities = intent.getParcelableArrayListExtra(Constants.ACTIVITY_EXTRA); String strStatus = ""; for(DetectedActivity thisActivity: updatedActivities){ strStatus += getActivityString(thisActivity.getType()) + thisActivity.getConfidence() + "%\n"; } mStatusText.setText(strStatus); } } //Lesson 3 public void populateGeofenceList() { for (Map.Entry<String, LatLng> entry : Constants.BAY_AREA_LANDMARKS.entrySet()) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(entry.getKey()) // Set the circular region of this geofence. .setCircularRegion( entry.getValue().latitude, entry.getValue().longitude, Constants.GEOFENCE_RADIUS_IN_METERS ) // Set the expiration duration of the geofence. This geofence gets automatically // removed after this period of time. .setExpirationDuration(Constants.GEOFENCE_EXPIRATION_IN_MILLISECONDS) // Set the transition types of interest. Alerts are only generated for these // transition. We track entry and exit transitions in this sample. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // Create the geofence. .build()); } } private GeofencingRequest getGeofencingRequest() { GeofencingRequest.Builder builder = new GeofencingRequest.Builder(); builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER); builder.addGeofences(mGeofenceList); return builder.build(); } private PendingIntent getGeofencePendingIntent() { Intent intent = new Intent(this, GeoFenceTransitionsIntentService.class); // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling addgeoFences() return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } }
package simonov.pk.myapplication; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.Status; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.location.ActivityRecognition; import com.google.android.gms.location.DetectedActivity; import android.support.v4.content.LocalBroadcastManager; import android.view.View; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback< Status> { protected static final String TAG="activity"; protected ActivityDetectionBroadcastReceiver mBroadcastReceiver; protected GoogleApiClient mGoogleApiClient; private TextView mStatusText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mStatusText = (TextView) findViewById(R.id.detectedActivities); mBroadcastReceiver = new ActivityDetectionBroadcastReceiver(); buildGoogleApiClient(); } public void requestActivityUpdatesButtonHandler(View view) { if (!mGoogleApiClient.isConnected()) { Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show(); return; } ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates( mGoogleApiClient, Constants.DETECTION_INTERVAL_IN_MILLISECONDS, getActivityDetectionPendingIntent() ).setResultCallback(this); } public void removeActivityUpdatesButtonHandler(View view) { if (!mGoogleApiClient.isConnected()) { Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show(); return; } // Remove all activity updates for the PendingIntent that was used to request activity // updates. ActivityRecognition.ActivityRecognitionApi.removeActivityUpdates( mGoogleApiClient, getActivityDetectionPendingIntent() ).setResultCallback(this); } private PendingIntent getActivityDetectionPendingIntent() { Intent intent = new Intent(this, DetectedActivitiesIntentService.class); // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling // requestActivityUpdates() and removeActivityUpdates(). return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(ActivityRecognition.API) .build(); } public void onResult(Status status) { if (status.isSuccess()) { Log.e(TAG, "Successfully added activity detection."); } else { Log.e(TAG, "Error adding or removing activity detection: " + status.getStatusMessage()); } } @Override protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } @Override protected void onStop() { super.onStop(); mGoogleApiClient.disconnect(); } @Override protected void onResume() { super.onResume(); // Register the broadcast receiver that informs this activity of the DetectedActivity // object broadcast sent by the intent service. LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, new IntentFilter(Constants.BROADCAST_ACTION)); } @Override protected void onPause() { // Unregister the broadcast receiver that was registered during onResume(). LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver); super.onPause(); } @Override public void onConnected(Bundle connectionHint) { Log.i(TAG, "Connected to GoogleApiClient"); } @Override public void onConnectionFailed(ConnectionResult result) { // Refer to the javadoc for ConnectionResult to see what error codes might be returned in // onConnectionFailed. Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode()); } @Override public void onConnectionSuspended(int cause) { // The connection to Google Play services was lost for some reason. We call connect() to // attempt to re-establish the connection. Log.i(TAG, "Connection suspended"); mGoogleApiClient.connect(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * Returns a human readable String corresponding to a detected activity type. */ public String getActivityString(int detectedActivityType) { Resources resources = this.getResources(); switch(detectedActivityType) { case DetectedActivity.IN_VEHICLE: return resources.getString(R.string.in_vehicle); case DetectedActivity.ON_BICYCLE: return resources.getString(R.string.on_bicycle); case DetectedActivity.ON_FOOT: return resources.getString(R.string.on_foot); case DetectedActivity.RUNNING: return resources.getString(R.string.running); case DetectedActivity.STILL: return resources.getString(R.string.still); case DetectedActivity.TILTING: return resources.getString(R.string.tilting); case DetectedActivity.UNKNOWN: return resources.getString(R.string.unknown); case DetectedActivity.WALKING: return resources.getString(R.string.walking); default: return resources.getString(R.string.unidentifiable_activity, detectedActivityType); } } /** * Receiver for intents sent by DetectedActivitiesIntentService via a sendBroadcast(). * Receives a list of one or more DetectedActivity objects associated with the current state of * the device. */ public class ActivityDetectionBroadcastReceiver extends BroadcastReceiver { protected static final String TAG = "receiver"; @Override public void onReceive(Context context, Intent intent) { ArrayList<DetectedActivity> updatedActivities = intent.getParcelableArrayListExtra(Constants.ACTIVITY_EXTRA); String strStatus = ""; for(DetectedActivity thisActivity: updatedActivities){ strStatus += getActivityString(thisActivity.getType()) + thisActivity.getConfidence() + "%\n"; } mStatusText.setText(strStatus); } } }
package org.commcare.android.framework; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.media.MediaPlayer; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.text.Spannable; import android.util.DisplayMetrics; import android.util.Pair; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.SearchView; import android.widget.TextView; import android.widget.Toast; import org.commcare.android.database.user.models.ACase; import org.commcare.android.javarosa.AndroidLogger; import org.commcare.android.tasks.templates.CommCareTask; import org.commcare.android.tasks.templates.CommCareTaskConnector; import org.commcare.android.util.AndroidUtil; import org.commcare.android.util.MarkupUtil; import org.commcare.android.util.SessionUnavailableException; import org.commcare.android.util.StringUtils; import org.commcare.dalvik.BuildConfig; import org.commcare.dalvik.application.CommCareApplication; import org.commcare.dalvik.dialogs.CustomProgressDialog; import org.commcare.dalvik.dialogs.DialogController; import org.commcare.dalvik.R; import org.commcare.suite.model.Detail; import org.commcare.suite.model.StackFrameStep; import org.commcare.util.SessionFrame; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.services.Logger; import org.javarosa.core.services.locale.Localization; import org.javarosa.core.util.NoLocalizedTextException; import org.odk.collect.android.views.media.AudioButton; import org.odk.collect.android.views.media.AudioController; import org.odk.collect.android.views.media.MediaEntity; import org.odk.collect.android.views.media.MediaState; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.media.MediaPlayer; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.text.Spannable; import android.util.DisplayMetrics; import android.util.Log; import android.util.Pair; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.TextView; import android.widget.Toast; import java.lang.reflect.Field; /** * Base class for CommCareActivities to simplify * common localization and workflow tasks * * @author ctsims * */ public abstract class CommCareActivity<R> extends FragmentActivity implements CommCareTaskConnector<R>, AudioController, DialogController, OnGestureListener { protected final static int DIALOG_PROGRESS = 32; protected final static String DIALOG_TEXT = "cca_dialog_text"; public final static String KEY_DIALOG_FRAG = "dialog_fragment"; StateFragment stateHolder; private boolean firstRun = true; //Fields for implementation of AudioController private MediaEntity currentEntity; private AudioButton currentButton; private MediaState stateBeforePause; //fields for implementing task transitions for CommCareTaskConnector boolean inTaskTransition; boolean shouldDismissDialog = true; private GestureDetector mGestureDetector; /* * (non-Javadoc) * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle) */ @Override @TargetApi(14) protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FragmentManager fm = this.getSupportFragmentManager(); stateHolder = (StateFragment) fm.findFragmentByTag("state"); // If the state holder is null, create a new one for this activity if (stateHolder == null) { stateHolder = new StateFragment(); fm.beginTransaction().add(stateHolder, "state").commit(); } else { if(stateHolder.getPreviousState() != null){ firstRun = stateHolder.getPreviousState().isFirstRun(); loadPreviousAudio(stateHolder.getPreviousState()); } else{ firstRun = true; } } if(this.getClass().isAnnotationPresent(ManagedUi.class)) { this.setContentView(this.getClass().getAnnotation(ManagedUi.class).value()); loadFields(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { getActionBar().setDisplayShowCustomEnabled(true); //Add breadcrumb bar BreadcrumbBarFragment bar = (BreadcrumbBarFragment) fm.findFragmentByTag("breadcrumbs"); // If the state holder is null, create a new one for this activity if (bar == null) { bar = new BreadcrumbBarFragment(); fm.beginTransaction().add(bar, "breadcrumbs").commit(); } } mGestureDetector = new GestureDetector(this, this); } private void loadPreviousAudio(AudioController oldController) { MediaEntity oldEntity = oldController.getCurrMedia(); if (oldEntity != null) { this.currentEntity = oldEntity; oldController.removeCurrentMediaEntity(); } } private void playPreviousAudio() { if (currentEntity == null) return; switch (currentEntity.getState()) { case PausedForRenewal: playCurrentMediaEntity(); break; case Paused: break; case Playing: case Ready: System.out.println("WARNING: state in loadPreviousAudio is invalid"); } } /* * Method to override in classes that need some functions called only once at the start * of the life cycle. Called by the CommCareActivity onResume() method; so, after the onCreate() * method of all classes, but before the onResume() of the overriding activity. State maintained in * stateFragment Fragment and firstRun boolean. */ public void fireOnceOnStart(){ // override when needed } /* * (non-Javadoc) * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: this.onBackPressed(); // try { // CommCareApplication._().getCurrentSession().clearAllState(); // } catch(SessionUnavailableException sue) { // // probably won't go anywhere with this // // app icon in action bar clicked; go home // Intent intent = new Intent(this, CommCareHomeActivity.class); // startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } private void loadFields() { CommCareActivity oldActivity = stateHolder.getPreviousState(); Class c = this.getClass(); for(Field f : c.getDeclaredFields()) { if(f.isAnnotationPresent(UiElement.class)) { UiElement element = f.getAnnotation(UiElement.class); try{ f.setAccessible(true); try { View v = this.findViewById(element.value()); f.set(this, v); if(oldActivity != null) { View oldView = (View)f.get(oldActivity); if(oldView != null) { if(v instanceof TextView) { ((TextView)v).setText(((TextView)oldView).getText()); } if(v == null || oldView == null) { Log.d("loadFields", "NullPointerException when trying to find view with id: " + + element.value() + " (" + getResources().getResourceEntryName(element.value()) + ") " + "v is " + v + ", oldView is " + oldView + " for activity " + oldActivity + ", element is: " + f + " (" + f.getName() + ")"); } v.setVisibility(oldView.getVisibility()); v.setEnabled(oldView.isEnabled()); continue; } } if(element.locale() != "") { if(v instanceof TextView) { ((TextView)v).setText(Localization.get(element.locale())); } else { throw new RuntimeException("Can't set the text for a " + v.getClass().getName() + " View!"); } } } catch (IllegalArgumentException e) { e.printStackTrace(); throw new RuntimeException("Bad Object type for field " + f.getName()); } catch (IllegalAccessException e) { throw new RuntimeException("Couldn't access the activity field for some reason"); } } finally { f.setAccessible(false); } } } } protected CommCareActivity getDestroyedActivityState() { return stateHolder.getPreviousState(); } protected boolean isTopNavEnabled() { return false; } boolean visible = false; /* (non-Javadoc) * @see android.app.Activity#onResume() */ @Override @TargetApi(11) protected void onResume() { super.onResume(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { //If we're in honeycomb this is taken care of by the fragment } else { this.setTitle(getTitle(this, getActivityTitle())); } visible = true; playPreviousAudio(); //set that this activity has run if(isFirstRun()){ fireOnceOnStart(); setActivityHasRun(); } } /* (non-Javadoc) * @see android.app.Activity#onPause() */ @Override protected void onPause() { super.onPause(); visible = false; if (currentEntity != null) saveEntityStateAndClear(); } protected boolean isInVisibleState() { return visible; } /* (non-Javadoc) * @see android.app.Activity#onDestroy() */ @Override protected void onDestroy() { super.onDestroy(); if (currentEntity != null) { attemptSetStateToPauseForRenewal(); } } /* (non-Javadoc) * @see org.commcare.android.tasks.templates.CommCareTaskConnector#connectTask(org.commcare.android.tasks.templates.CommCareTask) */ @Override public <A, B, C> void connectTask(CommCareTask<A, B, C, R> task) { //If stateHolder is null here, it's because it is restoring itself, it doesn't need //this step wakelock(); stateHolder.connectTask(task); //If we've left an old dialog showing during the task transition and it was from the same task //as the one that is starting, don't dismiss it CustomProgressDialog currDialog = getCurrentDialog(); if (currDialog != null && currDialog.getTaskId() == task.getTaskId()) { shouldDismissDialog = false; } } /* * (non-Javadoc) * @see org.commcare.android.tasks.templates.CommCareTaskConnector#getReceiver() */ @Override public R getReceiver() { return (R)this; } /* (non-Javadoc) * @see org.commcare.android.tasks.templates.CommCareTaskConnector#startBlockingForTask() * * Override these to control the UI for your task */ @Override public void startBlockingForTask(int id) { //attempt to dismiss the dialog from the last task before showing this one attemptDismissDialog(); //ONLY if shouldDismissDialog = true, i.e. if we chose to dismiss the last dialog during transition, show a new one if (id >= 0 && shouldDismissDialog) { this.showProgressDialog(id); } } /* (non-Javadoc) * @see org.commcare.android.tasks.templates.CommCareTaskConnector#stopBlockingForTask() */ @Override public void stopBlockingForTask(int id) { if (id >= 0) { if (inTaskTransition) { shouldDismissDialog = true; } else { dismissProgressDialog(); } } unlock(); } /* * (non-Javadoc) * @see org.commcare.android.tasks.templates.CommCareTaskConnector#startTaskTransition() */ @Override public void startTaskTransition() { inTaskTransition = true; } /* * (non-Javadoc) * @see org.commcare.android.tasks.templates.CommCareTaskConnector#stopTaskTransition() */ @Override public void stopTaskTransition() { inTaskTransition = false; attemptDismissDialog(); //reset shouldDismissDialog to true after this transition cycle is over shouldDismissDialog = true; } //if shouldDismiss flag has not been set to false in the course of a task transition, //then dismiss the dialog public void attemptDismissDialog() { if (shouldDismissDialog) { dismissProgressDialog(); } } /** * Handle an error in task execution. * * @param e */ protected void taskError(Exception e) { //TODO: For forms with good error reporting, integrate that Toast.makeText(this, Localization.get("activity.task.error.generic", new String[] {e.getMessage()}), Toast.LENGTH_LONG).show(); Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW, e.getMessage()); } /** * Display exception details as a pop-up to the user. * * @param e Exception to handle */ protected void displayException(Exception e) { String mErrorMessage = e.getMessage(); AlertDialog mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); mAlertDialog.setTitle(Localization.get("notification.case.predicate.title")); mAlertDialog.setMessage(Localization.get("notification.case.predicate.action", new String[] {mErrorMessage})); DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() { /* * (non-Javadoc) * @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int) */ @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON1: finish(); break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(Localization.get("dialog.ok"), errorListener); mAlertDialog.show(); } /* (non-Javadoc) * @see org.commcare.android.tasks.templates.CommCareTaskConnector#taskCancelled(int) */ @Override public void taskCancelled(int id) { } public void cancelCurrentTask() { stateHolder.cancelTask(); } /* * (non-Javadoc) * @see android.support.v4.app.FragmentActivity#onStop() */ @Override public void onStop() { super.onStop(); } private void wakelock() { int lockLevel = getWakeLockingLevel(); if(lockLevel == -1) { return;} stateHolder.wakelock(lockLevel); } private void unlock() { stateHolder.unlock(); } /** * @return The WakeLock flags that should be used for this activity's tasks. -1 * if this activity should not acquire/use the wakelock for tasks */ protected int getWakeLockingLevel() { return -1; } //Graphical stuff below, needs to get modularized public void TransplantStyle(TextView target, int resource) { //get styles from here TextView tv = (TextView)View.inflate(this, resource, null); int[] padding = {target.getPaddingLeft(), target.getPaddingTop(), target.getPaddingRight(),target.getPaddingBottom() }; target.setTextColor(tv.getTextColors().getDefaultColor()); target.setTypeface(tv.getTypeface()); target.setBackgroundDrawable(tv.getBackground()); target.setPadding(padding[0], padding[1], padding[2], padding[3]); } /** * The right-hand side of the title associated with this activity. * * This will update dynamically as the activity loads/updates, but if * it will ever have a value it must return a blank string when one * isn't available. * * @return */ public String getActivityTitle() { return null; } public static String getTopLevelTitleName(Context c) { String topLevel = null; try { topLevel = Localization.get("app.display.name"); return topLevel; } catch(NoLocalizedTextException nlte) { //nothing, app display name is optional for now. } return c.getString(org.commcare.dalvik.R.string.title_bar_name); } public static String getTitle(Context c, String local) { String topLevel = getTopLevelTitleName(c); String[] stepTitles = new String[0]; try { stepTitles = CommCareApplication._().getCurrentSession().getHeaderTitles(); //See if we can insert any case hacks int i = 0; for(StackFrameStep step : CommCareApplication._().getCurrentSession().getFrame().getSteps()){ try { if(SessionFrame.STATE_DATUM_VAL.equals(step.getType())) { //Haaack if(step.getId() != null && step.getId().contains("case_id")) { ACase foundCase = CommCareApplication._().getUserStorage(ACase.STORAGE_KEY, ACase.class).getRecordForValue(ACase.INDEX_CASE_ID, step.getValue()); stepTitles[i] = Localization.get("title.datum.wrapper", new String[] { foundCase.getName()}); } } } catch(Exception e) { //TODO: Your error handling is bad and you should feel bad } ++i; } } catch(SessionUnavailableException sue) { } String returnValue = topLevel; for(String title : stepTitles) { if(title != null) { returnValue += " > " + title; } } if(local != null) { returnValue += " > " + local; } return returnValue; } public void setActivityHasRun(){ this.firstRun = false; } public boolean isFirstRun(){ return this.firstRun; } /* * (non-Javadoc) * @see org.odk.collect.android.views.media.AudioController#getCurrMedia() * * All methods for implementation of AudioController */ @Override public MediaEntity getCurrMedia() { return currentEntity; } /* * (non-Javadoc) * @see org.odk.collect.android.views.media.AudioController#refreshCurrentAudioButton(org.odk.collect.android.views.media.AudioButton) */ @Override public void refreshCurrentAudioButton(AudioButton clickedButton) { if (currentButton != null && currentButton != clickedButton) { currentButton.setStateToReady(); } } /* * (non-Javadoc) * @see org.odk.collect.android.views.media.AudioController#setCurrent(org.odk.collect.android.views.media.MediaEntity, org.odk.collect.android.views.media.AudioButton) */ @Override public void setCurrent(MediaEntity e, AudioButton b) { refreshCurrentAudioButton(b); setCurrent(e); setCurrentAudioButton(b); } /* * (non-Javadoc) * @see org.odk.collect.android.views.media.AudioController#setCurrent(org.odk.collect.android.views.media.MediaEntity) */ @Override public void setCurrent(MediaEntity e) { releaseCurrentMediaEntity(); currentEntity = e; } /* * (non-Javadoc) * @see org.odk.collect.android.views.media.AudioController#setCurrentAudioButton(org.odk.collect.android.views.media.AudioButton) */ @Override public void setCurrentAudioButton(AudioButton b) { currentButton = b; } /* * (non-Javadoc) * @see org.odk.collect.android.views.media.AudioController#releaseCurrentMediaEntity() */ @Override public void releaseCurrentMediaEntity() { if (currentEntity != null) { MediaPlayer mp = currentEntity.getPlayer(); mp.reset(); mp.release(); } currentEntity = null; } /* * (non-Javadoc) * @see org.odk.collect.android.views.media.AudioController#playCurrentMediaEntity() */ @Override public void playCurrentMediaEntity() { if (currentEntity != null) { MediaPlayer mp = currentEntity.getPlayer(); mp.start(); currentEntity.setState(MediaState.Playing); } } /* * (non-Javadoc) * @see org.odk.collect.android.views.media.AudioController#pauseCurrentMediaEntity() */ @Override public void pauseCurrentMediaEntity() { if (currentEntity != null && currentEntity.getState().equals(MediaState.Playing)) { MediaPlayer mp = currentEntity.getPlayer(); mp.pause(); currentEntity.setState(MediaState.Paused); } } /* * (non-Javadoc) * @see org.odk.collect.android.views.media.AudioController#getMediaEntityId() */ @Override public Object getMediaEntityId() { return currentEntity.getId(); } /* * (non-Javadoc) * @see org.odk.collect.android.views.media.AudioController#attemptSetStateToPauseForRenewal() */ @Override public void attemptSetStateToPauseForRenewal() { if (stateBeforePause != null && stateBeforePause.equals(MediaState.Playing)) { currentEntity.setState(MediaState.PausedForRenewal); } } /* * (non-Javadoc) * @see org.odk.collect.android.views.media.AudioController#saveEntityStateAndClear() */ @Override public void saveEntityStateAndClear() { stateBeforePause = currentEntity.getState(); pauseCurrentMediaEntity(); refreshCurrentAudioButton(null); } /* * (non-Javadoc) * @see org.odk.collect.android.views.media.AudioController#setMediaEntityState(org.odk.collect.android.views.media.MediaState) */ @Override public void setMediaEntityState(MediaState state) { currentEntity.setState(state); } /* * (non-Javadoc) * @see org.odk.collect.android.views.media.AudioController#removeCurrentMediaEntity() */ @Override public void removeCurrentMediaEntity() { currentEntity = null; } /* * (non-Javadoc) * @see org.odk.collect.android.views.media.AudioController#getDuration() */ @Override public Integer getDuration() { if (currentEntity != null) { MediaPlayer mp = currentEntity.getPlayer(); return mp.getDuration(); } return null; } /* * (non-Javadoc) * @see org.odk.collect.android.views.media.AudioController#getProgress() */ @Override public Integer getProgress() { if (currentEntity != null) { MediaPlayer mp = currentEntity.getPlayer(); return mp.getCurrentPosition(); } return null; } protected void createErrorDialog(String errorMsg, boolean shouldExit) { createErrorDialog(this, errorMsg, shouldExit); } /** * Pop up a semi-friendly error dialog rather than crashing outright. * @param activity Activity to which to attach the dialog. * @param errorMsg * @param shouldExit If true, cancel activity when user exits dialog. */ public static void createErrorDialog(final Activity activity, String errorMsg, final boolean shouldExit) { AlertDialog dialog = new AlertDialog.Builder(activity).create(); dialog.setIcon(android.R.drawable.ic_dialog_info); dialog.setTitle(StringUtils.getStringRobust(activity, org.commcare.dalvik.R.string.error_occured)); dialog.setMessage(errorMsg); DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() { /* * (non-Javadoc) * @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int) */ @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON_POSITIVE: if (shouldExit) { activity.setResult(RESULT_CANCELED); activity.finish(); } break; } } }; dialog.setCancelable(false); dialog.setButton(AlertDialog.BUTTON_POSITIVE, StringUtils.getStringSpannableRobust(activity, org.commcare.dalvik.R.string.ok), errorListener); dialog.show(); } /** All methods for implementation of DialogController **/ /* * (non-Javadoc) * @see org.commcare.dalvik.dialogs.DialogController#updateProgress(java.lang.String, int) */ @Override public void updateProgress(String updateText, int taskId) { CustomProgressDialog mProgressDialog = getCurrentDialog(); if (mProgressDialog != null) { if (mProgressDialog.getTaskId() == taskId) { mProgressDialog.updateMessage(updateText); } else { Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "Attempting to update a progress dialog whose taskId does not match the" + "task for which the update message was intended."); } } } /* * (non-Javadoc) * @see org.commcare.dalvik.dialogs.DialogController#updateProgressBar(int, int, int) */ @Override public void updateProgressBar(int progress, int max, int taskId) { CustomProgressDialog mProgressDialog = getCurrentDialog(); if (mProgressDialog != null) { if (mProgressDialog.getTaskId() == taskId) { mProgressDialog.updateProgressBar(progress, max); } else { Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "Attempting to update a progress dialog whose taskId does not match the" + "task for which the update message was intended."); } } } /* * (non-Javadoc) * @see org.commcare.dalvik.dialogs.DialogController#showProgressDialog(int) */ @Override public void showProgressDialog(int taskId) { CustomProgressDialog dialog = generateProgressDialog(taskId); if (dialog != null) { dialog.show(getSupportFragmentManager(), KEY_DIALOG_FRAG); } } /* * (non-Javadoc) * @see org.commcare.dalvik.dialogs.DialogController#getCurrentDialog() */ @Override public CustomProgressDialog getCurrentDialog() { return (CustomProgressDialog) getSupportFragmentManager(). findFragmentByTag(KEY_DIALOG_FRAG); } /* * (non-Javadoc) * @see org.commcare.dalvik.dialogs.DialogController#dismissProgressDialog() */ @Override public void dismissProgressDialog() { CustomProgressDialog mProgressDialog = getCurrentDialog(); if (mProgressDialog != null && mProgressDialog.isAdded()) { mProgressDialog.dismissAllowingStateLoss(); } } /* * (non-Javadoc) * @see org.commcare.dalvik.dialogs.DialogController#generateProgressDialog(int) */ @Override public CustomProgressDialog generateProgressDialog(int taskId) { //dummy method for compilation, implementation handled in those subclasses that need it return null; } public Pair<Detail, TreeReference> requestEntityContext() { return null; } /** * Interface to perform additional setup code when adding an ActionBar * using the {@link #tryToAddActionSearchBar(android.app.Activity, * android.view.Menu, * org.commcare.android.framework.CommCareActivity.ActionBarInstantiator)} * tryToAddActionSearchBar} method. */ public interface ActionBarInstantiator { void onActionBarFound(SearchView searchView); } /** * Tries to add actionBar to current Activity and hides the current search * widget and runs ActionBarInstantiator if it exists. Used in * EntitySelectActivity and FormRecordListActivity. * * @param act Current activity * @param menu Menu passed through onCreateOptionsMenu * @param instantiator Optional ActionBarInstantiator for additional setup * code. */ public void tryToAddActionSearchBar(Activity act, Menu menu, ActionBarInstantiator instantiator) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { MenuInflater inflater = act.getMenuInflater(); inflater.inflate(org.commcare.dalvik.R.menu.activity_report_problem, menu); SearchView searchView = (SearchView)menu.findItem(org.commcare.dalvik.R.id.search_action_bar).getActionView(); if (searchView != null) { int[] searchViewStyle = AndroidUtil.getThemeColorIDs(this, new int[]{org.commcare.dalvik.R.attr.searchbox_action_bar_color}); int id = searchView.getContext() .getResources() .getIdentifier("android:id/search_src_text", null, null); TextView textView = (TextView)searchView.findViewById(id); textView.setTextColor(searchViewStyle[0]); if (instantiator != null) { instantiator.onActionBarFound(searchView); } } View bottomSearchWidget = act.findViewById(org.commcare.dalvik.R.id.searchfooter); if (bottomSearchWidget != null) { bottomSearchWidget.setVisibility(View.GONE); } } } /** * Whether or not the "Back" action makes sense for this activity. * * @return True if "Back" is a valid concept for the Activity ande should be shown * in the action bar if available. False otherwise. */ public boolean isBackEnabled() { return true; } /* * (non-Javadoc) * @see android.app.Activity#dispatchTouchEvent(android.view.MotionEvent) */ @Override public boolean dispatchTouchEvent(MotionEvent mv) { boolean handled = mGestureDetector == null ? false : mGestureDetector.onTouchEvent(mv); if (!handled) { return super.dispatchTouchEvent(mv); } return handled; } /* * (non-Javadoc) * @see android.view.GestureDetector.OnGestureListener#onDown(android.view.MotionEvent) */ @Override public boolean onDown(MotionEvent arg0) { return false; } /* * (non-Javadoc) * @see android.view.GestureDetector.OnGestureListener#onFling(android.view.MotionEvent, android.view.MotionEvent, float, float) */ @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (isHorizontalSwipe(this, e1, e2)) { if (velocityX <= 0) { return onForwardSwipe(); } return onBackwardSwipe(); } return false; } /** * Action to take when user swipes forward during activity. * @return Whether or not the swipe was handled */ protected boolean onForwardSwipe() { return false; } /** * Action to take when user swipes backward during activity. * @return Whether or not the swipe was handled */ protected boolean onBackwardSwipe() { return false; } /* * (non-Javadoc) * @see android.view.GestureDetector.OnGestureListener#onLongPress(android.view.MotionEvent) */ @Override public void onLongPress(MotionEvent arg0) { // ignore } /* * (non-Javadoc) * @see android.view.GestureDetector.OnGestureListener#onScroll(android.view.MotionEvent, android.view.MotionEvent, float, float) */ @Override public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) { return false; } /* * (non-Javadoc) * @see android.view.GestureDetector.OnGestureListener#onShowPress(android.view.MotionEvent) */ @Override public void onShowPress(MotionEvent arg0) { // ignore } /* * (non-Javadoc) * @see android.view.GestureDetector.OnGestureListener#onSingleTapUp(android.view.MotionEvent) */ @Override public boolean onSingleTapUp(MotionEvent arg0) { return false; } /** * Decide if two given MotionEvents represent a swipe. * @param activity * @param e1 First MotionEvent * @param e2 Second MotionEvent * @return True iff the movement is a definitive horizontal swipe. */ public static boolean isHorizontalSwipe(Activity activity, MotionEvent e1, MotionEvent e2) { DisplayMetrics dm = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(dm); //screen width and height in inches. double sw = dm.xdpi * dm.widthPixels; double sh = dm.ydpi * dm.heightPixels; //relative metrics for what constitutes a swipe (to adjust per screen size) double swipeX = 0.25; double swipeY = 0.25; //details of the motion itself float xMov = Math.abs(e1.getX() - e2.getX()); float yMov = Math.abs(e1.getY() - e2.getY()); double angleOfMotion = ((Math.atan(yMov / xMov) / Math.PI) * 180); //large screen (tablet style if( sw > 5 || sh > 5) { swipeX = 0.5; } // for all screens a swipe is left/right of at least .25" and at an angle of no more than 30 //degrees int xPixelLimit = (int) (dm.xdpi * .25); //int yPixelLimit = (int) (dm.ydpi * .25); return xMov > xPixelLimit && angleOfMotion < 30; } /* * Methods to make localization and styling easier for devs * copied from CommCareActivity */ public Spannable stylize(String text){ return MarkupUtil.styleSpannable(this, text); } public Spannable localize(String key){ return MarkupUtil.localizeStyleSpannable(this, key); } public Spannable localize(String key, String arg){ return MarkupUtil.localizeStyleSpannable(this, key, arg); } public Spannable localize(String key, String[] args){ return MarkupUtil.localizeStyleSpannable(this, key, args); } }
package us.mn.state.health.lims.security; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import us.mn.state.health.lims.common.log.LogEvent; public class SecurityFilter implements Filter { HashSet<String> getParamWhiteList; HashSet<String> getParamBlackList; public SecurityFilter() { } @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; boolean suspectedAttack = false; ArrayList<String> attackList = new ArrayList<String>(); //CSRF check for any "action" pages if (httpRequest.getMethod().equals("POST") || httpRequest.getRequestURI().contains("Update") || httpRequest.getRequestURI().contains("Save")) { String referer = httpRequest.getHeader("Referer"); String scheme = httpRequest.getScheme(); String host = httpRequest.getHeader("Host"); String contextPath = httpRequest.getContextPath(); String baseURL = scheme + "://" + host + contextPath; if (referer == null) { suspectedAttack = true; attackList.add("CSRF- null referer"); } else if (!referer.startsWith(baseURL)) { suspectedAttack = true; attackList.add("CSRF- " + referer); } } //Body Parameters in query check currently on blacklist String query = httpRequest.getQueryString(); if (query != null) { String[] urlParams = query.split("&"); for (int i = 0; i < urlParams.length; i++) { String urlParamName = urlParams[i].split("=")[0]; if (urlParamName.contains(".")) { urlParamName = urlParamName.split(".")[0]; } if (urlParamName.contains("[")) { urlParamName = urlParamName.split("[")[0]; } //if (!getParamWhiteList.contains(urlParamName)) { if (getParamBlackList.contains(urlParamName)) { suspectedAttack = true; attackList.add("Body Parameter in query- " + urlParamName); } } } //XSS check if (httpRequest.getMethod().equals("POST") || httpRequest.getRequestURI().contains("Update") || httpRequest.getRequestURI().contains("Save")) { Enumeration<String> parameterNames = httpRequest.getParameterNames(); while (parameterNames.hasMoreElements()) { String param = httpRequest.getParameter(parameterNames.nextElement()); String paramValue = java.net.URLDecoder.decode(param, "UTF-8"); paramValue = paramValue.replaceAll("\\s", ""); if (paramValue.contains("<script>") || paramValue.contains("</script>")) { suspectedAttack = true; attackList.add("XSS- " + param); } } } //Adding security headers to response httpResponse.addHeader("Content-Security-Policy","default-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval';" + "connect-src 'self'; img-src 'self'; style-src 'self' 'unsafe-inline';");//defines where content is allowed to be loaded from //httpResponse.addHeader("Strict-Transport-Security", "max-age=31536000"); //enforces communication must be over https httpResponse.addHeader("X-Content-Type-Options","nosniff"); //prevents MIME sniffing errors httpResponse.addHeader("X-Frame-Options", "SAMEORIGIN");//enforces whether page is allowed to be an iframe in another website httpResponse.addHeader("X-XSS-Protection","1"); //provides browser xss protection. attempts to cleanse. if (!suspectedAttack) { chain.doFilter(request, httpResponse); } else { StringBuilder attackMessage = new StringBuilder(); String separator = ""; attackMessage.append(httpRequest.getRequestURI()); attackMessage.append(" suspected attack(s) of type: "); for (String attack : attackList) { attackMessage.append(separator); separator = ","; attackMessage.append(attack); } //should log suspected attempt LogEvent.logWarn("SecurityFilter", "doFilter()", attackMessage.toString()); System.out.println(attackMessage.toString()); //send to safe page httpResponse.sendRedirect("Dashboard.do"); } } @Override public void init(FilterConfig filterConfig) throws ServletException { getParamWhiteList = new HashSet<String>(); //createWhiteList(); getParamBlackList = new HashSet<String>(); createBlackList(); } //less restrictive, less likely to stop valid traffic private void createBlackList() { getParamBlackList.add("englishValue"); getParamBlackList.add("frenchValue"); getParamBlackList.add("loginName"); getParamBlackList.add("observations"); getParamBlackList.add("password"); getParamBlackList.add("patientProperties"); getParamBlackList.add("ProjectData"); getParamBlackList.add("qaEvents"); getParamBlackList.add("referralItems"); getParamBlackList.add("resultList"); getParamBlackList.add("sampleOrderItems"); getParamBlackList.add("selectedIDs"); getParamBlackList.add("selectedRoles"); getParamBlackList.add("testResult"); } //more restrictive, more likely to stop valid traffic public void createWhiteList() { getParamWhiteList.add("accessionNumber"); getParamWhiteList.add("accessionNumberSearch"); getParamWhiteList.add("blank"); getParamWhiteList.add("cacheBreaker"); getParamWhiteList.add("date"); getParamWhiteList.add("field"); getParamWhiteList.add("fieldId"); getParamWhiteList.add("firstName"); getParamWhiteList.add("forward"); getParamWhiteList.add("guid"); getParamWhiteList.add("ID"); getParamWhiteList.add("labNo"); getParamWhiteList.add("labNumber"); getParamWhiteList.add("lang"); getParamWhiteList.add("lastName"); getParamWhiteList.add("NationalID"); getParamWhiteList.add("nationalID"); getParamWhiteList.add("patientID"); getParamWhiteList.add("personKey"); getParamWhiteList.add("provider"); getParamWhiteList.add("regionId"); getParamWhiteList.add("relativeToNow"); getParamWhiteList.add("report"); getParamWhiteList.add("sampleType"); getParamWhiteList.add("selectedSearchID"); getParamWhiteList.add("selectedValue"); getParamWhiteList.add("startingRecNo"); getParamWhiteList.add("STNumber"); getParamWhiteList.add("subjectNumber"); getParamWhiteList.add("suppressExternalSearch"); getParamWhiteList.add("test"); getParamWhiteList.add("testSectionId"); getParamWhiteList.add("type"); getParamWhiteList.add("value"); getParamWhiteList.add("ver"); } }
package org.apache.commons.validator; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import org.apache.commons.collections.FastHashMap; import org.apache.commons.digester.Digester; import org.apache.commons.digester.xmlrules.DigesterLoader; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.xml.sax.SAXException; public class ValidatorResources implements Serializable { /** * The set of public identifiers, and corresponding resource names, for * the versions of the configuration file DTDs that we know about. There * <strong>MUST</strong> be an even number of Strings in this list! */ private static final String registrations[] = { "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0//EN", "/org/apache/commons/validator/resources/validator_1_0.dtd", "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0.1//EN", "/org/apache/commons/validator/resources/validator_1_0_1.dtd", "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1//EN", "/org/apache/commons/validator/resources/validator_1_1.dtd" }; /** * Logger. */ protected static Log log = LogFactory.getLog(ValidatorResources.class); /** * <code>FastHashMap</code> of <code>FormSet</code>s stored under * a <code>Locale</code> key. */ protected FastHashMap hFormSets = new FastHashMap(); /** * <code>FastHashMap</code> of global constant values with * the name of the constant as the key. */ protected FastHashMap hConstants = new FastHashMap(); /** * <code>FastHashMap</code> of <code>ValidatorAction</code>s with * the name of the <code>ValidatorAction</code> as the key. */ protected FastHashMap hActions = new FastHashMap(); /** * The default locale on our server. */ protected static Locale defaultLocale = Locale.getDefault(); /** * Create an empty ValidatorResources object. */ public ValidatorResources() { super(); } /** * Create a ValidatorResources object from an InputStream. * * @param in InputStream to a validation.xml configuration file. It's the client's * responsibility to close this stream. */ public ValidatorResources(InputStream in) throws IOException { this(new InputStream[] { in }); } /** * Create a ValidatorResources object from an InputStream. * * @param streams An array of InputStreams to several validation.xml * configuration files that will be read in order and merged into this object. * It's the client's responsibility to close these streams. */ public ValidatorResources(InputStream[] streams) throws IOException { super(); URL rulesUrl = this.getClass().getResource("digester-rules.xml"); Digester digester = DigesterLoader.createDigester(rulesUrl); digester.setNamespaceAware(true); digester.setValidating(false); digester.setUseContextClassLoader(true); // register DTDs for (int i = 0; i < registrations.length; i += 2) { URL url = this.getClass().getResource(registrations[i + 1]); if (url != null) { digester.register(registrations[i], url.toString()); } } for (int i = 0; i < streams.length; i++) { digester.push(this); try { digester.parse(streams[i]); } catch (SAXException e) { log.error(e.getMessage(), e); } } this.process(); } /** * Add a <code>FormSet</code> to this <code>ValidatorResources</code> * object. It will be associated with the <code>Locale</code> of the * <code>FormSet</code>. * @deprecated Use addFormSet() instead. */ public void put(FormSet fs) { this.addFormSet(fs); } /** * Add a <code>FormSet</code> to this <code>ValidatorResources</code> * object. It will be associated with the <code>Locale</code> of the * <code>FormSet</code>. */ public void addFormSet(FormSet fs) { if (fs == null) { return; } String key = buildKey(fs); List formsets = (List) hFormSets.get(key); if (formsets == null) { formsets = new ArrayList(); hFormSets.put(key, formsets); } if (!formsets.contains(fs)) { if (log.isDebugEnabled()) { log.debug("Adding FormSet '" + fs.toString() + "'."); } formsets.add(fs); } } /** * Add a global constant to the resource. */ public void addConstant(Constant c) { this.addConstantParam(c.getName(), c.getValue()); } /** * Add a global constant to the resource. */ public void addConstantParam(String name, String value) { if (name != null && name.length() > 0 && value != null && value.length() > 0) { if (log.isDebugEnabled()) { log.debug("Adding Global Constant: " + name + "," + value); } this.hConstants.put(name, value); } } /** * <p>Add a <code>ValidatorAction</code> to the resource. It also creates an instance * of the class based on the <code>ValidatorAction</code>s classname and retrieves * the <code>Method</code> instance and sets them in the <code>ValidatorAction</code>.</p> */ public void addValidatorAction(ValidatorAction va) { if (va != null && va.getName() != null && va.getName().length() > 0 && va.getClassname() != null && va.getClassname().length() > 0 && va.getMethod() != null && va.getMethod().length() > 0) { va.init(); hActions.put(va.getName(), va); if (log.isDebugEnabled()) { log.debug( "Add ValidatorAction: " + va.getName() + "," + va.getClassname()); } } } /** * Get a <code>ValidatorAction</code> based on it's name. */ public ValidatorAction getValidatorAction(String key) { return (ValidatorAction) hActions.get(key); } /** * Get an unmodifiable <code>Map</code> of the <code>ValidatorAction</code>s. */ public Map getValidatorActions() { return Collections.unmodifiableMap(hActions); } /** * Builds a key to store the <code>FormSet</code> under based on it's language, country, * and variant values. */ protected String buildKey(FormSet fs) { String lang = fs.getLanguage(); String country = fs.getCountry(); String variant = fs.getVariant(); String key = ((lang != null && lang.length() > 0) ? lang : ""); key += ((country != null && country.length() > 0) ? "_" + country : ""); key += ((variant != null && variant.length() > 0) ? "_" + variant : ""); if (key.length() == 0) { key = defaultLocale.toString(); } return key; } /** * <p>Gets a <code>Form</code> based on the name of the form and the <code>Locale</code> that * most closely matches the <code>Locale</code> passed in. The order of <code>Locale</code> * matching is:</p> * <ol> * <li>language + country + variant</li> * <li>language + country</li> * <li>language</li> * <li>default locale</li> * </ol> * @deprecated Use getForm() instead. */ public Form get(Locale locale, Object formKey) { return this.getForm(locale, formKey); } /** * <p>Gets a <code>Form</code> based on the name of the form and the <code>Locale</code> that * most closely matches the <code>Locale</code> passed in. The order of <code>Locale</code> * matching is:</p> * <ol> * <li>language + country + variant</li> * <li>language + country</li> * <li>language</li> * <li>default locale</li> * </ol> */ public Form getForm(Locale locale, Object formKey) { return this.getForm( locale.getLanguage(), locale.getCountry(), locale.getVariant(), formKey); } /** * <p>Gets a <code>Form</code> based on the name of the form and the * <code>Locale</code> that most closely matches the <code>Locale</code> * passed in. The order of <code>Locale</code> matching is:</p> * <ol> * <li>language + country + variant</li> * <li>language + country</li> * <li>language</li> * <li>default locale</li> * </ol> * @deprecated Use getForm() instead. */ public Form get( String language, String country, String variant, Object formKey) { return this.getForm(language, country, variant, formKey); } /** * <p>Gets a <code>Form</code> based on the name of the form and the * <code>Locale</code> that most closely matches the <code>Locale</code> * passed in. The order of <code>Locale</code> matching is:</p> * <ol> * <li>language + country + variant</li> * <li>language + country</li> * <li>language</li> * <li>default locale</li> * </ol> */ public Form getForm( String language, String country, String variant, Object formKey) { String key = null; key = (language != null && language.length() > 0) ? language : ""; key += (country != null && country.length() > 0) ? "_" + country : ""; key += (variant != null && variant.length() > 0) ? "_" + variant : ""; List v = (List) hFormSets.get(key); if (v == null) { key = (language != null && language.length() > 0) ? language : ""; key += (country != null && country.length() > 0) ? "_" + country : ""; v = (List) hFormSets.get(key); } if (v == null) { key = (language != null && language.length() > 0) ? language : ""; v = (List) hFormSets.get(key); } if (v == null) { key = defaultLocale.toString(); v = (List) hFormSets.get(key); } if (v == null) { return null; } Iterator formsets = v.iterator(); while (formsets.hasNext()) { FormSet set = (FormSet) formsets.next(); if ((set != null) && (set.getForm(formKey) != null)) { return set.getForm(formKey); } } return null; } /** * <p>Process the <code>ValidatorResources</code> object. </p> * * <p>Currently sets the <code>FastHashMap</code>s to the 'fast' * mode and call the processes all other resources.</p> */ public void process() { hFormSets.setFast(true); hConstants.setFast(true); hActions.setFast(true); this.internalProcessForms(); } /** * <p>Process the <code>Form</code> objects. This clones the <code>Field</code>s * that don't exist in a <code>FormSet</code> compared to the default * <code>FormSet</code>.</p> * @deprecated This is an internal method that client classes need not call directly. */ public void processForms() { this.internalProcessForms(); } /** * <p>Process the <code>Form</code> objects. This clones the <code>Field</code>s * that don't exist in a <code>FormSet</code> compared to the default * <code>FormSet</code>.</p> * TODO When processForms() is removed from the public interface, rename this * private method back to "processForms". */ private void internalProcessForms() { //hFormSets.put(buildKey(fs), fs); String defaultKey = defaultLocale.toString(); // Loop through FormSets for (Iterator i = hFormSets.keySet().iterator(); i.hasNext();) { String key = (String) i.next(); // Skip default FormSet if (key.equals(defaultKey)) { continue; } List formsets = (List) hFormSets.get(key); Iterator formsetsIterator = formsets.iterator(); while (formsetsIterator.hasNext()) { FormSet fs = (FormSet) formsetsIterator.next(); // Loop through Forms and copy/clone fields from default locale for (Iterator x = fs.getForms().keySet().iterator(); x.hasNext();) { String formKey = (String) x.next(); Form form = (Form) fs.getForms().get(formKey); // Create a new Form object so the order from the default is // maintained (very noticable in the JavaScript). Form newForm = new Form(); newForm.setName(form.getName()); // Loop through the default locale form's fields // If they don't exist in the current locale's form, then clone them. Form defaultForm = get(defaultLocale, formKey); Iterator defaultFields = defaultForm.getFields().iterator(); while (defaultFields.hasNext()) { Field defaultField = (Field) defaultFields.next(); String fieldKey = defaultField.getKey(); if (form.getFieldMap().containsKey(fieldKey)) { newForm.addField( (Field) form.getFieldMap().get(fieldKey)); } else { Field field = getClosestLocaleField(fs, formKey, fieldKey); newForm.addField((Field) field.clone()); } } fs.addForm(newForm); } } } // Process Fully Constructed FormSets for (Iterator i = hFormSets.values().iterator(); i.hasNext();) { List formsets = (List) i.next(); Iterator formsetsIterator = formsets.iterator(); while (formsetsIterator.hasNext()) { FormSet fs = (FormSet) formsetsIterator.next(); if (!fs.isProcessed()) { fs.process(hConstants); } } } } /** * Retrieves the closest matching <code>Field</code> based * on <code>FormSet</code>'s locale. This is used when * constructing a clone, field by field, of partial * <code>FormSet</code>. */ protected Field getClosestLocaleField( FormSet fs, String formKey, String fieldKey) { Field field = null; String language = fs.getLanguage(); String country = fs.getCountry(); String variant = fs.getVariant(); if (!GenericValidator.isBlankOrNull(language) && !GenericValidator.isBlankOrNull(country) && !GenericValidator.isBlankOrNull(variant)) { Form form = get(language, country, variant, formKey); if (form.getFieldMap().containsKey(fieldKey)) { field = (Field) form.getFieldMap().get(fieldKey); } } if (field == null) { if (!GenericValidator.isBlankOrNull(language) && !GenericValidator.isBlankOrNull(country)) { Form form = get(language, country, null, formKey); if (form.getFieldMap().containsKey(fieldKey)) { field = (Field) form.getFieldMap().get(fieldKey); } } } if (field == null) { if (!GenericValidator.isBlankOrNull(language)) { Form form = get(language, null, null, formKey); if (form.getFieldMap().containsKey(fieldKey)) { field = (Field) form.getFieldMap().get(fieldKey); } } } if (field == null) { Form form = get(defaultLocale, formKey); if (form.getFieldMap().containsKey(fieldKey)) { field = (Field) form.getFieldMap().get(fieldKey); } } return field; } }
package com.alibaba.json.bvt.guava; import com.alibaba.fastjson.JSON; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.HashMultimap; import com.google.gson.Gson; import junit.framework.TestCase; public class HashMultimapTest extends TestCase { public void test_for_multimap() throws Exception { HashMultimap map = HashMultimap.create(); map.put("name", "a"); map.put("name", "b"); String json = JSON.toJSONString(map); assertTrue(json.equals("{\"name\":[\"a\",\"b\"]}") || json.equals("{\"name\":[\"b\",\"a\"]}")); } }
package com.opensource.diacoder.avp; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; public class OctetStringTest { @Test public void testOctetStringEncodeWithoutVendorId() { OctetString avp = new OctetString(); avp.setAvpCode(0x11223344); byte[] data = { (byte) 0x88, 0x77, 0x66 }; avp.setData(data); avp.setMandatory(true); byte[] expected = { 0x11, 0x22, 0x33, 0x44, 0x40, 0x00, 0x00, (byte) 0x0B, (byte) 0x88, 0x77, 0x66, 0x00 }; byte[] actual = avp.encode(); assertArrayEquals(expected, actual); } @Test public void testOctetStringEncodeWithVendorId() { OctetString avp = new OctetString(); avp.setAvpCode(0x11223344); avp.setVendorId(0xFFEEDDCC); byte[] data = { (byte) 0x88, 0x77 }; avp.setData(data); avp.setMandatory(false); byte[] expected = { 0x11, 0x22, 0x33, 0x44, (byte) 0x80, 0x00, 0x00, (byte) 0x0E, (byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC, (byte) 0x88, 0x77, 0x00, 0x00 }; byte[] actual = avp.encode(); assertArrayEquals(expected, actual); } @Test public void testOctetStringDecodeWithoutVendorId() { byte[] input = { (byte) 0x88, 0x77, 0x66, 0x55, 0x40, 0x00, 0x00, (byte) 0x0B, (byte) 0x88, 0x77, 0x66, 0x00 }; OctetString avp = new OctetString(); avp.decode(input); byte[] data = {(byte) 0x88, 0x77, 0x66}; assertEquals(0x88776655, avp.getAvpCode()); assertArrayEquals(data, avp.getData()); assertFalse(avp.hasVendorId()); assertTrue(avp.isMandatory()); assertFalse(avp.isEncrypted()); } @Test public void testUnsigned32DecodeWithVendorId() { byte[] input = { (byte) 0x88, 0x77, 0x66, 0x55, (byte) 0x80, 0x00, 0x00, (byte) 0x0E, (byte) 0x87, 0x65, 0x43, 0x21, (byte) 0x88, 0x77, 0x00, 0x00 }; OctetString avp = new OctetString(); avp.decode(input); assertEquals(0x88776655, avp.getAvpCode()); byte[] data = {(byte) 0x88, 0x77}; assertArrayEquals(data, avp.getData()); assertTrue(avp.hasVendorId()); assertEquals(0x87654321, avp.getVendorId()); assertFalse(avp.isMandatory()); assertFalse(avp.isEncrypted()); } }
package com.taskadapter.redmineapi; import com.taskadapter.redmineapi.bean.Changeset; import com.taskadapter.redmineapi.bean.CustomFieldFactory; import com.taskadapter.redmineapi.bean.Issue; import com.taskadapter.redmineapi.bean.IssueCategory; import com.taskadapter.redmineapi.bean.IssueCategoryFactory; import com.taskadapter.redmineapi.bean.IssueFactory; import com.taskadapter.redmineapi.bean.IssueRelation; import com.taskadapter.redmineapi.bean.IssueStatus; import com.taskadapter.redmineapi.bean.Journal; import com.taskadapter.redmineapi.bean.JournalDetail; import com.taskadapter.redmineapi.bean.Project; import com.taskadapter.redmineapi.bean.SavedQuery; import com.taskadapter.redmineapi.bean.TimeEntry; import com.taskadapter.redmineapi.bean.TimeEntryFactory; import com.taskadapter.redmineapi.bean.Tracker; import com.taskadapter.redmineapi.bean.User; import com.taskadapter.redmineapi.bean.Version; import com.taskadapter.redmineapi.bean.VersionFactory; import com.taskadapter.redmineapi.bean.Watcher; import com.taskadapter.redmineapi.bean.WatcherFactory; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; import static com.taskadapter.redmineapi.IssueHelper.createIssues; import static org.fest.assertions.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class IssueManagerTest { private static final Logger logger = LoggerFactory.getLogger(IssueManagerTest.class); // TODO We don't know activities' IDs! private static final Integer ACTIVITY_ID = 8; private static IssueManager issueManager; private static ProjectManager projectManager; private static String projectKey; private static RedmineManager mgr; private static UserManager userManager; @BeforeClass public static void oneTimeSetup() { mgr = IntegrationTestHelper.createRedmineManager(); userManager = mgr.getUserManager(); issueManager = mgr.getIssueManager(); projectManager = mgr.getProjectManager(); projectKey = IntegrationTestHelper.createProject(mgr); } @AfterClass public static void oneTimeTearDown() { IntegrationTestHelper.deleteProject(mgr, projectKey); } @Test public void issueCreated() { try { Issue issueToCreate = IssueFactory.createWithSubject("test zzx"); Calendar startCal = Calendar.getInstance(); // have to clear them because they are ignored by Redmine and // prevent from comparison later startCal.clear(Calendar.HOUR_OF_DAY); startCal.clear(Calendar.MINUTE); startCal.clear(Calendar.SECOND); startCal.clear(Calendar.MILLISECOND); startCal.add(Calendar.DATE, 5); issueToCreate.setStartDate(startCal.getTime()); Calendar due = Calendar.getInstance(); due.add(Calendar.MONTH, 1); issueToCreate.setDueDate(due.getTime()); User assignee = IntegrationTestHelper.getOurUser(); issueToCreate.setAssignee(assignee); String description = "This is the description for the new task." + "\nIt has several lines." + "\nThis is the last line."; issueToCreate.setDescription(description); float estimatedHours = 44; issueToCreate.setEstimatedHours(estimatedHours); Issue newIssue = issueManager.createIssue(projectKey, issueToCreate); assertNotNull("Checking returned result", newIssue); assertNotNull("New issue must have some ID", newIssue.getId()); // check startDate Calendar returnedStartCal = Calendar.getInstance(); returnedStartCal.setTime(newIssue.getStartDate()); assertEquals(startCal.get(Calendar.YEAR), returnedStartCal.get(Calendar.YEAR)); assertEquals(startCal.get(Calendar.MONTH), returnedStartCal.get(Calendar.MONTH)); assertEquals(startCal.get(Calendar.DAY_OF_MONTH), returnedStartCal.get(Calendar.DAY_OF_MONTH)); // check dueDate Calendar returnedDueCal = Calendar.getInstance(); returnedDueCal.setTime(newIssue.getDueDate()); assertEquals(due.get(Calendar.YEAR), returnedDueCal.get(Calendar.YEAR)); assertEquals(due.get(Calendar.MONTH), returnedDueCal.get(Calendar.MONTH)); assertEquals(due.get(Calendar.DAY_OF_MONTH), returnedDueCal.get(Calendar.DAY_OF_MONTH)); // check ASSIGNEE User actualAssignee = newIssue.getAssignee(); assertNotNull("Checking assignee not null", actualAssignee); assertEquals("Checking assignee id", assignee.getId(), actualAssignee.getId()); // check AUTHOR Integer EXPECTED_AUTHOR_ID = IntegrationTestHelper.getOurUser().getId(); assertEquals(EXPECTED_AUTHOR_ID, newIssue.getAuthor() .getId()); // check ESTIMATED TIME assertEquals((Float) estimatedHours, newIssue.getEstimatedHours()); // check multi-line DESCRIPTION String regexpStripExtra = "\\r|\\n|\\s"; description = description.replaceAll(regexpStripExtra, ""); String actualDescription = newIssue.getDescription(); actualDescription = actualDescription.replaceAll(regexpStripExtra, ""); assertEquals(description, actualDescription); // PRIORITY assertNotNull(newIssue.getPriorityId()); assertTrue(newIssue.getPriorityId() > 0); } catch (Exception e) { e.printStackTrace(); fail(); } } @Test public void issueWithParentCreated() { try { Issue parentIssue = IssueFactory.createWithSubject("parent 1"); Issue newParentIssue = issueManager.createIssue(projectKey, parentIssue); assertNotNull("Checking parent was created", newParentIssue); assertNotNull("Checking ID of parent issue is not null", newParentIssue.getId()); // Integer parentId = 46; Integer parentId = newParentIssue.getId(); Issue childIssue = IssueFactory.createWithSubject("child 1"); childIssue.setParentId(parentId); Issue newChildIssue = issueManager.createIssue(projectKey, childIssue); assertEquals("Checking parent ID of the child issue", parentId, newChildIssue.getParentId()); } catch (Exception e) { e.printStackTrace(); fail(); } } @Test public void testUpdateIssue() { try { String originalSubject = "Issue " + new Date(); Issue issue = IssueFactory.createWithSubject(originalSubject); Issue newIssue = issueManager.createIssue(projectKey, issue); String changedSubject = "changed subject"; newIssue.setSubject(changedSubject); issueManager.update(newIssue); Issue reloadedFromRedmineIssue = issueManager.getIssueById(newIssue.getId()); assertEquals( "Checking if 'update issue' operation changed the 'subject' field", changedSubject, reloadedFromRedmineIssue.getSubject()); } catch (Exception e) { e.printStackTrace(); fail(); } } /** * Tests the retrieval of an {@link Issue} by its ID. * * @throws com.taskadapter.redmineapi.RedmineException * thrown in case something went wrong in Redmine * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws com.taskadapter.redmineapi.NotFoundException * thrown in case the objects requested for could not be found */ @Test public void testGetIssueById() throws RedmineException { String originalSubject = "Issue " + new Date(); Issue issue = IssueFactory.createWithSubject(originalSubject); Issue newIssue = issueManager.createIssue(projectKey, issue); Issue reloadedFromRedmineIssue = issueManager.getIssueById(newIssue.getId()); assertEquals( "Checking if 'get issue by ID' operation returned issue with same 'subject' field", originalSubject, reloadedFromRedmineIssue.getSubject()); Tracker tracker = reloadedFromRedmineIssue.getTracker(); assertNotNull("Tracker of issue should not be null", tracker); assertNotNull("ID of tracker of issue should not be null", tracker.getId()); assertNotNull("Name of tracker of issue should not be null", tracker.getName()); } @Test public void testGetIssues() { try { // create at least 1 issue Issue issueToCreate = IssueFactory.createWithSubject("testGetIssues: " + new Date()); Issue newIssue = issueManager.createIssue(projectKey, issueToCreate); List<Issue> issues = issueManager.getIssues(projectKey, null); assertTrue(issues.size() > 0); boolean found = false; for (Issue issue : issues) { if (issue.getId().equals(newIssue.getId())) { found = true; break; } } if (!found) { fail("getIssues() didn't return the issue we just created. The query " + " must have returned all issues created during the last 2 days"); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test(expected = NotFoundException.class) public void testGetIssuesInvalidQueryId() throws RedmineException { Integer invalidQueryId = 9999999; issueManager.getIssues(projectKey, invalidQueryId); } @Test public void testCreateIssueNonUnicodeSymbols() { try { String nonLatinSymbols = "Example with accents Ao"; Issue toCreate = IssueFactory.createWithSubject(nonLatinSymbols); Issue created = issueManager.createIssue(projectKey, toCreate); assertEquals(nonLatinSymbols, created.getSubject()); } catch (Exception e) { fail(e.getMessage()); } } @Test public void testCreateIssueSummaryOnly() { try { Issue issueToCreate = new Issue(); issueToCreate.setSubject("This is the summary line 123"); Issue newIssue = issueManager.createIssue(projectKey, issueToCreate); assertNotNull("Checking returned result", newIssue); assertNotNull("New issue must have some ID", newIssue.getId()); // check AUTHOR Integer EXPECTED_AUTHOR_ID = IntegrationTestHelper.getOurUser().getId(); assertEquals(EXPECTED_AUTHOR_ID, newIssue.getAuthor() .getId()); } catch (Exception e) { e.printStackTrace(); fail(); } } @Test(expected = NotFoundException.class) public void testCreateIssueInvalidProjectKey() throws RedmineException { Issue issueToCreate = IssueFactory.createWithSubject("Summary line 100"); issueManager.createIssue("someNotExistingProjectKey", issueToCreate); } @Test(expected = NotFoundException.class) public void testGetIssueNonExistingId() throws RedmineException { int someNonExistingID = 999999; issueManager.getIssueById(someNonExistingID); } @Test(expected = NotFoundException.class) public void testUpdateIssueNonExistingId() throws RedmineException { int nonExistingId = 999999; Issue issue = IssueFactory.create(nonExistingId); issueManager.update(issue); } @Test public void testGetIssuesPaging() { try { // create 27 issues. default page size is 25. createIssues(issueManager, projectKey, 27); // mgr.setObjectsPerPage(5); <-- does not work now List<Issue> issues = issueManager.getIssues(projectKey, null); assertTrue(issues.size() > 26); Set<Issue> issueSet = new HashSet<Issue>(issues); assertEquals(issues.size(), issueSet.size()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test(expected = NotFoundException.class) public void testDeleteIssue() throws RedmineException { Issue issue = createIssues(issueManager, projectKey, 1).get(0); Issue retrievedIssue = issueManager.getIssueById(issue.getId()); assertEquals(issue, retrievedIssue); issueManager.deleteIssue(issue.getId()); issueManager.getIssueById(issue.getId()); } @Test public void testUpdateIssueSpecialXMLtags() throws Exception { Issue issue = createIssues(issueManager, projectKey, 1).get(0); String newSubject = "\"text in quotes\" and <xml> tags"; String newDescription = "<taghere>\"abc\"</here>"; issue.setSubject(newSubject); issue.setDescription(newDescription); issueManager.update(issue); Issue updatedIssue = issueManager.getIssueById(issue.getId()); assertEquals(newSubject, updatedIssue.getSubject()); assertEquals(newDescription, updatedIssue.getDescription()); } @Test public void testCreateRelation() { try { List<Issue> issues = createIssues(issueManager, projectKey, 2); Issue src = issues.get(0); Issue target = issues.get(1); String relationText = IssueRelation.TYPE.precedes.toString(); IssueRelation r = issueManager.createRelation(src.getId(), target.getId(), relationText); assertEquals(src.getId(), r.getIssueId()); assertEquals(target.getId(), r.getIssueToId()); assertEquals(relationText, r.getType()); } catch (Exception e) { fail(e.toString()); } } private IssueRelation createTwoRelatedIssues() throws RedmineException { List<Issue> issues = createIssues(issueManager, projectKey, 2); Issue src = issues.get(0); Issue target = issues.get(1); String relationText = IssueRelation.TYPE.precedes.toString(); return issueManager.createRelation(src.getId(), target.getId(), relationText); } @Test public void issueRelationsAreCreatedAndLoadedOK() { try { IssueRelation relation = createTwoRelatedIssues(); Issue issue = issueManager.getIssueById(relation.getIssueId(), Include.relations); Issue issueTarget = issueManager.getIssueById(relation.getIssueToId(), Include.relations); assertThat(issue.getRelations().size()).isEqualTo(1); assertThat(issueTarget.getRelations().size()).isEqualTo(1); IssueRelation relation1 = issue.getRelations().iterator().next(); assertEquals(issue.getId(), relation1.getIssueId()); assertEquals(issueTarget.getId(), relation1.getIssueToId()); assertEquals("precedes", relation1.getType()); assertEquals((Integer) 0, relation1.getDelay()); IssueRelation reverseRelation = issueTarget.getRelations().iterator().next(); // both forward and reverse relations are the same! assertEquals(relation1, reverseRelation); } catch (Exception e) { fail(e.toString()); } } @Test public void testIssureRelationDelete() throws RedmineException { IssueRelation relation = createTwoRelatedIssues(); issueManager.deleteRelation(relation.getId()); Issue issue = issueManager .getIssueById(relation.getIssueId(), Include.relations); assertTrue(issue.getRelations().isEmpty()); } @Test public void testIssueRelationsDelete() throws RedmineException { List<Issue> issues = createIssues(issueManager, projectKey, 3); Issue src = issues.get(0); Issue target = issues.get(1); String relationText = IssueRelation.TYPE.precedes.toString(); issueManager.createRelation(src.getId(), target.getId(), relationText); target = issues.get(2); issueManager.createRelation(src.getId(), target.getId(), relationText); src = issueManager.getIssueById(src.getId(), Include.relations); issueManager.deleteIssueRelations(src); Issue issue = issueManager.getIssueById(src.getId(), Include.relations); assertTrue(issue.getRelations().isEmpty()); } /** * Requires Redmine 2.3 */ @Test public void testAddIssueWatcher() throws RedmineException { final Issue issue = createIssues(issueManager, projectKey, 1).get(0); final Issue retrievedIssue = issueManager.getIssueById(issue.getId()); assertEquals(issue, retrievedIssue); final User newUser = userManager.createUser(UserGenerator.generateRandomUser()); try { Watcher watcher = WatcherFactory.create(newUser.getId()); issueManager.addWatcherToIssue(watcher, issue); } finally { userManager.deleteUser(newUser.getId()); } issueManager.getIssueById(issue.getId()); } /** * Requires Redmine 2.3 */ @Test public void testDeleteIssueWatcher() throws RedmineException { final Issue issue = createIssues(issueManager, projectKey, 1).get(0); final Issue retrievedIssue = issueManager.getIssueById(issue.getId()); assertEquals(issue, retrievedIssue); final User newUser = userManager.createUser(UserGenerator.generateRandomUser()); try { Watcher watcher = WatcherFactory.create(newUser.getId()); issueManager.addWatcherToIssue(watcher, issue); issueManager.deleteWatcherFromIssue(watcher, issue); } finally { userManager.deleteUser(newUser.getId()); } issueManager.deleteIssue(issue.getId()); } /** * Requires Redmine 2.3 */ @Test public void testGetIssueWatcher() throws RedmineException { final Issue issue = createIssues(issueManager, projectKey, 1).get(0); final Issue retrievedIssue = issueManager.getIssueById(issue.getId()); assertEquals(issue, retrievedIssue); final User newUser = userManager.createUser(UserGenerator.generateRandomUser()); try { Watcher watcher = WatcherFactory.create(newUser.getId()); issueManager.addWatcherToIssue(watcher, issue); final Issue includeWatcherIssue = issueManager.getIssueById(issue.getId(), Include.watchers); if (!includeWatcherIssue.getWatchers().isEmpty()) { Watcher watcher1 = includeWatcherIssue.getWatchers().iterator().next(); assertThat(watcher1.getId()).isEqualTo(newUser.getId()); } } finally { userManager.deleteUser(newUser.getId()); } issueManager.getIssueById(issue.getId()); } @Test public void testAddIssueWithWatchers() throws RedmineException { final Issue issue = IssueHelper.generateRandomIssue(); final User newUserWatcher = userManager.createUser(UserGenerator.generateRandomUser()); try { List<Watcher> watchers = new ArrayList<Watcher>(); Watcher watcher = WatcherFactory.create(newUserWatcher.getId()); watchers.add(watcher); issue.addWatchers(watchers); final Issue retrievedIssue = issueManager.createIssue(projectKey, issue); final Issue retrievedIssueWithWatchers = issueManager.getIssueById(retrievedIssue.getId(), Include.watchers); assertNotNull(retrievedIssueWithWatchers); assertNotNull(retrievedIssueWithWatchers.getWatchers()); assertEquals(watchers.size(), retrievedIssueWithWatchers.getWatchers().size()); assertEquals(watcher.getId(), retrievedIssueWithWatchers.getWatchers().iterator().next().getId()); } finally { userManager.deleteUser(newUserWatcher.getId()); } } @Test public void testGetIssuesBySummary() { String summary = "issue with subject ABC"; try { Issue issue = IssueFactory.createWithSubject(summary); User assignee = IntegrationTestHelper.getOurUser(); issue.setAssignee(assignee); Issue newIssue = issueManager.createIssue(projectKey, issue); assertNotNull("Checking returned result", newIssue); assertNotNull("New issue must have some ID", newIssue.getId()); // try to find the issue List<Issue> foundIssues = issueManager.getIssuesBySummary(projectKey, summary); assertNotNull("Checking if search results is not NULL", foundIssues); assertTrue("Search results must be not empty", !(foundIssues.isEmpty())); Issue loadedIssue1 = RedmineTestUtils.findIssueInList(foundIssues, newIssue.getId()); assertNotNull(loadedIssue1); assertEquals(summary, loadedIssue1.getSubject()); } catch (Exception e) { e.printStackTrace(); fail(); } } @Test public void findByNonExistingSummaryReturnsEmptyList() { String summary = "some summary here for issue which does not exist"; try { // try to find the issue List<Issue> foundIssues = issueManager.getIssuesBySummary(projectKey, summary); assertNotNull("Search result must be not null", foundIssues); assertTrue("Search result list must be empty", foundIssues.isEmpty()); } catch (Exception e) { e.printStackTrace(); fail(); } } @Test(expected = RedmineAuthenticationException.class) public void noAPIKeyOnCreateIssueThrowsAE() throws Exception { TestConfig testConfig = new TestConfig(); RedmineManager redmineMgrEmpty = RedmineManagerFactory.createUnauthenticated(testConfig.getURI()); Issue issue = IssueFactory.createWithSubject("test zzx"); redmineMgrEmpty.getIssueManager().createIssue(projectKey, issue); } @Test(expected = RedmineAuthenticationException.class) public void wrongAPIKeyOnCreateIssueThrowsAE() throws Exception { TestConfig testConfig = new TestConfig(); RedmineManager redmineMgrInvalidKey = RedmineManagerFactory.createWithApiKey( testConfig.getURI(), "wrong_key"); Issue issue = IssueFactory.createWithSubject("test zzx"); redmineMgrInvalidKey.getIssueManager().createIssue(projectKey, issue); } @Test public void testIssueDoneRatio() { try { Issue issue = new Issue(); String subject = "Issue " + new Date(); issue.setSubject(subject); Issue createdIssue = issueManager.createIssue(projectKey, issue); assertEquals("Initial 'done ratio' must be 0", (Integer) 0, createdIssue.getDoneRatio()); Integer doneRatio = 50; createdIssue.setDoneRatio(doneRatio); issueManager.update(createdIssue); Integer issueId = createdIssue.getId(); Issue reloadedFromRedmineIssue = issueManager.getIssueById(issueId); assertEquals( "Checking if 'update issue' operation changed 'done ratio' field", doneRatio, reloadedFromRedmineIssue.getDoneRatio()); Integer invalidDoneRatio = 130; reloadedFromRedmineIssue.setDoneRatio(invalidDoneRatio); try { issueManager.update(reloadedFromRedmineIssue); } catch (RedmineProcessingException e) { assertEquals("Must be 1 error", 1, e.getErrors().size()); assertEquals("Checking error text", "% Done is not included in the list", e.getErrors() .get(0)); } Issue reloadedFromRedmineIssueUnchanged = issueManager.getIssueById(issueId); assertEquals( "'done ratio' must have remained unchanged after invalid value", doneRatio, reloadedFromRedmineIssueUnchanged.getDoneRatio()); } catch (Exception e) { fail(e.toString()); } } @Test public void testIssueNullDescriptionDoesNotEraseIt() { try { Issue issue = new Issue(); String subject = "Issue " + new Date(); String descr = "Some description"; issue.setSubject(subject); issue.setDescription(descr); Issue createdIssue = issueManager.createIssue(projectKey, issue); assertEquals("Checking description", descr, createdIssue.getDescription()); createdIssue.setDescription(null); issueManager.update(createdIssue); Integer issueId = createdIssue.getId(); Issue reloadedFromRedmineIssue = issueManager.getIssueById(issueId); assertEquals("Description must not be erased", descr, reloadedFromRedmineIssue.getDescription()); reloadedFromRedmineIssue.setDescription(""); issueManager.update(reloadedFromRedmineIssue); Issue reloadedFromRedmineIssueUnchanged = issueManager.getIssueById(issueId); assertEquals("Description must be erased", "", reloadedFromRedmineIssueUnchanged.getDescription()); } catch (Exception e) { fail(); } } @Test public void testIssueJournals() { try { // create at least 1 issue Issue issueToCreate = new Issue(); issueToCreate.setSubject("testGetIssues: " + new Date()); Issue newIssue = issueManager.createIssue(projectKey, issueToCreate); Issue loadedIssueWithJournals = issueManager.getIssueById(newIssue.getId(), Include.journals); assertTrue(loadedIssueWithJournals.getJournals().isEmpty()); String commentDescribingTheUpdate = "some comment describing the issue update"; loadedIssueWithJournals.setSubject("new subject"); loadedIssueWithJournals.setNotes(commentDescribingTheUpdate); issueManager.update(loadedIssueWithJournals); Issue loadedIssueWithJournals2 = issueManager.getIssueById(newIssue.getId(), Include.journals); assertEquals(1, loadedIssueWithJournals2.getJournals() .size()); Journal journalItem = loadedIssueWithJournals2.getJournals().iterator().next(); assertEquals(commentDescribingTheUpdate, journalItem.getNotes()); User ourUser = IntegrationTestHelper.getOurUser(); // can't compare User objects because either of them is not // completely filled assertEquals(ourUser.getId(), journalItem.getUser().getId()); assertEquals(ourUser.getFirstName(), journalItem.getUser() .getFirstName()); assertEquals(ourUser.getLastName(), journalItem.getUser() .getLastName()); assertEquals(1, journalItem.getDetails().size()); final JournalDetail journalDetail = journalItem.getDetails().get(0); assertEquals("new subject", journalDetail.getNewValue()); assertEquals("subject", journalDetail.getName()); assertEquals("attr", journalDetail.getProperty()); Issue loadedIssueWithoutJournals = issueManager.getIssueById(newIssue.getId()); assertTrue(loadedIssueWithoutJournals.getJournals().isEmpty()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void emptyDescriptionReturnedAsEmptyString() throws RedmineException { Issue issue = IssueFactory.createWithSubject("Issue " + new Date()); Issue createdIssue = issueManager.createIssue(projectKey, issue); assertEquals("Description must be an empty string, not NULL", "", createdIssue.getDescription()); } @Test public void updateIssueDescription() throws RedmineException { Issue issue = new Issue(); issue.setSubject("test123"); final Issue iss1 = issueManager.createIssue(projectKey, issue); final Issue iss2 = IssueFactory.create(iss1.getId()); iss2.setDescription("This is a test"); issueManager.update(iss2); final Issue iss3 = issueManager.getIssueById(iss2.getId()); assertEquals("test123", iss3.getSubject()); assertEquals("This is a test", iss3.getDescription()); } @Test public void updateIssueTitle() throws RedmineException { Issue issue = new Issue(); issue.setSubject("test123"); issue.setDescription("Original description"); final Issue iss1 = issueManager.createIssue(projectKey, issue); final Issue iss2 = IssueFactory.create(iss1.getId()); iss2.setSubject("New subject"); issueManager.update(iss2); final Issue iss3 = issueManager.getIssueById(iss2.getId()); assertEquals("New subject", iss3.getSubject()); assertEquals("Original description", iss3.getDescription()); } /** * Test for issue 64 (time entry format) */ @Test public void testTimeEntryComments() throws RedmineException { Issue issue = createIssues(issueManager, projectKey, 1).get(0); Integer issueId = issue.getId(); TimeEntry entry = TimeEntryFactory.create(); Float hours = 11f; entry.setHours(hours); entry.setIssueId(issueId); final String comment = "This is a comment although it may not look like it"; entry.setComment(comment); // TODO We don't know activities IDs! entry.setActivityId(ACTIVITY_ID); TimeEntry createdEntry = issueManager.createTimeEntry(entry); assertNotNull(createdEntry); assertEquals(comment, createdEntry.getComment()); createdEntry.setComment("New comment"); issueManager.update(createdEntry); final TimeEntry updatedEntry = issueManager.getTimeEntry(createdEntry.getId()); assertEquals("New comment", updatedEntry.getComment()); } @Test public void testIssuePriorities() throws RedmineException { assertTrue(issueManager.getIssuePriorities().size() > 0); } @Test public void testTimeEntryActivities() throws RedmineException { assertTrue(issueManager.getTimeEntryActivities().size() > 0); } @Test public void testGetTimeEntries() throws RedmineException { List<TimeEntry> list = issueManager.getTimeEntries(); assertNotNull(list); } @Test public void testCreateGetTimeEntry() throws RedmineException { Issue issue = createIssues(issueManager, projectKey, 1).get(0); Integer issueId = issue.getId(); TimeEntry entry = TimeEntryFactory.create(); Float hours = 11f; entry.setHours(hours); entry.setIssueId(issueId); // TODO We don't know activities IDs! entry.setActivityId(ACTIVITY_ID); TimeEntry createdEntry = issueManager.createTimeEntry(entry); assertNotNull(createdEntry); logger.debug("Created time entry " + createdEntry); assertEquals(hours, createdEntry.getHours()); Float newHours = 22f; createdEntry.setHours(newHours); issueManager.update(createdEntry); TimeEntry updatedEntry = issueManager.getTimeEntry(createdEntry.getId()); assertEquals(newHours, updatedEntry.getHours()); } @Test(expected = NotFoundException.class) public void testCreateDeleteTimeEntry() throws RedmineException { Issue issue = createIssues(issueManager, projectKey, 1).get(0); Integer issueId = issue.getId(); TimeEntry entry = TimeEntryFactory.create(); Float hours = 4f; entry.setHours(hours); entry.setIssueId(issueId); entry.setActivityId(ACTIVITY_ID); TimeEntry createdEntry = issueManager.createTimeEntry(entry); assertNotNull(createdEntry); issueManager.deleteTimeEntry(createdEntry.getId()); issueManager.getTimeEntry(createdEntry.getId()); } @Test public void testGetTimeEntriesForIssue() throws RedmineException { Issue issue = createIssues(issueManager, projectKey, 1).get(0); Integer issueId = issue.getId(); Float hours1 = 2f; Float hours2 = 7f; Float totalHoursExpected = hours1 + hours2; TimeEntry createdEntry1 = createTimeEntry(issueId, hours1); TimeEntry createdEntry2 = createTimeEntry(issueId, hours2); assertNotNull(createdEntry1); assertNotNull(createdEntry2); List<TimeEntry> entries = issueManager.getTimeEntriesForIssue(issueId); assertEquals(2, entries.size()); Float totalTime = 0f; for (TimeEntry timeEntry : entries) { totalTime += timeEntry.getHours(); } assertEquals(totalHoursExpected, totalTime); } private TimeEntry createTimeEntry(Integer issueId, float hours) throws RedmineException { TimeEntry entry = TimeEntryFactory.create(); entry.setHours(hours); entry.setIssueId(issueId); entry.setActivityId(ACTIVITY_ID); return issueManager.createTimeEntry(entry); } @Ignore @Test public void issueFixVersionIsSet() throws Exception { String existingProjectKey = "test"; Issue toCreate = IssueHelper.generateRandomIssue(); Version v = VersionFactory.create(1); String versionName = "1.0"; v.setName("1.0"); v.setProject(mgr.getProjectManager().getProjectByKey(projectKey)); v = mgr.getProjectManager().createVersion(v); toCreate.setTargetVersion(v); Issue createdIssue = issueManager.createIssue(existingProjectKey, toCreate); assertNotNull(createdIssue.getTargetVersion()); assertEquals(createdIssue.getTargetVersion().getName(), versionName); } /** * Not supported by Redmine REST API. */ @Ignore @Test public void testSpentTimeFieldLoaded() { try { Issue issue = new Issue(); String subject = "Issue " + new Date(); issue.setSubject(subject); float spentHours = 2; issue.setSpentHours(spentHours); Issue createdIssue = issueManager.createIssue(projectKey, issue); Issue newIssue = issueManager.getIssueById(createdIssue.getId()); assertEquals((Float) spentHours, newIssue.getSpentHours()); } catch (Exception e) { fail(); } } @Test(expected = IllegalArgumentException.class) public void invalidTimeEntryFailsWithIAEOnCreate() throws RedmineException { issueManager.createTimeEntry(createIncompleteTimeEntry()); } @Test(expected = IllegalArgumentException.class) public void invalidTimeEntryFailsWithIAEOnUpdate() throws RedmineException { issueManager.update(createIncompleteTimeEntry()); } private TimeEntry createIncompleteTimeEntry() { TimeEntry timeEntry = TimeEntryFactory.create(); timeEntry.setActivityId(ACTIVITY_ID); timeEntry.setSpentOn(new Date()); timeEntry.setHours(1.5f); return timeEntry; } @Test public void testViolateTimeEntryConstraint_ProjectOrIssueID_issue66() throws RedmineException { TimeEntry timeEntry = createIncompleteTimeEntry(); // Now can try to verify with project ID (only test with issue ID seems // to be already covered) int projectId = mgr.getProjectManager().getProjects().get(0).getId(); timeEntry.setProjectId(projectId); try { TimeEntry created = issueManager.createTimeEntry(timeEntry); logger.debug("Created time entry " + created); } catch (Exception e) { e.printStackTrace(); fail("Unexpected " + e.getClass().getSimpleName() + ": " + e.getMessage()); } } @Test public void testUpdateIssueDoesNotChangeEstimatedTime() { try { Issue issue = new Issue(); String originalSubject = "Issue " + new Date(); issue.setSubject(originalSubject); Issue newIssue = issueManager.createIssue(projectKey, issue); assertEquals("Estimated hours must be NULL", null, newIssue.getEstimatedHours()); issueManager.update(newIssue); Issue reloadedFromRedmineIssue = issueManager.getIssueById(newIssue.getId()); assertEquals("Estimated hours must be NULL", null, reloadedFromRedmineIssue.getEstimatedHours()); } catch (Exception e) { fail(); } } /** * tests the retrieval of statuses. * * @throws RedmineProcessingException thrown in case something went wrong in Redmine * @throws java.io.IOException thrown in case something went wrong while performing I/O * operations * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test public void testGetStatuses() throws RedmineException { // TODO we should create some statuses first, but the Redmine Java API // does not support this presently List<IssueStatus> statuses = issueManager.getStatuses(); assertFalse("Expected list of statuses not to be empty", statuses.isEmpty()); for (IssueStatus issueStatus : statuses) { // asserts on status assertNotNull("ID of status must not be null", issueStatus.getId()); assertNotNull("Name of status must not be null", issueStatus.getName()); } } /** * tests the creation and deletion of a {@link com.taskadapter.redmineapi.bean.IssueCategory}. * * @throws RedmineException thrown in case something went wrong in Redmine * @throws java.io.IOException thrown in case something went wrong while performing I/O * operations * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test public void testCreateAndDeleteIssueCategory() throws RedmineException { Project project = projectManager.getProjectByKey(projectKey); IssueCategory category = IssueCategoryFactory.create(project, "Category" + new Date().getTime()); category.setAssignee(IntegrationTestHelper.getOurUser()); IssueCategory newIssueCategory = issueManager.createCategory(category); assertNotNull("Expected new category not to be null", newIssueCategory); assertNotNull("Expected project of new category not to be null", newIssueCategory.getProject()); assertNotNull("Expected assignee of new category not to be null", newIssueCategory.getAssignee()); // now delete category issueManager.deleteCategory(newIssueCategory); // assert that the category is gone List<IssueCategory> categories = issueManager.getCategories(project.getId()); assertTrue( "List of categories of test project must be empty now but is " + categories, categories.isEmpty()); } /** * tests the retrieval of {@link IssueCategory}s. * * @throws RedmineException thrown in case something went wrong in Redmine * @throws java.io.IOException thrown in case something went wrong while performing I/O * operations * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test public void testGetIssueCategories() throws RedmineException { Project project = projectManager.getProjectByKey(projectKey); // create some categories IssueCategory testIssueCategory1 = IssueCategoryFactory.create(project, "Category" + new Date().getTime()); testIssueCategory1.setAssignee(IntegrationTestHelper.getOurUser()); IssueCategory newIssueCategory1 = issueManager.createCategory(testIssueCategory1); IssueCategory testIssueCategory2 = IssueCategoryFactory.create(project, "Category" + new Date().getTime()); testIssueCategory2.setAssignee(IntegrationTestHelper.getOurUser()); IssueCategory newIssueCategory2 = issueManager.createCategory(testIssueCategory2); try { List<IssueCategory> categories = issueManager.getCategories(project.getId()); assertEquals("Wrong number of categories for project " + project.getName() + " delivered by Redmine Java API", 2, categories.size()); for (IssueCategory category : categories) { // assert category assertNotNull("ID of category must not be null", category.getId()); assertNotNull("Name of category must not be null", category.getName()); assertNotNull("Project of category must not be null", category.getProject()); assertNotNull("Assignee of category must not be null", category.getAssignee()); } } finally { // scrub test categories if (newIssueCategory1 != null) { issueManager.deleteCategory(newIssueCategory1); } if (newIssueCategory2 != null) { issueManager.deleteCategory(newIssueCategory2); } } } /** * tests the creation of an invalid {@link IssueCategory}. * * @throws RedmineException thrown in case something went wrong in Redmine * @throws java.io.IOException thrown in case something went wrong while performing I/O * operations * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test(expected = IllegalArgumentException.class) public void testCreateInvalidIssueCategory() throws RedmineException { IssueCategory category = IssueCategoryFactory.create(null, "InvalidCategory" + new Date().getTime()); issueManager.createCategory(category); } /** * tests the deletion of an invalid {@link IssueCategory}. Expects a * {@link NotFoundException} to be thrown. * * @throws RedmineException thrown in case something went wrong in Redmine * @throws java.io.IOException thrown in case something went wrong while performing I/O * operations * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test(expected = NotFoundException.class) public void testDeleteInvalidIssueCategory() throws RedmineException { // create new test category IssueCategory category = IssueCategoryFactory.create(-1); category.setName("InvalidCategory" + new Date().getTime()); // now try deleting the category issueManager.deleteCategory(category); } /** * Tests the creation and retrieval of an * {@link com.taskadapter.redmineapi.bean.Issue} with a * {@link IssueCategory}. * * @throws RedmineException thrown in case something went wrong in Redmine * @throws java.io.IOException thrown in case something went wrong while performing I/O * operations * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test public void testCreateAndGetIssueWithCategory() throws RedmineException { IssueCategory newIssueCategory = null; Issue newIssue = null; try { Project project = projectManager.getProjectByKey(projectKey); // create an issue category IssueCategory category = IssueCategoryFactory.create(project, "Category_" + new Date().getTime()); category.setAssignee(IntegrationTestHelper.getOurUser()); newIssueCategory = issueManager.createCategory(category); // create an issue Issue issueToCreate = IssueFactory.createWithSubject("getIssueWithCategory_" + UUID.randomUUID()); issueToCreate.setCategory(newIssueCategory); newIssue = issueManager.createIssue(projectKey, issueToCreate); // retrieve issue Issue retrievedIssue = issueManager.getIssueById(newIssue.getId()); // assert retrieved category of issue IssueCategory retrievedCategory = retrievedIssue.getCategory(); assertNotNull("Category retrieved for issue " + newIssue.getId() + " should not be null", retrievedCategory); assertEquals("ID of category retrieved for issue " + newIssue.getId() + " is wrong", newIssueCategory.getId(), retrievedCategory.getId()); assertEquals("Name of category retrieved for issue " + newIssue.getId() + " is wrong", newIssueCategory.getName(), retrievedCategory.getName()); } finally { if (newIssue != null) { issueManager.deleteIssue(newIssue.getId()); } if (newIssueCategory != null) { issueManager.deleteCategory(newIssueCategory); } } } @Test public void nullStartDateIsPreserved() { try { Issue issue = IssueFactory.createWithSubject("test start date"); issue.setStartDate(null); Issue newIssue = issueManager.createIssue(projectKey, issue); Issue loadedIssue = issueManager.getIssueById(newIssue.getId()); assertNull(loadedIssue.getStartDate()); } catch (Exception e) { e.printStackTrace(); fail(); } } @Test public void testCustomFields() throws Exception { Issue issue = createIssues(issueManager, projectKey, 1).get(0); // default empty values assertThat(issue.getCustomFields().size()).isEqualTo(2); // TODO update this! int id1 = 1; // TODO this is pretty much a hack, we don't generally know // these ids! String custom1FieldName = "my_custom_1"; String custom1Value = "some value 123"; int id2 = 2; String custom2FieldName = "custom_boolean_1"; String custom2Value = "true"; issue.clearCustomFields(); issue.addCustomField(CustomFieldFactory.create(id1, custom1FieldName, custom1Value)); issue.addCustomField(CustomFieldFactory.create(id2, custom2FieldName, custom2Value)); issueManager.update(issue); Issue updatedIssue = issueManager.getIssueById(issue.getId()); assertThat(updatedIssue.getCustomFields().size()).isEqualTo(2); assertEquals(custom1Value, updatedIssue.getCustomField(custom1FieldName)); assertEquals(custom2Value, updatedIssue.getCustomField(custom2FieldName)); } @Ignore @Test public void testChangesets() throws RedmineException { final Issue issue = issueManager.getIssueById(89, Include.changesets); assertThat(issue.getChangesets().size()).isEqualTo(2); final Changeset firstChange = issue.getChangesets().iterator().next(); assertNotNull(firstChange.getComments()); } /** * Tests the retrieval of {@link Tracker}s. * * @throws RedmineException thrown in case something went wrong in Redmine * @throws RedmineAuthenticationException thrown in case something went wrong while trying to login * @throws NotFoundException thrown in case the objects requested for could not be found */ @Test public void testGetTrackers() throws RedmineException { List<Tracker> trackers = issueManager.getTrackers(); assertNotNull("List of trackers returned should not be null", trackers); assertFalse("List of trackers returned should not be empty", trackers.isEmpty()); for (Tracker tracker : trackers) { assertNotNull("Tracker returned should not be null", tracker); assertNotNull("ID of tracker returned should not be null", tracker.getId()); assertNotNull("Name of tracker returned should not be null", tracker.getName()); } } @Test public void getSavedQueriesDoesNotFailForTempProject() throws RedmineException { issueManager.getSavedQueries(projectKey); } @Test public void getSavedQueriesDoesNotFailForNULLProject() throws RedmineException { issueManager.getSavedQueries(null); } @Ignore("This test requires a specific project configuration") @Test public void testSavedQueries() throws RedmineException { final Collection<SavedQuery> queries = issueManager.getSavedQueries("test"); assertTrue(queries.size() > 0); } @Test public void statusIsUpdated() throws RedmineException { Issue issue = createIssues(issueManager, projectKey, 1).get(0); Issue retrievedIssue = issueManager.getIssueById(issue.getId()); Integer initialStatusId = retrievedIssue.getStatusId(); List<IssueStatus> statuses = issueManager.getStatuses(); // get some status ID that is not equal to the initial one Integer newStatusId = null; for (IssueStatus status : statuses) { if (!status.getId().equals(initialStatusId)) { newStatusId = status.getId(); break; } } if (newStatusId == null) { throw new RuntimeException("can't run this test: no Issue Statuses are available except for the initial one"); } retrievedIssue.setStatusId(newStatusId); issueManager.update(retrievedIssue); Issue issueWithUpdatedStatus = issueManager.getIssueById(retrievedIssue.getId()); assertThat(issueWithUpdatedStatus.getStatusId()).isEqualTo(newStatusId); } }
package com.voodoodyne.jackson.jsog; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import com.fasterxml.jackson.databind.ObjectMapper; import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; public class PolymorphicTest { @JsonIdentityInfo(generator=JSOGGenerator.class) @JsonTypeInfo(use=Id.CLASS, include=As.PROPERTY, property="@class") public static class Inner { public String bar; public Inner() {} public Inner(String bar) { this.bar = bar; } } public static class SubInner extends Inner { public String extra; public SubInner() {} public SubInner(String bar, String extra) { super(bar); this.extra = extra; } } @JsonIdentityInfo(generator=JSOGGenerator.class) public static class Outer { public String foo; public Inner inner1; public Inner inner2; } /** Expected output */ private static final String JSOGIFIED = "{\"@id\":\"1\",\"foo\":\"foo\",\"inner1\":{\"@class\":\"com.voodoodyne.jackson.jsog.PolymorphicTest$SubInner\",\"@id\":\"2\",\"bar\":\"bar\",\"extra\":\"extra\"},\"inner2\":{\"@ref\":\"2\"}}"; ObjectMapper mapper = new ObjectMapper(); @Test public void serializationWorks() throws Exception { Outer outer = new Outer(); outer.foo = "foo"; outer.inner1 = outer.inner2 = new SubInner("bar", "extra"); String jsog = mapper.writeValueAsString(outer); System.out.println("Serialized to: " + jsog); assertThat(jsog, equalTo(JSOGIFIED)); } //@Test public void deserializationWorks() throws Exception { Outer outer = mapper.readValue(JSOGIFIED, Outer.class); assert outer.inner1 == outer.inner2; } }
package de.vogel612.helper.ui; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import java.nio.file.Path; import java.util.List; import org.junit.Before; import org.junit.Test; import de.vogel612.helper.data.Translation; import de.vogel612.helper.ui.impl.OverviewPresenterImpl; public class OverviewPresenterTest { OverviewView v; OverviewModel m; TranslationPresenter p; OverviewPresenter cut; @Before public void beforeTest() { v = mock(OverviewView.class); m = mock(OverviewModel.class); p = mock(TranslationPresenter.class); cut = new OverviewPresenterImpl(m, v, p); reset(v, m, p); } @Test public void initialize_registersPresenter() { cut.initialize(); verify(v).register(cut); verify(m).register(cut); verify(p).register(cut); verifyNoMoreInteractions(m, v, p); } @Test public void initialize_registersPresenter_onlyOnce() { cut.initialize(); reset(m, v, p); cut.initialize(); verifyNoMoreInteractions(m, v, p); } @Test public void show_callsInitialize_ifNotInitialized() { cut.show(); verify(v).show(); verify(v).register(cut); verify(m).register(cut); verify(p).register(cut); verifyNoMoreInteractions(m, v, p); } @Test public void show_callsShow_onView() { cut.initialize(); reset(m, v, p); cut.show(); verify(v).show(); verifyNoMoreInteractions(m, v, p); } @Test public void loadFromFile_delegatesToModel() { Path mock = mock(Path.class); cut.loadFiles(mock, OverviewPresenter.DEFAULT_ROOT_LOCALE, OverviewPresenter.DEFAULT_TARGET_LOCALE); verify(m).loadFromDirectory(mock, "de"); verifyNoMoreInteractions(m, v, p); } @Test public void onException_delegatesToView() { final Exception e = mock(Exception.class); final String message = "testingmessage"; final String errorMessage = "alsdkj"; doReturn(errorMessage).when(e).getMessage(); cut.onException(e, message); verify(v).showError(message, errorMessage); verify(e).getMessage(); verifyNoMoreInteractions(m, v, p); } @Test public void onParseCompletion_rebuildsView() { List<Translation> list = mock(List.class); doReturn(list).when(m).getTranslations(); cut.onParseCompletion(); verify(m).getTranslations(); verify(v).rebuildWith(list); verifyNoMoreInteractions(m, v, p); } @Test public void onTranslateRequest_delegatesToTranslationPresenter() { final String key = "Key"; Translation fake = mock(Translation.class); doReturn(fake).when(m).getSingleTranslation(key); cut.onTranslateRequest(key); verify(m).getSingleTranslation(key); verify(p).setRequestedTranslation(fake); verify(p).show(); verifyNoMoreInteractions(m, v, p); } @Test public void onTranslationSubmit_hidesTranslationView_propagatesEdit_updatesView() { final Translation t = new Translation("Key", "Value", "Translation"); final List<Translation> list = mock(List.class); doReturn(list).when(m).getTranslations(); cut.onTranslationSubmit(t); verify(m).updateTranslation("Key", "Translation"); verify(m).getTranslations(); verify(v).rebuildWith(list); verify(p).hide(); verifyNoMoreInteractions(m, v, p); } @Test public void onTranslationAbort_hidesTranslationView() { cut.onTranslationAbort(); verify(p).hide(); verifyNoMoreInteractions(m, v, p); } }
package de.vorb.platon.web.rest; import de.vorb.platon.model.Comment; import de.vorb.platon.model.CommentThread; import de.vorb.platon.persistence.CommentRepository; import de.vorb.platon.persistence.CommentThreadRepository; import de.vorb.platon.security.RequestVerifier; import com.google.common.truth.Truth; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import javax.ws.rs.BadRequestException; import javax.ws.rs.NotFoundException; import java.util.List; import java.util.Random; @RunWith(MockitoJUnitRunner.class) public class CommentResourceTest { private static final CommentThread emptyThread = new CommentThread("http://example.com/article", "An empty comment thread"); private static final CommentThread nonEmptyThread = new CommentThread("http://example.com/article-with-comments", "An non-empty comment thread"); static { final Comment comment = new Comment(nonEmptyThread, null, "Text", "Author", null, null); comment.setId(4711L); nonEmptyThread.getComments().add(comment); } @Mock private CommentRepository commentRepository; @Mock private CommentThreadRepository threadRepository; @Mock private RequestVerifier requestVerifier; @InjectMocks private CommentResource commentResource; @Before public void setUp() throws Exception { Mockito.when(threadRepository.getByUrl(Mockito.eq(null))).thenReturn(null); Mockito.when(threadRepository.getByUrl(Mockito.eq(emptyThread.getUrl()))).thenReturn(emptyThread); Mockito.when(threadRepository.getByUrl(Mockito.eq(nonEmptyThread.getUrl()))).thenReturn(nonEmptyThread); final Random rng = new Random(); Mockito.when(commentRepository.save(Mockito.any(Comment.class))).then(invocation -> { final Comment comment = invocation.getArgumentAt(0, Comment.class); comment.setId(rng.nextLong()); return comment; }); Mockito.when(commentRepository.findByThread(nonEmptyThread)).thenReturn(nonEmptyThread.getComments()); Mockito.when(requestVerifier.getSignatureToken(Mockito.any(), Mockito.any())).thenReturn(new byte[0]); Mockito.when(requestVerifier.isRequestValid(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(true); } @Test(expected = NotFoundException.class) public void testGetCommentsByThreadUrlNull() throws Exception { commentResource.findCommentsByThreadUrl(null); } @Test public void testGetCommentsByThreadUrlEmptyThread() throws Exception { Truth.assertThat(commentResource.findCommentsByThreadUrl(emptyThread.getUrl())).isEmpty(); } @Test public void testGetCommentsByThreadUrlNonEmptyThread() throws Exception { final List<Comment> comments = commentResource.findCommentsByThreadUrl(nonEmptyThread.getUrl()); Truth.assertThat(comments).isNotEmpty(); } @Test public void testPostCommentToExistingThread() throws Exception { final Comment newComment = Mockito.spy(new Comment(nonEmptyThread, null, "Text", "Author", null, null)); commentResource.postComment(nonEmptyThread.getUrl(), nonEmptyThread.getTitle(), newComment); Mockito.verify(commentRepository).save(Mockito.same(newComment)); } @Test public void testPostCommentToNewThread() throws Exception { final String threadUrl = "http://example.com/new-article"; final String threadTitle = "New article"; final Comment newComment = Mockito.spy(new Comment(null, null, "Text", "Author", null, null)); commentResource.postComment(threadUrl, threadTitle, newComment); final ArgumentCaptor<CommentThread> threadCaptor = ArgumentCaptor.forClass(CommentThread.class); Mockito.verify(threadRepository).save(threadCaptor.capture()); Truth.assertThat(threadCaptor.getValue().getUrl()).isEqualTo(threadUrl); Truth.assertThat(threadCaptor.getValue().getTitle()).isEqualTo(threadTitle); Mockito.verify(commentRepository).save(Mockito.same(newComment)); } @Test(expected = BadRequestException.class) public void testUpdateNonExistingComment() throws Exception { final Comment newComment = new Comment(null, null, "Text", "Author", null, null); newComment.setId(42L); commentResource.updateComment(newComment.getId(), newComment); Mockito.verifyZeroInteractions(threadRepository, commentRepository); } }
package nablarch.core.dataformat; import static org.junit.Assert.assertThat; import static org.xmlunit.matchers.CompareMatcher.isIdenticalTo; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.math.BigDecimal; import java.util.HashMap; import nablarch.core.repository.SystemRepository; import nablarch.core.repository.di.DiContainer; import nablarch.core.repository.di.config.xml.XmlComponentDefinitionLoader; import nablarch.core.util.FilePathSetting; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.rules.TestName; /** * {@link XmlDataParser} * * @author TIS */ public class XmlDataBuilderTest { @Rule public TestName testNameRule = new TestName(); @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Rule public ExpectedException expectedException = ExpectedException.none(); private StructuredDataBuilder sut = new XmlDataBuilder(); @Before public void setUp() { SystemRepository.clear(); SystemRepository.load( new DiContainer( new XmlComponentDefinitionLoader( "nablarch/core/dataformat/XmlBuilder.xml"))); } /** * * * @return */ private String getFormatFileName() { FilePathSetting fps = FilePathSetting.getInstance() .addBasePathSetting("format", temporaryFolder.getRoot() .toURI() .toString()) .addFileExtensions("fortmat", "fmt"); return fps.getBasePathSettings() .get("format") .getPath() + '/' + testNameRule.getMethodName() + ".fmt"; } /** * * * @return */ private LayoutDefinition getLayoutDefinition() { LayoutDefinition ld = new LayoutFileParser(getFormatFileName()).parse(); DataRecordFormatter formatter = new XmlDataRecordFormatter(); formatter.setDefinition(ld); formatter.initialize(); return ld; } private void createFormatFile(String charset, String... lines) throws Exception { final BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(getFormatFileName()), "utf-8")); writer.append("file-type: \"XML\""); writer.newLine(); writer.append("text-encoding: \"") .append(charset) .append("\""); writer.newLine(); for (final String line : lines) { writer.append(line); writer.newLine(); } writer.flush(); writer.close(); } @Test public void XML() throws Exception { createFormatFile( "UTF-8", "[data]", "1 child [0..1] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\"?><data></data>")); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[data]", "1 @name X", "2 @age [0..1] X9" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("name", ""); input.put("age", 50); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\"?><data name=\"\" age=\"50\"></data>")); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[data]", "1 @name X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); expectedException.expect(InvalidDataFormatException.class); expectedException.expectMessage("name is required"); sut.buildData(input, getLayoutDefinition(), actual); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[data]", "1 @name X", "2 @age [0..1] X9" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("name", ""); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\"?><data name=\"\"></data>")); } @Test @Ignore(":") public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 content X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("content", ""); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<root></root>")); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 child1 X", "2 child2 [0..1] X9" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("child1", ""); input.put("child2", 100); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root>\n" + " <child1></child1>\n" + " <child2>100</child2>\n" + "</root>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 child1 X", "2 child2 [0..1] X9" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("child1", ""); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root>\n" + " <child1></child1>\n" + "</root>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 child1 X", "2 child2 [0..1] X9" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("child2", 99); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); expectedException.expect(InvalidDataFormatException.class); expectedException.expectMessage("child1 is required"); sut.buildData(input, getLayoutDefinition(), actual); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 @name X", "2 child X9" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("name", ""); input.put("child", 99); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root name=\"\">\n" + " <child>99</child>\n" + "</root>\n").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 @name [0..1] X", "2 child [0..1] X9" ); final HashMap<String, Object> input = new HashMap<String, Object>(); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root>\n" + "</root>\n").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 child [0..1] OB", "", "[child]", "1 @attr X", "2 @any [0..1] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("child.attr", ""); input.put("child.any", ""); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root>\n" + " <child attr=\"\" any=''></child>\n" + "</root>\n").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 child [0..1] OB", "", "[child]", "1 @attr X", "2 @any [0..1] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("child.attr", ""); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root>\n" + " <child attr=\"\"></child>\n" + "</root>\n").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 child [0..1] OB", "", "[child]", "1 @attr X", "2 @any [0..1] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("child.any", ""); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); expectedException.expect(InvalidDataFormatException.class); expectedException.expectMessage("attr is required"); sut.buildData(input, getLayoutDefinition(), actual); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 child OB", "", "[child]", "1 content1 X", "2 content2 [0..1] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("child.content1", ""); input.put("child.content2", ""); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root>\n" + " <child>\n" + " <content1></content1>\n" + " <content2></content2>\n" + " </child>\n" + "</root>\n").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 child OB", "", "[child]", "1 content1 X", "2 content2 [0..1] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("child.content1", ""); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root>\n" + " <child>\n" + " <content1></content1>\n" + " </child>\n" + "</root>\n").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 child OB", "", "[child]", "1 content1 [0..1] X", "2 content2 [0..1] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("dummy.data", ""); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); expectedException.expect(InvalidDataFormatException.class); expectedException.expectMessage("child is required"); sut.buildData(input, getLayoutDefinition(), actual); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 child OB", "", "[child]", "1 content1 X", "2 content2 [0..1] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("child.content2", ""); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); expectedException.expect(InvalidDataFormatException.class); expectedException.expectMessage("content1 is required"); sut.buildData(input, getLayoutDefinition(), actual); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 child OB", "", "[child]", "1 @attr X", "2 @any [0..1] X", "3 content X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("child.attr", ""); input.put("child.any", ""); input.put("child.content", ""); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root>\n" + " <child attr='' any=''>\n" + " <content></content>\n" + " </child>\n" + "</root>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 child OB", "", "[child]", "1 @attr X", "2 @any [0..1] X", "3 content X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("child.attr", ""); input.put("child.content", ""); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root>\n" + " <child attr=''>\n" + " <content></content>\n" + " </child>\n" + "</root>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 child OB", "", "[child]", "1 @attr X", "2 @any [0..1] X", "3 content X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("child.any", ""); input.put("child.content", ""); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); expectedException.expect(InvalidDataFormatException.class); expectedException.expectMessage("attr is required"); sut.buildData(input, getLayoutDefinition(), actual); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[parent]", "1 children [1..*] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("children", new String[] {"", ""}); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<parent>\n" + " <children></children>\n" + " <children></children>\n" + "</parent>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[parent]", "1 children [0..2] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("children", new String[] {"", ""}); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<parent>\n" + " <children></children>\n" + " <children></children>\n" + "</parent>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[parent]", "1 children [0..2] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("children", new String[] {}); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<parent>\n" + "</parent>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[parent]", "1 children [0..2] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<parent>\n" + "</parent>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[parent]", "1 children [1..2] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); expectedException.expect(InvalidDataFormatException.class); expectedException.expectMessage("children is required"); sut.buildData(input, getLayoutDefinition(), actual); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[parent]", "1 children [0..2] OB", "[children]", "1 @name X", "2 @age [0..1] X9" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("children[0].name", ""); input.put("children[0].age", "20"); input.put("children[1].name", ""); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<parent>\n" + " <children name='' age='20'></children>\n" + " <children name=''></children>\n" + "</parent>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[parent]", "1 children [0..2] OB", "[children]", "1 @name X", "2 @age [0..1] X9" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("children[0].age", "20"); input.put("children[1].name", ""); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); expectedException.expect(InvalidDataFormatException.class); expectedException.expectMessage("name is required"); sut.buildData(input, getLayoutDefinition(), actual); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[parent]", "1 child [1..10]OB", "[child]", "1 name X", "2 age [0..1] X9" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("child[0].name", ""); input.put("child[0].age", 30); input.put("child[1].name", ""); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<parent>\n" + " <child>\n" + " <name></name>\n" + " <age>30</age>\n" + " </child>\n" + " <child>\n" + " <name></name>\n" + " </child>\n" + "</parent>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[parent]", "1 child [1..10]OB", "[child]", "1 name X", "2 age [0..1] X9" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("child[0].age", 30); input.put("child[1].name", ""); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); expectedException.expect(InvalidDataFormatException.class); expectedException.expectMessage("name is required"); sut.buildData(input, getLayoutDefinition(), actual); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[parent]", "1 @attr X", "2 child [1..10] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("attr", ""); input.put("child", new String[] {"", ""}); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<parent attr=''>\n" + " <child></child>\n" + " <child></child>\n" + "</parent>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[parent]", "1 @attr X", "2 child [0..10] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("attr", ""); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<parent attr=''>\n" + "</parent>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[parent]", "1 @attr X", "2 child [1..10] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("attr", ""); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); expectedException.expect(InvalidDataFormatException.class); expectedException.expectMessage("child is required"); sut.buildData(input, getLayoutDefinition(), actual); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[parent]", "1 size X9", "2 child [1..10] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("size", 3); input.put("child", new String[] {"1", "2", "3"}); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<parent>\n" + " <size>3</size>\n" + " <child>1</child>\n" + " <child>2</child>\n" + " <child>3</child>\n" + "</parent>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[parent]", "1 size X9", "2 child [0..10] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("size", 3); input.put("child", new String[] {"1", "2", "3"}); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<parent>\n" + " <size>3</size>\n" + " <child>1</child>\n" + " <child>2</child>\n" + " <child>3</child>\n" + "</parent>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[parent]", "1 size X9", "2 child [0..10] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("size", 0); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<parent>\n" + " <size>0</size>\n" + "</parent>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[parent]", "1 size X9", "2 child [1..10] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("size", 0); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); expectedException.expect(InvalidDataFormatException.class); expectedException.expectMessage("child is required"); sut.buildData(input, getLayoutDefinition(), actual); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[parent]", "1 children [1..*] OB", "[children]", "1 data X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("children[0].data", "1"); input.put("children[1].data", "2"); input.put("children[2].data", "3"); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<parent>\n" + " <children><data>1</data></children>\n" + " <children><data>2</data></children>\n" + " <children><data>3</data></children>\n" + "</parent>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[parent]", "1 children [1..*] OB", "[children]", "1 data [0..1] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("children[0].data", 1); input.put("children[1].data", 2); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<parent>\n" + " <children><data>1</data></children>\n" + " <children><data>2</data></children>\n" + "</parent>").ignoreWhitespace()); } @Test @Ignore("") public void () throws Exception { createFormatFile( "UTF-8", "[parent]", "1 children [1..*] OB", "[children]", "1 data [0..1] X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("children[0]", ""); input.put("children[1]", ""); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<parent>\n" + " <children></children>\n" + " <children></children>\n" + "</parent>").ignoreWhitespace()); } @Test @Ignore("") public void () throws Exception { createFormatFile( "UTF-8", "[parent]", "1 children [1..*] OB", "[children]", "1 data X" ); final HashMap<String, Object> input = new HashMap<String, Object>(); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); expectedException.expect(InvalidDataFormatException.class); expectedException.expectMessage("data is required"); sut.buildData(input, getLayoutDefinition(), actual); } @Test public void null() throws Exception { createFormatFile( "UTF-8", "[root]", "1 data [0..1] OB", "[data]", "1 name X" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(null, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root></root>").ignoreWhitespace()); } @Test public void null() throws Exception { createFormatFile( "UTF-8", "[root]", "1 data [0..1] X" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(null, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root></root>").ignoreWhitespace()); } @Test public void null() throws Exception { createFormatFile( "UTF-8", "[root]", "1 data [0..*] X" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(null, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root></root>").ignoreWhitespace()); } @Test public void null() throws Exception { createFormatFile( "UTF-8", "[root]", "1 data [0..*] X", "[data]", "1 name X" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(null, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root></root>").ignoreWhitespace()); } @Test public void Map() throws Exception { createFormatFile( "UTF-8", "[root]", "1 data [0..1] X" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); sut.buildData(new HashMap<String, Object>(), getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root></root>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 data X" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("data", ""); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root><data /></root>").ignoreWhitespace()); } @Test public void null() throws Exception { createFormatFile( "UTF-8", "[root]", "1 data X" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("data", null); expectedException.expect(InvalidDataFormatException.class); expectedException.expectMessage("data is required"); sut.buildData(input, getLayoutDefinition(), actual); } @Test public void null() throws Exception { createFormatFile( "UTF-8", "[root]", "1 data [0..1] X" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("data", null); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root><data /></root>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 data [0..2] X" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("data", new String[] {"1" ,"2", "3"}); expectedException.expect(InvalidDataFormatException.class); expectedException.expectMessage("FieldName=data:MinCount=0:MaxCount=2:Actual=3"); sut.buildData(input, getLayoutDefinition(), actual); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 data [0..2] OB", "[data]", "1 name X" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); final HashMap<String, Object> input = new HashMap<String, Object>(); input.put("data[0].name", "1"); input.put("data[1].name", "2"); input.put("data[2].name", "3"); input.put("data[3].name", "4"); expectedException.expect(InvalidDataFormatException.class); expectedException.expectMessage("FieldName=data:MinCount=0:MaxCount=2:Actual=4"); sut.buildData(input, getLayoutDefinition(), actual); } @Test public void _X_N_XN() throws Exception { createFormatFile( "UTF-8", "[root]", "1 X X", "2 N N", "3 XN XN" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); final DataRecord input = new DataRecord(); input.put("X", ""); input.put("N", 100); input.put("XN", BigDecimal.ONE); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root>\n" + " <X></X>\n" + " <N>100</N>\n" + " <XN>1</XN>\n" + "</root>").ignoreWhitespace()); } @Test public void _X9_XS9() throws Exception { createFormatFile( "UTF-8", "[root]", "1 X9 X9", "2 SX9 SX9" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); final DataRecord input = new DataRecord(); input.put("X9", "aaaa"); input.put("SX9", true); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root>\n" + " <X9>aaaa</X9>\n" + " <SX9>true</SX9>\n" + "</root>").ignoreWhitespace()); } @Test public void _BL() throws Exception { createFormatFile( "UTF-8", "[root]", "1 BL1 BL", "2 BL2 BL" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); final DataRecord input = new DataRecord(); input.put("BL1", true); input.put("BL2", "aaaa"); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root>\n" + " <BL1>true</BL1>\n" + " <BL2>aaaa</BL2>\n" + "</root>").ignoreWhitespace()); } @Test public void OB() throws Exception { createFormatFile( "UTF-8", "[root]", "1 @child OB", "[child]", "1 name X" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); final DataRecord input = new DataRecord(); input.put("child.name", "name"); expectedException.expect(InvalidDataFormatException.class); expectedException.expectMessage("child is Object but specified by Attribute"); sut.buildData(input, getLayoutDefinition(), actual); } @Test public void null() throws Exception { createFormatFile( "UTF-8", "[root]", "1 data X \"\"", "2 num X9 999" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); final DataRecord input = new DataRecord(); input.put("data", null); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root>\n" + " <data></data>\n" + " <num>999</num>\n" + "</root>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 data X \"\"" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); final DataRecord input = new DataRecord(); input.put("data", ""); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root>\n" + " <data></data>\n" + "</root>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 X9 X9 number", "2 SX9 SX9 signed_number" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); final DataRecord input = new DataRecord(); input.put("X9", "100"); input.put("SX9", "-1.123"); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root>\n" + " <X9>100</X9>\n" + " <SX9>-1.123</SX9>\n" + "</root>").ignoreWhitespace()); } @Test public void number() throws Exception { createFormatFile( "UTF-8", "[root]", "1 X9 X9 number", "2 SX9 SX9 signed_number" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); final DataRecord input = new DataRecord(); input.put("X9", new BigDecimal("-100")); input.put("SX9", "-1.123"); expectedException.expect(InvalidDataFormatException.class); expectedException.expectMessage("value=[-100]. field name=[X9]"); sut.buildData(input, getLayoutDefinition(), actual); } @Test public void signed_number() throws Exception { createFormatFile( "UTF-8", "[root]", "1 X9 X9 number", "2 SX9 SX9 signed_number" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); final DataRecord input = new DataRecord(); input.put("X9", new BigDecimal("100")); input.put("SX9", ""); expectedException.expect(InvalidDataFormatException.class); expectedException.expectMessage("value=[]. field name=[SX9]"); sut.buildData(input, getLayoutDefinition(), actual); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 text X replacement(\"charconverter\")" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); final DataRecord input = new DataRecord(); input.put("text", ""); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root>\n" + " <text></text>\n" + "</root>").ignoreWhitespace()); } @Test public void () throws Exception { createFormatFile( "UTF-8", "[root]", "1 ?@xmlns:ns X \"http://test.com/apply\"", "2 ns:data OB", "[ns:data]", "1 ns:name X", "2 ns:age X9" ); final ByteArrayOutputStream actual = new ByteArrayOutputStream(); final DataRecord input = new DataRecord(); input.put("nsData.nsname", ""); input.put("nsData.nsage", 100); sut.buildData(input, getLayoutDefinition(), actual); System.out.println("actual.toString(\"utf-8\") = " + actual.toString("utf-8")); assertThat(actual.toString("utf-8"), isIdenticalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<root xmlns:ns='http://test.com/apply'>\n" + " <ns:data>\n" + " <ns:name></ns:name>\n" + " <ns:age>100</ns:age>\n" + " </ns:data>\n" + "</root>").ignoreWhitespace()); } }
package net.coobird.thumbnailator; import static org.junit.Assert.*; import java.awt.Dimension; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.imageio.ImageIO; import net.coobird.thumbnailator.builders.BufferedImageBuilder; import net.coobird.thumbnailator.builders.ThumbnailParameterBuilder; import net.coobird.thumbnailator.name.Rename; import net.coobird.thumbnailator.resizers.DefaultResizerFactory; import net.coobird.thumbnailator.resizers.ResizerFactory; import net.coobird.thumbnailator.tasks.SourceSinkThumbnailTask; import net.coobird.thumbnailator.tasks.UnsupportedFormatException; import net.coobird.thumbnailator.tasks.io.BufferedImageSink; import net.coobird.thumbnailator.tasks.io.BufferedImageSource; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.ArgumentCaptor; import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; /** * Unit tests for the {@link Thumbnailator} class. * * @author coobird * */ @RunWith(Enclosed.class) @SuppressWarnings("deprecation") public class ThumbnailatorTest { public static class Tests { /** * Test for * {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)} * where, * <p> * 1) All parameters are correct, except * a) The Collection is null * <p> * Expected outcome is, * <p> * 1) Processing will stop with an NullPointerException. * * @throws IOException */ @Test(expected = NullPointerException.class) public void testCreateThumbnailCollections_nullCollection() throws IOException { try { Thumbnailator.createThumbnailsAsCollection( null, Rename.PREFIX_DOT_THUMBNAIL, 50, 50 ); fail(); } catch (NullPointerException e) { assertEquals("Collection of Files is null.", e.getMessage()); throw e; } } /** * Test for * {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)} * where, * <p> * 1) All parameters are correct, except * a) The Rename is null * <p> * Expected outcome is, * <p> * 1) Processing will stop with an NullPointerException. * * @throws IOException */ @Test(expected = NullPointerException.class) public void testCreateThumbnailCollections_nullRename() throws IOException { /* * The files to make thumbnails of. */ List<File> files = Collections.singletonList( new File("nameDoesntMatter.jpg") ); try { Thumbnailator.createThumbnailsAsCollection( files, null, 50, 50 ); fail(); } catch (NullPointerException e) { assertEquals("Rename is null.", e.getMessage()); throw e; } } /** * Test for * {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)} * where, * <p> * 1) All parameters are correct, except * a) The Collection is null * <p> * Expected outcome is, * <p> * 1) Processing will stop with an NullPointerException. * * @throws IOException */ @Test(expected = NullPointerException.class) public void testCreateThumbnails_nullCollection() throws IOException { try { Thumbnailator.createThumbnails( null, Rename.PREFIX_DOT_THUMBNAIL, 50, 50 ); fail(); } catch (NullPointerException e) { assertEquals("Collection of Files is null.", e.getMessage()); throw e; } } /** * Test for * {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)} * where, * <p> * 1) All parameters are correct, except * a) The Rename is null * <p> * Expected outcome is, * <p> * 1) Processing will stop with an NullPointerException. * * @throws IOException */ @Test(expected = NullPointerException.class) public void testCreateThumbnails_nullRename() throws IOException { /* * The files to make thumbnails of. */ List<File> files = Collections.singletonList( new File("nameDoesntMatter.jpg") ); try { Thumbnailator.createThumbnails( files, null, 50, 50 ); fail(); } catch (NullPointerException e) { assertEquals("Rename is null.", e.getMessage()); throw e; } } /** * Test for * {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)} * where, * <p> * 1) InputStream is null * <p> * Expected outcome is, * <p> * 1) Processing will stop with an NullPointerException. * * @throws IOException */ @Test(expected = NullPointerException.class) public void testCreateThumbnail_IOII_nullIS() throws IOException { /* * Actual test */ InputStream is = null; ByteArrayOutputStream os = new ByteArrayOutputStream(); Thumbnailator.createThumbnail(is, os, 50, 50); fail(); } /** * Test for * {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)} * where, * <p> * 1) OutputStream is null * <p> * Expected outcome is, * <p> * 1) Processing will stop with an NullPointerException. * * @throws IOException */ @Test(expected = NullPointerException.class) public void testCreateThumbnail_IOII_nullOS() throws IOException { /* * Actual test */ byte[] bytes = makeImageData("jpg", 200, 200); InputStream is = new ByteArrayInputStream(bytes); ByteArrayOutputStream os = null; Thumbnailator.createThumbnail(is, os, 50, 50); fail(); } /** * Test for * {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)} * where, * <p> * 1) InputStream is null * 2) OutputStream is null * <p> * Expected outcome is, * <p> * 1) Processing will stop with an NullPointerException. * * @throws IOException */ @Test(expected = NullPointerException.class) public void testCreateThumbnail_IOII_nullISnullOS() throws IOException { Thumbnailator.createThumbnail((InputStream) null, null, 50, 50); fail(); } /** * Test for * {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)} * where, * <p> * 1) InputStream throws an IOException during read. * <p> * Expected outcome is, * <p> * 1) Processing will stop with an IOException. * * @throws IOException */ @Test(expected = IOException.class) public void testCreateThumbnail_IOII_IOExceptionFromIS() throws IOException { /* * Actual test */ InputStream is = mock(InputStream.class); doThrow(new IOException("read error!")).when(is).read(); doThrow(new IOException("read error!")).when(is).read((byte[]) any()); doThrow(new IOException("read error!")).when(is).read((byte[]) any(), anyInt(), anyInt()); ByteArrayOutputStream os = new ByteArrayOutputStream(); Thumbnailator.createThumbnail(is, os, 50, 50); fail(); } /** * Test for * {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)} * where, * <p> * 1) OutputStream throws an IOException during read. * <p> * Expected outcome is, * <p> * 1) Processing will stop with an IOException. * * @throws IOException */ @Test(expected = IOException.class) public void testCreateThumbnail_IOII_IOExceptionFromOS() throws IOException { /* * Actual test */ byte[] bytes = makeImageData("png", 200, 200); InputStream is = new ByteArrayInputStream(bytes); OutputStream os = mock(OutputStream.class); doThrow(new IOException("write error!")).when(os).write(anyInt()); doThrow(new IOException("write error!")).when(os).write((byte[]) any()); doThrow(new IOException("write error!")).when(os).write((byte[]) any(), anyInt(), anyInt()); Thumbnailator.createThumbnail(is, os, 50, 50); fail(); } /** * Test for * {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)} * where, * <p> * 1) InputStream throws an IOException during read. * <p> * Expected outcome is, * <p> * 1) Processing will stop with an IOException. * * @throws IOException */ @Test(expected = IOException.class) public void testCreateThumbnail_IOSII_IOExceptionFromIS() throws IOException { /* * Actual test */ InputStream is = mock(InputStream.class); doThrow(new IOException("read error!")).when(is).read(); doThrow(new IOException("read error!")).when(is).read((byte[]) any()); doThrow(new IOException("read error!")).when(is).read((byte[]) any(), anyInt(), anyInt()); ByteArrayOutputStream os = new ByteArrayOutputStream(); Thumbnailator.createThumbnail(is, os, "png", 50, 50); fail(); } /** * Test for * {@link Thumbnailator#createThumbnail(InputStream, OutputStream, String, int, int)} * where, * <p> * 1) OutputStream throws an IOException during read. * <p> * Expected outcome is, * <p> * 1) Processing will stop with an IOException. * * @throws IOException */ @Test(expected = IOException.class) public void testCreateThumbnail_IOSII_IOExceptionFromOS() throws IOException { /* * Actual test */ byte[] bytes = makeImageData("png", 200, 200); InputStream is = new ByteArrayInputStream(bytes); OutputStream os = mock(OutputStream.class); doThrow(new IOException("write error!")).when(os).write(anyInt()); doThrow(new IOException("write error!")).when(os).write((byte[]) any()); doThrow(new IOException("write error!")).when(os).write((byte[]) any(), anyInt(), anyInt()); Thumbnailator.createThumbnail(is, os, "png", 50, 50); fail(); } /** * Test for * {@link Thumbnailator#createThumbnail(File, File, int, int)} * where, * <p> * 1) Input File is null * <p> * Expected outcome is, * <p> * 1) Processing will stop with an NullPointerException. * * @throws IOException */ @Test(expected = NullPointerException.class) public void testCreateThumbnail_FFII_nullInputFile() throws IOException { /* * Actual test */ File inputFile = null; File outputFile = new File("bar.jpg"); Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50); fail(); } /** * Test for * {@link Thumbnailator#createThumbnail(File, File, int, int)} * where, * <p> * 1) Output File is null * <p> * Expected outcome is, * <p> * 1) Processing will stop with an NullPointerException. * * @throws IOException */ @Test(expected = NullPointerException.class) public void testCreateThumbnail_FFII_nullOutputFile() throws IOException { /* * Actual test */ File inputFile = new File("foo.jpg"); File outputFile = null; Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50); fail(); } /** * Test for * {@link Thumbnailator#createThumbnail(File, File, int, int)} * where, * <p> * 1) Input File is null * 2) Output File is null * <p> * Expected outcome is, * <p> * 1) Processing will stop with an NullPointerException. * * @throws IOException */ @Test(expected = NullPointerException.class) public void testCreateThumbnail_FFII_nullInputAndOutputFiles() throws IOException { Thumbnailator.createThumbnail((File) null, null, 50, 50); fail(); } /** * Test for * {@link Thumbnailator#createThumbnail(File, File, int, int)} * where, * <p> * 1) Input File does not exist. * <p> * Expected outcome is, * <p> * 1) Processing will stop with an IOException. * * @throws IOException */ @Test public void testCreateThumbnail_FFII_nonExistentInputFile() throws IOException { /* * Actual test */ File inputFile = new File("foo.jpg"); File outputFile = new File("bar.jpg"); try { Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50); fail(); } catch (IOException e) { assertEquals("Input file does not exist.", e.getMessage()); } } /** * Test for * {@link Thumbnailator#createThumbnail(File, File, int, int)} * where, * <p> * 1) A problem occurs while writing to the file. * <p> * Expected outcome is, * <p> * 1) Processing will stop with an IOException. * * @throws IOException */ @Ignore public void testCreateThumbnail_FFII_IOExceptionOnWrite() throws IOException { //Cannot craft a test case to test this condition. fail(); } /** * Test for * {@link Thumbnailator#createThumbnail(File, int, int)} * where, * <p> * 1) Input File is null * <p> * Expected outcome is, * <p> * 1) Processing will stop with an NullPointerException. * * @throws IOException */ @Test(expected = NullPointerException.class) public void testCreateThumbnail_FII_nullInputFile() throws IOException { Thumbnailator.createThumbnail((File) null, 50, 50); fail(); } /** * Test for * {@link Thumbnailator#createThumbnail(BufferedImage, int, int)} * where, * <p> * 1) Method arguments are correct * <p> * Expected outcome is, * <p> * 1) Processing will complete successfully. */ @Test public void testCreateThumbnail_BII_CorrectUsage() { /* * Actual test */ BufferedImage img = new BufferedImageBuilder(200, 200, BufferedImage.TYPE_INT_ARGB).build(); BufferedImage thumbnail = Thumbnailator.createThumbnail(img, 50, 50); assertEquals(50, thumbnail.getWidth()); assertEquals(50, thumbnail.getHeight()); assertEquals(BufferedImage.TYPE_INT_ARGB, thumbnail.getType()); } /** * Test for * {@link Thumbnailator#createThumbnail(Image, int, int)} * where, * <p> * 1) Method arguments are correct * <p> * Expected outcome is, * <p> * 1) Processing will complete successfully. */ @Test public void testCreateThumbnail_III_CorrectUsage() { /* * Actual test */ BufferedImage img = new BufferedImageBuilder(200, 200, BufferedImage.TYPE_INT_ARGB).build(); Image thumbnail = Thumbnailator.createThumbnail((Image) img, 50, 50); assertEquals(50, thumbnail.getWidth(null)); assertEquals(50, thumbnail.getHeight(null)); } /** * Test for * {@link Thumbnailator#createThumbnail(net.coobird.thumbnailator.tasks.ThumbnailTask)} * where, * <p> * 1) The correct parameters are given. * 2) The size is specified for the ThumbnailParameter. * <p> * Expected outcome is, * <p> * 1) The ResizerFactory is being used. * * @throws IOException */ @Test public void testCreateThumbnail_ThumbnailTask_ResizerFactoryBeingUsed_UsingSize() throws IOException { // given BufferedImageSource source = new BufferedImageSource( new BufferedImageBuilder(200, 200, BufferedImage.TYPE_INT_ARGB).build() ); BufferedImageSink sink = new BufferedImageSink(); ResizerFactory resizerFactory = spy(DefaultResizerFactory.getInstance()); ThumbnailParameter param = new ThumbnailParameterBuilder() .size(100, 100) .resizerFactory(resizerFactory) .build(); // when Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<BufferedImage, BufferedImage>( param, source, sink ) ); // then verify(resizerFactory) .getResizer(new Dimension(200, 200), new Dimension(100, 100)); } /** * Test for * {@link Thumbnailator#createThumbnail(net.coobird.thumbnailator.tasks.ThumbnailTask)} * where, * <p> * 1) The correct parameters are given. * 2) The scale is specified for the ThumbnailParameter. * <p> * Expected outcome is, * <p> * 1) The ResizerFactory is being used. * * @throws IOException */ @Test public void testCreateThumbnail_ThumbnailTask_ResizerFactoryBeingUsed_UsingScale() throws IOException { // given BufferedImageSource source = new BufferedImageSource( new BufferedImageBuilder(200, 200, BufferedImage.TYPE_INT_ARGB).build() ); BufferedImageSink sink = new BufferedImageSink(); ResizerFactory resizerFactory = spy(DefaultResizerFactory.getInstance()); ThumbnailParameter param = new ThumbnailParameterBuilder() .scale(0.5) .resizerFactory(resizerFactory) .build(); // when Thumbnailator.createThumbnail( new SourceSinkThumbnailTask<BufferedImage, BufferedImage>( param, source, sink ) ); // then verify(resizerFactory) .getResizer(new Dimension(200, 200), new Dimension(100, 100)); } } public static class FileIOTests { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); private boolean isTemporaryFolderEmpty() { String[] files = temporaryFolder.getRoot().list(); if (files == null) { throw new IllegalStateException("Temporary folder didn't exist. Shouldn't happen."); } return files.length == 0; } /** * Test for * {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)} * where, * <p> * 1) All parameters are correct * a) The Collection is an empty List. * <p> * Expected outcome is, * <p> * 1) Processing will complete successfully. * * @throws IOException */ @Test public void testCreateThumbnailCollections_NoErrors_EmptyList() throws IOException { /* * The files to make thumbnails of -- nothing! */ List<File> files = Collections.emptyList(); Collection<File> resultingFiles = Thumbnailator.createThumbnailsAsCollection( files, Rename.PREFIX_DOT_THUMBNAIL, 50, 50 ); assertTrue(resultingFiles.isEmpty()); assertTrue(isTemporaryFolderEmpty()); } /** * Test for * {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)} * where, * <p> * 1) All parameters are correct * a) The Collection is an empty Set. * <p> * Expected outcome is, * <p> * 1) Processing will complete successfully. * * @throws IOException */ @Test public void testCreateThumbnailCollections_NoErrors_EmptySet() throws IOException { /* * The files to make thumbnails of -- nothing! */ Set<File> files = Collections.emptySet(); Collection<File> resultingFiles = Thumbnailator.createThumbnailsAsCollection( files, Rename.PREFIX_DOT_THUMBNAIL, 50, 50 ); assertTrue(resultingFiles.isEmpty()); assertTrue(isTemporaryFolderEmpty()); } /** * Test for * {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)} * where, * <p> * 1) All parameters are correct * 2) All data can be processed correctly. * <p> * Expected outcome is, * <p> * 1) Processing will complete successfully. * * @throws IOException */ @Test public void testCreateThumbnailCollections_NoErrors() throws IOException { File sourceFile1 = TestUtils.copyResourceToTemporaryFile( "Thumbnailator/grid.jpg", temporaryFolder ); File sourceFile2 = TestUtils.copyResourceToTemporaryFile( "Thumbnailator/grid.png", temporaryFolder ); List<File> files = Arrays.asList(sourceFile1, sourceFile2); Collection<File> resultingFiles = Thumbnailator.createThumbnailsAsCollection( files, Rename.PREFIX_DOT_THUMBNAIL, 50, 50 ); /* * Perform post-execution checks. */ Iterator<File> iter = resultingFiles.iterator(); BufferedImage img0 = ImageIO.read(iter.next()); assertEquals(50, img0.getWidth()); assertEquals(50, img0.getHeight()); BufferedImage img1 = ImageIO.read(iter.next()); assertEquals(50, img1.getWidth()); assertEquals(50, img1.getHeight()); assertTrue(!iter.hasNext()); } /** * Test for * {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)} * where, * <p> * 1) All parameters are correct * 2) A file that was specified does not exist * <p> * Expected outcome is, * <p> * 1) Processing will stop with an IOException. * * @throws IOException */ @Test(expected = IOException.class) public void testCreateThumbnailCollections_ErrorDuringProcessing_FileNotFound() throws IOException { File sourceFile = TestUtils.copyResourceToTemporaryFile( "Thumbnailator/grid.jpg", temporaryFolder ); File nonExistentFile = new File(temporaryFolder.getRoot(), "doesntExist.jpg"); List<File> files = Arrays.asList(sourceFile, nonExistentFile); Thumbnailator.createThumbnailsAsCollection( files, Rename.PREFIX_DOT_THUMBNAIL, 50, 50 ); fail(); } /** * Test for * {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)} * where, * <p> * 1) All parameters are correct * 2) The thumbnail cannot be written. (unsupported format) * <p> * Expected outcome is, * <p> * 1) Processing will stop with an UnsupportedFormatException. * * @throws IOException */ @Test(expected = UnsupportedFormatException.class) public void testCreateThumbnailCollections_ErrorDuringProcessing_CantWriteThumbnail() throws IOException { File sourceFile1 = TestUtils.copyResourceToTemporaryFile( "Thumbnailator/grid.jpg", temporaryFolder ); File sourceFile2 = TestUtils.copyResourceToTemporaryFile( "Thumbnailator/grid.gif", temporaryFolder ); List<File> files = Arrays.asList(sourceFile1, sourceFile2); // This will force a UnsupportedFormatException when trying to output // a thumbnail whose source was a gif file. Rename brokenRenamer = new Rename() { @Override public String apply(String name, ThumbnailParameter param) { if (name.endsWith(".gif")) { return "thumbnail." + name + ".foobar"; } return "thumbnail." + name; } }; Thumbnailator.createThumbnailsAsCollection( files, brokenRenamer, 50, 50 ); fail(); } /** * Test for * {@link Thumbnailator#createThumbnailsAsCollection(Collection, Rename, int, int)} * where, * <p> * 1) All parameters are correct * 2) All data can be processed correctly. * 3) The Collection is a List of a class extending File. * <p> * Expected outcome is, * <p> * 1) Processing will complete successfully. * * @throws IOException */ @Test public void testCreateThumbnailCollections_NoErrors_CollectionExtendsFile() throws IOException { class File2 extends File { private static final long serialVersionUID = 1L; public File2(String pathname) { super(pathname); } } File sourceFile1 = TestUtils.copyResourceToTemporaryFile( "Thumbnailator/grid.jpg", temporaryFolder ); File sourceFile2 = TestUtils.copyResourceToTemporaryFile( "Thumbnailator/grid.png", temporaryFolder ); /* * The files to make thumbnails of. */ List<File2> files = Arrays.asList( new File2(sourceFile1.getAbsolutePath()), new File2(sourceFile2.getAbsolutePath()) ); Collection<File> resultingFiles = Thumbnailator.createThumbnailsAsCollection( files, Rename.PREFIX_DOT_THUMBNAIL, 50, 50 ); /* * Perform post-execution checks. */ Iterator<File> iter = resultingFiles.iterator(); BufferedImage img0 = ImageIO.read(iter.next()); assertEquals(50, img0.getWidth()); assertEquals(50, img0.getHeight()); BufferedImage img1 = ImageIO.read(iter.next()); assertEquals(50, img1.getWidth()); assertEquals(50, img1.getHeight()); assertTrue(!iter.hasNext()); } /** * Test for * {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)} * where, * <p> * 1) All parameters are correct * a) The Collection is an empty List. * <p> * Expected outcome is, * <p> * 1) Processing will complete successfully. * * @throws IOException */ @Test public void testCreateThumbnails_NoErrors_EmptyList() throws IOException { /* * The files to make thumbnails of -- nothing! */ List<File> files = Collections.emptyList(); Thumbnailator.createThumbnails( files, Rename.PREFIX_DOT_THUMBNAIL, 50, 50 ); assertTrue(isTemporaryFolderEmpty()); } /** * Test for * {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)} * where, * <p> * 1) All parameters are correct * a) The Collection is an empty Set. * <p> * Expected outcome is, * <p> * 1) Processing will complete successfully. * * @throws IOException */ @Test public void testCreateThumbnails_NoErrors_EmptySet() throws IOException { /* * The files to make thumbnails of -- nothing! */ Set<File> files = Collections.emptySet(); Thumbnailator.createThumbnails( files, Rename.PREFIX_DOT_THUMBNAIL, 50, 50 ); assertTrue(isTemporaryFolderEmpty()); } /** * Test for * {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)} * where, * <p> * 1) All parameters are correct * 2) All data can be processed correctly. * <p> * Expected outcome is, * <p> * 1) Processing will complete successfully. * * @throws IOException */ @Test public void testCreateThumbnails_NoErrors() throws IOException { File sourceFile1 = TestUtils.copyResourceToTemporaryFile( "Thumbnailator/grid.jpg", temporaryFolder ); File sourceFile2 = TestUtils.copyResourceToTemporaryFile( "Thumbnailator/grid.png", temporaryFolder ); List<File> files = Arrays.asList(sourceFile1, sourceFile2); Thumbnailator.createThumbnails( files, Rename.PREFIX_DOT_THUMBNAIL, 50, 50 ); /* * Perform post-execution checks. */ BufferedImage img0 = ImageIO.read(new File(temporaryFolder.getRoot(), "thumbnail.grid.jpg")); assertEquals(50, img0.getWidth()); assertEquals(50, img0.getHeight()); BufferedImage img1 = ImageIO.read(new File(temporaryFolder.getRoot(), "thumbnail.grid.png")); assertEquals(50, img1.getWidth()); assertEquals(50, img1.getHeight()); } /** * Test for * {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)} * where, * <p> * 1) All parameters are correct * 2) A file that was specified does not exist * <p> * Expected outcome is, * <p> * 1) Processing will stop with an IOException. * * @throws IOException */ @Test(expected = IOException.class) public void testCreateThumbnails_ErrorDuringProcessing_FileNotFound() throws IOException { File sourceFile = TestUtils.copyResourceToTemporaryFile( "Thumbnailator/grid.jpg", temporaryFolder ); File nonExistentFile = new File(temporaryFolder.getRoot(), "doesntExist.jpg"); List<File> files = Arrays.asList(sourceFile, nonExistentFile); Thumbnailator.createThumbnails( files, Rename.PREFIX_DOT_THUMBNAIL, 50, 50 ); fail(); } /** * Test for * {@link Thumbnailator#createThumbnails(Collection, Rename, int, int)} * where, * <p> * 1) All parameters are correct * 2) The thumbnail cannot be written. (unsupported format) * <p> * Expected outcome is, * <p> * 1) Processing will stop with an UnsupportedFormatException. * * @throws IOException */ @Test(expected = UnsupportedFormatException.class) public void testCreateThumbnails_ErrorDuringProcessing_CantWriteThumbnail() throws IOException { File sourceFile1 = TestUtils.copyResourceToTemporaryFile( "Thumbnailator/grid.jpg", temporaryFolder ); File sourceFile2 = TestUtils.copyResourceToTemporaryFile( "Thumbnailator/grid.gif", temporaryFolder ); List<File> files = Arrays.asList(sourceFile1, sourceFile2); // This will force a UnsupportedFormatException when trying to output // a thumbnail whose source was a gif file. Rename brokenRenamer = new Rename() { @Override public String apply(String name, ThumbnailParameter param) { if (name.endsWith(".gif")) { return "thumbnail." + name + ".foobar"; } return "thumbnail." + name; } }; Thumbnailator.createThumbnails( files, brokenRenamer, 50, 50 ); fail(); } @Test public void renameGivenThumbnailParameter_createThumbnails() throws IOException { // given Rename rename = mock(Rename.class); when(rename.apply(anyString(), any(ThumbnailParameter.class))) .thenReturn("thumbnail.grid.png"); File f = TestUtils.copyResourceToTemporaryFile( "Thumbnailator/grid.png", temporaryFolder ); // when Thumbnailator.createThumbnails( Collections.singletonList(f), rename, 50, 50 ); // then ArgumentCaptor<ThumbnailParameter> ac = ArgumentCaptor.forClass(ThumbnailParameter.class); verify(rename).apply(eq(f.getName()), ac.capture()); assertEquals(new Dimension(50, 50), ac.getValue().getSize()); } @Test public void renameGivenThumbnailParameter_createThumbnailsAsCollection() throws IOException { // given Rename rename = mock(Rename.class); when(rename.apply(anyString(), any(ThumbnailParameter.class))) .thenReturn("thumbnail.grid.png"); File f = TestUtils.copyResourceToTemporaryFile( "Thumbnailator/grid.png", temporaryFolder ); // when Thumbnailator.createThumbnailsAsCollection( Collections.singletonList(f), rename, 50, 50 ); // then ArgumentCaptor<ThumbnailParameter> ac = ArgumentCaptor.forClass(ThumbnailParameter.class); verify(rename).apply(eq(f.getName()), ac.capture()); assertEquals(new Dimension(50, 50), ac.getValue().getSize()); } /** * Test for * {@link Thumbnailator#createThumbnail(File, File, int, int)} * where, * <p> * 1) A filename that is invalid * <p> * Expected outcome is, * <p> * 1) Processing will stop with an IOException. * * @throws IOException */ @Test public void testCreateThumbnail_FFII_invalidOutputFile() throws IOException { /* * Actual test */ File inputFile = TestUtils.copyResourceToTemporaryFile( "Thumbnailator/grid.png", temporaryFolder ); File outputFile = new File( temporaryFolder.getRoot(), "@\\ ); try { Thumbnailator.createThumbnail(inputFile, outputFile, 50, 50); fail(); } catch (IOException e) { // An IOException is expected. Likely a FileNotFoundException. } } } @RunWith(Parameterized.class) public static class InvalidDimensionsTests { @Parameterized.Parameters(name = "width={0}, height={1}") public static Object[][] values() { return new Object[][] { new Object[] {-42, 42}, new Object[] {42, -42}, new Object[] {-42, -42} }; } @Parameterized.Parameter public int width; @Parameterized.Parameter(1) public int height; @Test(expected = IllegalArgumentException.class) public void testCreateThumbnailCollections() throws IOException { List<File> files = Arrays.asList( new File("foo.png"), new File("bar.jpg") ); Thumbnailator.createThumbnailsAsCollection( files, Rename.PREFIX_DOT_THUMBNAIL, width, height ); fail(); } @Test(expected = IllegalArgumentException.class) public void testCreateThumbnails() throws IOException { List<File> files = Arrays.asList( new File("foo.png"), new File("bar.jpg") ); Thumbnailator.createThumbnails( files, Rename.PREFIX_DOT_THUMBNAIL, width, height ); fail(); } @Test(expected = IllegalArgumentException.class) public void testCreateThumbnail_IOII() throws IOException { byte[] bytes = makeImageData("jpg", 200, 200); InputStream is = new ByteArrayInputStream(bytes); ByteArrayOutputStream os = new ByteArrayOutputStream(); Thumbnailator.createThumbnail(is, os, width, height); fail(); } @Test(expected = IllegalArgumentException.class) public void testCreateThumbnail_FII() throws IOException { File inputFile = new File("foo.jpg"); Thumbnailator.createThumbnail(inputFile, width, height); fail(); } @Test(expected = IllegalArgumentException.class) public void testCreateThumbnail_BII() { BufferedImage img = new BufferedImageBuilder(200, 200).build(); Thumbnailator.createThumbnail(img, width, height); fail(); } @Test(expected = IllegalArgumentException.class) public void testCreateThumbnail_FFII() throws IOException { File inputFile = new File("foo.jpg"); File outputFile = new File("bar.jpg"); Thumbnailator.createThumbnail(inputFile, outputFile, width, height); fail(); } @Test(expected = IllegalArgumentException.class) public void testCreateThumbnail_III() { BufferedImage img = new BufferedImageBuilder(200, 200).build(); Thumbnailator.createThumbnail((Image) img, width, height); fail(); } } /** * Returns test image data as an array of {@code byte}s. * * @param format Image format. * @param width Image width. * @param height Image height. * @throws IOException When a problem occurs while making image data. * @return A {@code byte[]} of image data. */ private static byte[] makeImageData(String format, int width, int height) throws IOException { BufferedImage img = new BufferedImageBuilder(width, height) .imageType("jpg".equals(format) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB) .build(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(img, format, baos); return baos.toByteArray(); } }
package org.arangodb.objectmapper.test; import java.io.InputStream; import java.util.Properties; import org.apache.commons.codec.binary.StringUtils; import org.apache.log4j.Logger; import org.arangodb.objectmapper.ArangoDb4JException; import org.arangodb.objectmapper.Database; import org.arangodb.objectmapper.http.ArangoDbHttpClient; import junit.framework.TestCase; public abstract class BaseTestCase extends TestCase { private static Logger LOG = Logger.getLogger(BaseTestCase.class); /** * the ArangoDB connection */ protected Database database; /** * the ArangoDB client */ protected ArangoDbHttpClient client; /** * name of the test vertex collection */ protected final String docCollection = "unittest_collection"; /** * name of the test database */ protected final String dbName = "ArangoDbObjectMapper"; /** * path for the collection api */ protected final static String COLLECTION_PATH = "/_api/collection/"; /** * path for the database api */ protected final static String DATABASE_PATH = "/_api/database/"; protected void setUp() { try { Properties properties = loadPropertiesFromFile(); ArangoDbHttpClient.Builder builder = new ArangoDbHttpClient.Builder(); client = builder.username(properties.getProperty("arangodb.user")) .password(properties.getProperty("arangodb.password")).host(properties.getProperty("arangodb.host")) .port(Integer.parseInt(properties.getProperty("arangodb.port"))).build(); } catch (ArangoDb4JException e1) { LOG.error("Cant create Builder", e1); } try { database = Database.createDatabase(client, dbName); } catch (ArangoDb4JException e) { if (e.getStatusCode() == 409) { // conflict database = new Database(client, dbName); } } assertNotNull(database); // delete some collections try { client.delete(database.buildPath(COLLECTION_PATH + Database.getCollectionName(Point.class))); } catch (ArangoDb4JException e1) { LOG.error("Cant create Builder", e1); } } protected void tearDown() { try { client.delete(database.buildPath(COLLECTION_PATH + Database.getCollectionName(Point.class))); } catch (ArangoDb4JException e1) { LOG.error("Cant create Builder", e1); } database = null; } private Properties loadPropertiesFromFile() { Properties props = new Properties(); try { LOG.debug("Try to load Properties from " + BaseTestCase.class.getResource("/arangodb.properties").getFile()); InputStream resourceAsStream = BaseTestCase.class.getResourceAsStream("/arangodb.properties"); props.load(resourceAsStream); LOG.debug("Load " + props.size() +" Properties from " + BaseTestCase.class.getResource("/arangodb.properties").getFile()); props.forEach((key, val) -> { String systemPropName = key.toString().replace(".", "_"); LOG.debug("Check Env " + systemPropName + " for override of " + key); String systemProp = System.getProperty(systemPropName); if(systemProp != null) { LOG.info("Found System Property for " + key + " with Value " + systemProp); props.put(key, systemProp); } }); } catch (Exception e) { LOG.warn("Cant read Properties from File", e); } return props; } }
package org.arangodb.objectmapper.test; import java.io.InputStream; import java.util.Properties; import org.apache.commons.codec.binary.StringUtils; import org.apache.log4j.Logger; import org.arangodb.objectmapper.ArangoDb4JException; import org.arangodb.objectmapper.Database; import org.arangodb.objectmapper.http.ArangoDbHttpClient; import junit.framework.TestCase; public abstract class BaseTestCase extends TestCase { private static Logger LOG = Logger.getLogger(BaseTestCase.class); /** * the ArangoDB connection */ protected Database database; /** * the ArangoDB client */ protected ArangoDbHttpClient client; /** * name of the test vertex collection */ protected final String docCollection = "unittest_collection"; /** * name of the test database */ protected final String dbName = "ArangoDbObjectMapper"; /** * path for the collection api */ protected final static String COLLECTION_PATH = "/_api/collection/"; /** * path for the database api */ protected final static String DATABASE_PATH = "/_api/database/"; protected void setUp() { try { Properties properties = loadPropertiesFromFile(); ArangoDbHttpClient.Builder builder = new ArangoDbHttpClient.Builder(); client = builder.username(properties.getProperty("arangodb.user")) .password(properties.getProperty("arangodb.password")).host(properties.getProperty("arangodb.host")) .port(Integer.parseInt(properties.getProperty("arangodb.port"))).build(); } catch (ArangoDb4JException e1) { LOG.error("Cant create Builder", e1); } try { database = Database.createDatabase(client, dbName); } catch (ArangoDb4JException e) { if (e.getStatusCode() == 409) { // conflict database = new Database(client, dbName); } } assertNotNull(database); // delete some collections try { client.delete(database.buildPath(COLLECTION_PATH + Database.getCollectionName(Point.class))); } catch (ArangoDb4JException e1) { LOG.error("Cant create Builder", e1); } } protected void tearDown() { try { client.delete(database.buildPath(COLLECTION_PATH + Database.getCollectionName(Point.class))); } catch (ArangoDb4JException e1) { LOG.error("Cant create Builder", e1); } database = null; } private Properties loadPropertiesFromFile() { Properties props = new Properties(); try { LOG.debug("Try to load Properties from " + BaseTestCase.class.getResource("/arangodb.properties").getFile()); InputStream resourceAsStream = BaseTestCase.class.getResourceAsStream("/arangodb.properties"); props.load(resourceAsStream); LOG.debug("Load " + props.size() +" Properties from " + BaseTestCase.class.getResource("/arangodb.properties").getFile()); props.forEach((key, val) -> { String systemProp = System.getProperty(key.toString()); if(systemProp != null && systemProp.equals(val) == false) { LOG.info("Found System Property for " + key + " with Value " + systemProp); props.put(key, systemProp); } }); } catch (Exception e) { LOG.warn("Cant read Properties from File", e); } return props; } }
package org.scm4j.vcs.api.exceptions; import org.junit.Test; import static org.junit.Assert.*; public class ExceptionsTest { public static final String TEST_MESSAGE = "test message"; public static final String TEST_REPO_URL = "test repo url"; public static final String TEST_BRANCH_NAME = "test branchName"; @Test public void testEVCSException() { EVCSException e = new EVCSException(TEST_MESSAGE); assertTrue(e.getMessage().contains(TEST_MESSAGE)); EVCSException e1 = new EVCSException(e); assertTrue(e1.getMessage().contains(TEST_MESSAGE)); assertEquals(e1.getCause(), e); } @Test public void testEVCSBranchExists() { Exception e = new Exception(TEST_MESSAGE); EVCSBranchExists e1 = new EVCSBranchExists(e); assertTrue(e1.getMessage().contains(TEST_MESSAGE)); assertEquals(e1.getCause(), e); } @Test public void testEVCSFileNotFound() { EVCSFileNotFound e = new EVCSFileNotFound("test repo", "test branch", "test file", "test revision"); assertFalse(e.getMessage().isEmpty()); } @Test public void testEVCSTagExists() { Exception e = new Exception(TEST_MESSAGE); EVCSTagExists e1 = new EVCSTagExists(e); assertTrue(e1.getMessage().contains(TEST_MESSAGE)); assertEquals(e1.getCause(), e); } @Test public void testEVCSBranchNotFound() { EVCSBranchNotFound e = new EVCSBranchNotFound(TEST_REPO_URL, TEST_BRANCH_NAME); assertTrue(e.getMessage().contains(TEST_REPO_URL)); assertTrue(e.getMessage().contains(TEST_BRANCH_NAME)); } }
package org.xins.tests.common.types.standard; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.xins.common.types.TypeValueException; import org.xins.common.types.standard.Int16; import org.xins.common.types.standard.Properties; import org.xins.common.collections.PropertyReader; /** * Tests for class <code>Int16</code>. * * @version $Revision$ $Date$ * @author Chris Gilbride (<a href="mailto:chris.gilbride@nl.wanadoo.com">chris.gilbride@nl.wanadoo.com</a>) */ public class Int16Tests extends TestCase { // Class functions /** * Returns a test suite with all test cases defined by this class. * * @return * the test suite, never <code>null</code>. */ public static Test suite() { return new TestSuite(PropertiesTests.class); } // Class fields // Constructor /** * Constructs a new <code>Int16Tests</code> test suite with * the specified name. The name will be passed to the superconstructor. * * @param name * the name for this test suite. */ public Int16Tests(String name) { super(name); } // Fields ZeroToTen lowerLimit = new ZeroToTen(); // Methods /** * Performs setup for the tests. */ protected void setUp() { // empty } private void reset() { // empty } public void testToString() { lowerLimit.toString((short)12); lowerLimit.toString(Short.valueOf("12")); lowerLimit.toString(null); } public void testFromStringForRequired() throws Throwable { /* This should cause the specified error. However for some reason it * isn't. To prevent the rest of the tests failing this test is commented out. try { lowerLimit.fromStringForRequired("120"); fail("Should fail with a TypeValueException due to out of bounds."); } catch (TypeValueException tve3) { // good } */ try { lowerLimit.fromStringForRequired(null); fail("Should have thrown a String is null error"); } catch (IllegalArgumentException iae) { // this is good } try { lowerLimit.fromStringForRequired("fred"); fail("Should have thrown a TypeValueException from a NumberFormatException."); } catch (TypeValueException tve) { // this is good } try { lowerLimit.fromStringForRequired("7"); } catch (Exception e) { fail("Caught an unexpected error."); } } public void testFromStringForOptional() throws Throwable { try { lowerLimit.fromStringForOptional("fred"); fail("Should have thrown a TypeValueException from a NumberFormatException."); } catch (TypeValueException tve2) { // this is good } try { lowerLimit.fromStringForOptional("4"); } catch (Exception e1) { fail("Caught unexpected error."); } assertNull("Null should be returned when a null is passed.",lowerLimit.fromStringForOptional(null)); } public void testValidValue() throws Throwable { assertFalse("fred is not a valid value.",lowerLimit.isValidValue("fred")); assertFalse("12 is outside the bounds of the instance.",lowerLimit.isValidValue("12")); assertTrue("9 is a valid value as it is within the bounds.",lowerLimit.isValidValue("9")); assertTrue("null is considered to be a valid object",lowerLimit.isValidValue(null)); } class ZeroToTen extends Int16 { // constructor public ZeroToTen() { super("ZeroToTen", (short) 0, (short) 10); } } }
package torrent.download.peer; import java.util.logging.Level; import java.util.logging.Logger; import org.johnnei.utils.ConsoleLogger; import org.johnnei.utils.JMath; import torrent.download.Torrent; import torrent.download.files.disk.DiskJob; import torrent.download.files.disk.DiskJobSendBlock; import torrent.network.BitTorrentSocket; import torrent.protocol.messages.MessageKeepAlive; public class Peer implements Comparable<Peer> { private Torrent torrent; /** * Client information about the connected peer * This will contain the requests the endpoint made of us */ private Client peerClient; /** * Client information about me retrieved from the connected peer<br/> * This will contain the requests we made to the endpoint */ private Client myClient; /** * The current Threads status */ private String status; /** * The last time this connection showed any form of activity<br/> * <i>Values are System.currentMillis()</i> */ private long lastActivity; private String clientName; /** * The count of messages which are still being processed by the IOManager */ private int pendingMessages; /** * The amount of errors the client made<br/> * If the amount reaches 5 the client will be disconnected on the next * peerCheck */ private int strikes; private Logger log; /** * The pieces this peer has */ private Bitfield haveState; /** * The extensions which are supported by this peer */ private Extensions extensions; /** * The absolute maximum amount of requests which the peer can support<br/> * Default value will be {@link Integer#MAX_VALUE} */ private int absoluteRequestLimit; /** * The amount of requests we think this peer can handle at most at the same time. */ private int requestLimit; /** * The bittorrent client which handles this peer's socket information and input/outputstreams */ private BitTorrentSocket socket; public Peer(BitTorrentSocket client, Torrent torrent) { this.torrent = torrent; this.socket = client; peerClient = new Client(); myClient = new Client(); status = ""; clientName = "pending"; lastActivity = System.currentTimeMillis(); log = ConsoleLogger.createLogger("Peer", Level.INFO); extensions = new Extensions(); absoluteRequestLimit = Integer.MAX_VALUE; haveState = new Bitfield(JMath.ceilDivision(torrent.getFiles().getPieceCount(), 8)); requestLimit = 1; } public void connect() { setStatus("Connecting..."); } public void checkDisconnect() { if (strikes >= 5) { socket.close(); return; } int inactiveSeconds = (int) ((System.currentTimeMillis() - lastActivity) / 1000); if (inactiveSeconds > 30) { if (myClient.getQueueSize() > 0) { // We are not receiving a single // byte in the last 30(!) // seconds // Let's try (max twice) if we can wake'm up by sending them a // keepalive addStrike(2); getBitTorrentSocket().queueMessage(new MessageKeepAlive()); updateLastActivity(); return; } else if (torrent.getDownloadStatus() == Torrent.STATE_DOWNLOAD_METADATA) { updateLastActivity(); } } if (inactiveSeconds > 60) { if (myClient.isInterested() && myClient.isChoked()) { addStrike(2); updateLastActivity(); } } if (inactiveSeconds > 90) {// 1.5 Minute, We are getting close to // timeout D: if (myClient.isInterested()) { getBitTorrentSocket().queueMessage(new MessageKeepAlive()); } } if (inactiveSeconds > 180) {// 3 Minutes, We've hit the timeout mark socket.close(); } } /** * Adds a download or upload job to the peer * @param job * @param type */ public void addJob(Job job, PeerDirection type) { getClientByDirection(type).addJob(job); } /** * Removes the download or upload job from the peer * @param job * @param type */ public void removeJob(Job job, PeerDirection type) { getClientByDirection(type).removeJob(job); } /** * Add a value to the pending Messages count * * @param i * The count to add */ public synchronized void addToPendingMessages(int i) { pendingMessages += i; } @Override public String toString() { if (socket != null) { return socket.toString(); } else { return "UNCONNECTED"; } } public void setStatus(String s) { status = s; } public void setClientName(String clientName) { this.clientName = clientName; } public String getClientName() { return clientName; } public String getStatus() { return status; } public void updateLastActivity() { lastActivity = System.currentTimeMillis(); } /** * A callback method which gets invoked when the torrent starts a new phase */ public void onTorrentPhaseChange() { if (torrent.getDownloadStatus() == Torrent.STATE_DOWNLOAD_DATA) { haveState.setSize(JMath.ceilDivision(torrent.getFiles().getPieceCount(), 8)); } } public boolean isWorking() { return getWorkQueueSize(PeerDirection.Download) > 0; } public int getFreeWorkTime() { return Math.max(0, getRequestLimit() - getWorkQueueSize(PeerDirection.Download)); } /** * Gets the amount of pieces the client still needs to send * @return */ public int getWorkQueueSize(PeerDirection direction) { return getClientByDirection(direction).getQueueSize(); } /** * Cancels all pieces */ public void cancelAllPieces() { synchronized (this) { if (getWorkQueueSize(PeerDirection.Download) > 0) { Object[] keys = myClient.getKeySet().toArray(); for (int i = 0; i < keys.length; i++) { Job job = (Job) keys[i]; torrent.getFiles().getPiece(job.getPieceIndex()) .reset(job.getBlockIndex()); } myClient.clearJobs(); } } } /** * Registers that this peer has the given piece * @param pieceIndex the piece to marked as "have" */ public void havePiece(int pieceIndex) { haveState.havePiece(pieceIndex, torrent.getDownloadStatus() == Torrent.STATE_DOWNLOAD_METADATA); } /** * Checks if the peer has the piece with the given index * @param pieceIndex the piece to check for * @return returns true when the peer has the piece otherwise false */ public boolean hasPiece(int pieceIndex) { return haveState.hasPiece(pieceIndex); } public void setTorrent(Torrent torrent) throws IllegalStateException { if (this.torrent != null) { throw new IllegalStateException("Peer is already bound to a torrent"); } this.torrent = torrent; } public long getLastActivity() { return lastActivity; } public Torrent getTorrent() { return torrent; } @Override public int compareTo(Peer p) { int myValue = getCompareValue(); int theirValue = p.getCompareValue(); return myValue - theirValue; } private int getCompareValue() { return (getWorkQueueSize(PeerDirection.Download) * 5000) + haveState.countHavePieces() + socket.getDownloadRate(); } /** * Adds an amount of strikes to the peer * * @param i */ public synchronized void addStrike(int i) { if (strikes + i < 0) { strikes = 0; } else { strikes += i; } } /** * Sets the amount of requests this peer can support at most * @param absoluteRequestLimit */ public void setAbsoluteRequestLimit(int absoluteRequestLimit) { this.absoluteRequestLimit = absoluteRequestLimit; } /** * Sets the amount of requests we think this peer can handle properly.<br/> * This amount will be limited by {@link #absoluteRequestLimit} * @param requestLimit */ public void setRequestLimit(int requestLimit) { if (requestLimit < 0) { // This wouldn't make any sense return; } this.requestLimit = Math.min(requestLimit, absoluteRequestLimit); } public void setChoked(PeerDirection direction, boolean choked) { Client client = getClientByDirection(direction); if (choked) { client.choke(); } else { client.unchoke(); } } public void setInterested(PeerDirection direction, boolean interested) { Client client = getClientByDirection(direction); if (interested) { client.interested(); } else { client.uninterested(); } } @Override public boolean equals(Object o) { if (o instanceof Peer) { Peer p = (Peer) o; return (p.toString().equals(toString())); } else { return false; } } /** * Adds flags to a string based on the state of a peer<br/> * Possible Flags:<br/> * U - Uses uTP T - Uses TCP I - Is Interested C - Is Choked * * @return */ public String getFlags() { String flags = socket.getConnectionFlag(); if (peerClient.isInterested()) { flags += "I"; } if (peerClient.isChoked()) { flags += "C"; } return flags; } public Logger getLogger() { return log; } /** * Gets the extensions which are supported by this peer * @return the extensions of this peer */ public Extensions getExtensions() { return extensions; } /** * Gets the amount of requests we are allowed to make to this peer * @return the maximum amount of concurrent requests we can make to this peer */ public int getRequestLimit() { return requestLimit; } public boolean isInterested(PeerDirection direction) { return getClientByDirection(direction).isInterested(); } public boolean isChoked(PeerDirection direction) { return getClientByDirection(direction).isChoked(); } private Client getClientByDirection(PeerDirection type) { switch (type) { case Download: return myClient; case Upload: return peerClient; } return null; } /** * Gets the amount of pieces this peer has * @return returns the amount of pieces which this peer has */ public int countHavePieces() { return haveState.countHavePieces(); } /** * Gets the socket handler which handles the socket of this peer * @return */ public BitTorrentSocket getBitTorrentSocket() { return socket; } /** * Requests to queue the next piece in the socket for sending */ public void queueNextPieceForSending() { if (myClient.getQueueSize() == 0 || pendingMessages > 0) { return; } Job request = peerClient.getNextJob(); peerClient.removeJob(request); addToPendingMessages(1); DiskJob sendBlock = new DiskJobSendBlock(this, request.getPieceIndex(), request.getBlockIndex(), request.getLength() ); torrent.addDiskJob(sendBlock); } }
package org.lwjgl.demo.nuklear; import org.lwjgl.glfw.GLFWErrorCallback; import org.lwjgl.nuklear.*; import org.lwjgl.opengl.*; import org.lwjgl.stb.*; import org.lwjgl.system.Callback; import org.lwjgl.system.MemoryStack; import org.lwjgl.system.Platform; import java.io.IOException; import java.nio.*; import static org.lwjgl.demo.util.IOUtil.*; import static org.lwjgl.glfw.Callbacks.*; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.nuklear.Nuklear.*; import static org.lwjgl.opengl.ARBDebugOutput.*; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL12.*; import static org.lwjgl.opengl.GL13.*; import static org.lwjgl.opengl.GL14.*; import static org.lwjgl.opengl.GL15.*; import static org.lwjgl.opengl.GL20.*; import static org.lwjgl.opengl.GL30.*; import static org.lwjgl.opengl.GL43.*; import static org.lwjgl.stb.STBTruetype.*; import static org.lwjgl.system.MemoryStack.*; import static org.lwjgl.system.MemoryUtil.*; public class GLFWDemo { private static final int NK_BUFFER_DEFAULT_INITIAL_SIZE = 4 * 1024; private static final int MAX_VERTEX_BUFFER = 512 * 1024; private static final int MAX_ELEMENT_BUFFER = 128 * 1024; private static final NkAllocator ALLOCATOR; static { ALLOCATOR = NkAllocator.create(); ALLOCATOR.alloc((handle, old, size) -> { long mem = nmemAlloc(size); if ( mem == NULL ) throw new OutOfMemoryError(); return mem; }); ALLOCATOR.mfree((handle, ptr) -> nmemFree(ptr)); } public static void main(String[] args) { new GLFWDemo().run(); } private final ByteBuffer ttf; private long win; private int width, height; private int display_width, display_height; private NkContext ctx = NkContext.create(); private NkUserFont default_font = NkUserFont.create(); private NkBuffer cmds = NkBuffer.create(); private NkDrawNullTexture null_texture = NkDrawNullTexture.create(); private int vbo, vao, ebo; private int prog; private int vert_shdr; private int frag_shdr; private int uniform_tex; private int uniform_proj; private final Demo demo = new Demo(); private final Calculator calc = new Calculator(); public GLFWDemo() { try { this.ttf = ioResourceToByteBuffer("demo/FiraSans.ttf", 160 * 1024); } catch (IOException e) { throw new RuntimeException(e); } } private void run() { GLFWErrorCallback.createPrint().set(); if ( !glfwInit() ) throw new IllegalStateException("Unable to initialize glfw"); glfwDefaultWindowHints(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); if ( Platform.get() == Platform.MACOSX ) glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE); int WINDOW_WIDTH = 640; int WINDOW_HEIGHT = 640; win = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "GLFW Nuklear Demo", NULL, NULL); if ( win == NULL ) throw new RuntimeException("Failed to create the GLFW window"); glfwMakeContextCurrent(win); GLCapabilities caps = GL.createCapabilities(); Callback debugProc = GLUtil.setupDebugMessageCallback(); if ( caps.OpenGL43 ) glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_OTHER, GL_DEBUG_SEVERITY_NOTIFICATION, (IntBuffer)null, false); else if ( caps.GL_KHR_debug ) { KHRDebug.glDebugMessageControl( KHRDebug.GL_DEBUG_SOURCE_API, KHRDebug.GL_DEBUG_TYPE_OTHER, KHRDebug.GL_DEBUG_SEVERITY_NOTIFICATION, (IntBuffer)null, false ); } else if ( caps.GL_ARB_debug_output ) glDebugMessageControlARB(GL_DEBUG_SOURCE_API_ARB, GL_DEBUG_TYPE_OTHER_ARB, GL_DEBUG_SEVERITY_LOW_ARB, (IntBuffer)null, false); NkContext ctx = nk_glfw3_init(win); int BITMAP_W = 1024; int BITMAP_H = 1024; int FONT_HEIGHT = 18; int fontTexID = glGenTextures(); STBTTFontinfo fontInfo = STBTTFontinfo.create(); STBTTPackedchar.Buffer cdata = STBTTPackedchar.create(95); float scale; float descent; try ( MemoryStack stack = stackPush() ) { stbtt_InitFont(fontInfo, ttf); scale = stbtt_ScaleForPixelHeight(fontInfo, FONT_HEIGHT); IntBuffer d = stack.mallocInt(1); stbtt_GetFontVMetrics(fontInfo, null, d, null); descent = d.get(0) * scale; ByteBuffer bitmap = memAlloc(BITMAP_W * BITMAP_H); STBTTPackContext pc = STBTTPackContext.mallocStack(stack); stbtt_PackBegin(pc, bitmap, BITMAP_W, BITMAP_H, 0, 1, null); stbtt_PackSetOversampling(pc, 4, 4); stbtt_PackFontRange(pc, ttf, 0, FONT_HEIGHT, 32, cdata); stbtt_PackEnd(pc); // Convert R8 to RGBA8 ByteBuffer texture = memAlloc(BITMAP_W * BITMAP_H * 4); for ( int i = 0; i < bitmap.capacity(); i++ ) texture.putInt((bitmap.get(i) << 24) | 0x00FFFFFF); texture.flip(); glBindTexture(GL_TEXTURE_2D, fontTexID); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, BITMAP_W, BITMAP_H, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); memFree(texture); memFree(bitmap); } default_font .width((handle, h, text, len) -> { float text_width = 0; try ( MemoryStack stack = stackPush() ) { IntBuffer unicode = stack.mallocInt(1); int glyph_len = nnk_utf_decode(text, memAddress(unicode), len); int text_len = glyph_len; if ( glyph_len == 0 ) return 0; IntBuffer advance = stack.mallocInt(1); while ( text_len <= len && glyph_len != 0 ) { if ( unicode.get(0) == NK_UTF_INVALID ) break; /* query currently drawn glyph information */ stbtt_GetCodepointHMetrics(fontInfo, unicode.get(0), advance, null); text_width += advance.get(0) * scale; /* offset next glyph */ glyph_len = nnk_utf_decode(text + text_len, memAddress(unicode), len - text_len); text_len += glyph_len; } } return text_width; }) .height(FONT_HEIGHT) .query((handle, font_height, glyph, codepoint, next_codepoint) -> { try ( MemoryStack stack = stackPush() ) { FloatBuffer x = stack.floats(0.0f); FloatBuffer y = stack.floats(0.0f); STBTTAlignedQuad q = STBTTAlignedQuad.malloc(); IntBuffer advance = memAllocInt(1); stbtt_GetPackedQuad(cdata, BITMAP_W, BITMAP_H, codepoint - 32, x, y, q, false); stbtt_GetCodepointHMetrics(fontInfo, codepoint, advance, null); NkUserFontGlyph ufg = NkUserFontGlyph.create(glyph); ufg.width(q.x1() - q.x0()); ufg.height(q.y1() - q.y0()); ufg.offset().set(q.x0(), q.y0() + (FONT_HEIGHT + descent)); ufg.xadvance(advance.get(0) * scale); ufg.uv(0).set(q.s0(), q.t0()); ufg.uv(1).set(q.s1(), q.t1()); memFree(advance); q.free(); } }) .texture().id(fontTexID); nk_style_set_font(ctx, default_font); while ( !glfwWindowShouldClose(win) ) { /* Input */ nk_glfw3_new_frame(); demo.layout(ctx, 50, 50); calc.layout(ctx, 300, 50); try ( MemoryStack stack = stackPush() ) { FloatBuffer bg = stack.mallocFloat(4); nk_color_fv(bg, demo.background); IntBuffer width = stack.mallocInt(1); IntBuffer height = stack.mallocInt(1); glfwGetWindowSize(win, width, height); glViewport(0, 0, width.get(0), height.get(0)); glClearColor(bg.get(0), bg.get(1), bg.get(2), bg.get(3)); glClear(GL_COLOR_BUFFER_BIT); /* IMPORTANT: `nk_glfw_render` modifies some global OpenGL state * with blending, scissor, face culling, depth test and viewport and * defaults everything back into a default state. * Make sure to either a.) save and restore or b.) reset your own state after * rendering the UI. */ nk_glfw3_render(NK_ANTI_ALIASING_ON, MAX_VERTEX_BUFFER, MAX_ELEMENT_BUFFER); glfwSwapBuffers(win); } } nk_glfw3_shutdown(); glfwFreeCallbacks(win); if ( debugProc != null ) debugProc.free(); glfwTerminate(); glfwSetErrorCallback(null).free(); } private void nk_glfw3_device_create() { String NK_SHADER_VERSION = Platform.get() == Platform.MACOSX ? "#version 150\n" : "#version 300 es\n"; String vertex_shader = NK_SHADER_VERSION + "uniform mat4 ProjMtx;\n" + "in vec2 Position;\n" + "in vec2 TexCoord;\n" + "in vec4 Color;\n" + "out vec2 Frag_UV;\n" + "out vec4 Frag_Color;\n" + "void main() {\n" + " Frag_UV = TexCoord;\n" + " Frag_Color = Color;\n" + " gl_Position = ProjMtx * vec4(Position.xy, 0, 1);\n" + "}\n"; String fragment_shader = NK_SHADER_VERSION + "precision mediump float;\n" + "uniform sampler2D Texture;\n" + "in vec2 Frag_UV;\n" + "in vec4 Frag_Color;\n" + "out vec4 Out_Color;\n" + "void main(){\n" + " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" + "}\n"; nk_buffer_init(cmds, ALLOCATOR, NK_BUFFER_DEFAULT_INITIAL_SIZE); prog = glCreateProgram(); vert_shdr = glCreateShader(GL_VERTEX_SHADER); frag_shdr = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(vert_shdr, vertex_shader); glShaderSource(frag_shdr, fragment_shader); glCompileShader(vert_shdr); glCompileShader(frag_shdr); if ( glGetShaderi(vert_shdr, GL_COMPILE_STATUS) != GL_TRUE ) throw new IllegalStateException(); if ( glGetShaderi(frag_shdr, GL_COMPILE_STATUS) != GL_TRUE ) throw new IllegalStateException(); glAttachShader(prog, vert_shdr); glAttachShader(prog, frag_shdr); glLinkProgram(prog); if ( glGetProgrami(prog, GL_LINK_STATUS) != GL_TRUE ) throw new IllegalStateException(); uniform_tex = glGetUniformLocation(prog, "Texture"); uniform_proj = glGetUniformLocation(prog, "ProjMtx"); int attrib_pos = glGetAttribLocation(prog, "Position"); int attrib_uv = glGetAttribLocation(prog, "TexCoord"); int attrib_col = glGetAttribLocation(prog, "Color"); { // buffer setup vbo = glGenBuffers(); ebo = glGenBuffers(); vao = glGenVertexArrays(); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); glEnableVertexAttribArray(attrib_pos); glEnableVertexAttribArray(attrib_uv); glEnableVertexAttribArray(attrib_col); glVertexAttribPointer(attrib_pos, 2, GL_FLOAT, false, NkDrawVertex.SIZEOF, NkDrawVertex.POS); glVertexAttribPointer(attrib_uv, 2, GL_FLOAT, false, NkDrawVertex.SIZEOF, NkDrawVertex.UV); glVertexAttribPointer(attrib_col, 4, GL_UNSIGNED_BYTE, true, NkDrawVertex.SIZEOF, NkDrawVertex.COL); } { // null texture setup int nullTexID = glGenTextures(); null_texture.texture().id(nullTexID); null_texture.uv().set(0.5f, 0.5f); glBindTexture(GL_TEXTURE_2D, nullTexID); try ( MemoryStack stack = stackPush() ) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, stack.ints(0xFFFFFFFF)); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } glBindTexture(GL_TEXTURE_2D, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindVertexArray(0); } private NkContext nk_glfw3_init(long win) { glfwSetScrollCallback(win, (window, xoffset, yoffset) -> nk_input_scroll(ctx, (float)yoffset)); glfwSetCharCallback(win, (window, codepoint) -> nk_input_unicode(ctx, codepoint)); glfwSetKeyCallback(win, (window, key, scancode, action, mods) -> { switch ( key ) { case GLFW_KEY_ESCAPE: glfwSetWindowShouldClose(window, true); break; case GLFW_KEY_DELETE: nk_input_key(ctx, NK_KEY_DEL, action == GLFW_PRESS); break; case GLFW_KEY_ENTER: nk_input_key(ctx, NK_KEY_ENTER, action == GLFW_PRESS); break; case GLFW_KEY_TAB: nk_input_key(ctx, NK_KEY_TAB, action == GLFW_PRESS); break; case GLFW_KEY_BACKSPACE: nk_input_key(ctx, NK_KEY_BACKSPACE, action == GLFW_PRESS); break; case GLFW_KEY_UP: nk_input_key(ctx, NK_KEY_UP, action == GLFW_PRESS); break; case GLFW_KEY_DOWN: nk_input_key(ctx, NK_KEY_DOWN, action == GLFW_PRESS); break; case GLFW_KEY_HOME: nk_input_key(ctx, NK_KEY_TEXT_START, action == GLFW_PRESS); break; case GLFW_KEY_END: nk_input_key(ctx, NK_KEY_TEXT_END, action == GLFW_PRESS); break; case GLFW_KEY_LEFT_SHIFT: case GLFW_KEY_RIGHT_SHIFT: nk_input_key(ctx, NK_KEY_SHIFT, action == GLFW_PRESS); break; case GLFW_KEY_LEFT_CONTROL: case GLFW_KEY_RIGHT_CONTROL: if ( action == GLFW_PRESS ) { nk_input_key(ctx, NK_KEY_COPY, glfwGetKey(window, GLFW_KEY_C) == GLFW_PRESS); nk_input_key(ctx, NK_KEY_PASTE, glfwGetKey(window, GLFW_KEY_P) == GLFW_PRESS); nk_input_key(ctx, NK_KEY_CUT, glfwGetKey(window, GLFW_KEY_X) == GLFW_PRESS); nk_input_key(ctx, NK_KEY_TEXT_UNDO, glfwGetKey(window, GLFW_KEY_Z) == GLFW_PRESS); nk_input_key(ctx, NK_KEY_TEXT_REDO, glfwGetKey(window, GLFW_KEY_R) == GLFW_PRESS); nk_input_key(ctx, NK_KEY_TEXT_WORD_LEFT, glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS); nk_input_key(ctx, NK_KEY_TEXT_WORD_RIGHT, glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS); nk_input_key(ctx, NK_KEY_TEXT_LINE_START, glfwGetKey(window, GLFW_KEY_B) == GLFW_PRESS); nk_input_key(ctx, NK_KEY_TEXT_LINE_END, glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS); } else { nk_input_key(ctx, NK_KEY_LEFT, glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS); nk_input_key(ctx, NK_KEY_RIGHT, glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS); nk_input_key(ctx, NK_KEY_COPY, false); nk_input_key(ctx, NK_KEY_PASTE, false); nk_input_key(ctx, NK_KEY_CUT, false); nk_input_key(ctx, NK_KEY_SHIFT, false); } break; } }); glfwSetCursorPosCallback(win, (window, xpos, ypos) -> nk_input_motion(ctx, (int)xpos, (int)ypos)); glfwSetMouseButtonCallback(win, (window, button, action, mods) -> { try ( MemoryStack stack = stackPush() ) { DoubleBuffer cx = stack.mallocDouble(1); DoubleBuffer cy = stack.mallocDouble(1); glfwGetCursorPos(window, cx, cy); int x = (int)cx.get(0); int y = (int)cy.get(0); int nkButton; switch ( button ) { case GLFW_MOUSE_BUTTON_RIGHT: nkButton = NK_BUTTON_RIGHT; break; case GLFW_MOUSE_BUTTON_MIDDLE: nkButton = NK_BUTTON_MIDDLE; break; default: nkButton = NK_BUTTON_LEFT; } nk_input_button(ctx, nkButton, x, y, action == GLFW_PRESS); } }); nk_init(ctx, ALLOCATOR, null); ctx.clip().copy((handle, text, len) -> { if ( len == 0 ) return; try ( MemoryStack stack = stackPush() ) { ByteBuffer str = stack.malloc(len + 1); memCopy(text, memAddress(str), len); str.put(len, (byte)0); glfwSetClipboardString(win, str); } }); ctx.clip().paste((handle, edit) -> { long text = nglfwGetClipboardString(win); if ( text != NULL ) nnk_textedit_paste(edit, text, nnk_strlen(text)); }); nk_glfw3_device_create(); return ctx; } private void nk_glfw3_new_frame() { try ( MemoryStack stack = stackPush() ) { IntBuffer w = stack.mallocInt(1); IntBuffer h = stack.mallocInt(1); glfwGetWindowSize(win, w, h); width = w.get(0); height = h.get(0); glfwGetFramebufferSize(win, w, h); display_width = w.get(0); display_height = h.get(0); } nk_input_begin(ctx); glfwPollEvents(); if ( ctx.input().mouse().grab() ) glfwSetInputMode(win, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); else if ( ctx.input().mouse().grabbed() ) glfwSetCursorPos(win, ctx.input().mouse().prev().x(), ctx.input().mouse().prev().y()); else if ( ctx.input().mouse().ungrab() ) glfwSetInputMode(win, GLFW_CURSOR, GLFW_CURSOR_NORMAL); nk_input_end(ctx); } private void nk_glfw3_render(int AA, int max_vertex_buffer, int max_element_buffer) { try ( MemoryStack stack = stackPush() ) { // setup global state glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); glActiveTexture(GL_TEXTURE0); // setup program glUseProgram(prog); glUniform1i(uniform_tex, 0); glUniformMatrix4fv(uniform_proj, false, stack.floats( 2.0f / width, 0.0f, 0.0f, 0.0f, 0.0f, -2.0f / height, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f )); glViewport(0, 0, display_width, display_height); } { // convert from command queue into draw list and draw to screen // allocate vertex and element buffer glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); glBufferData(GL_ARRAY_BUFFER, max_vertex_buffer, GL_STREAM_DRAW); glBufferData(GL_ELEMENT_ARRAY_BUFFER, max_element_buffer, GL_STREAM_DRAW); // load draw vertices & elements directly into vertex + element buffer ByteBuffer vertices = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY, max_vertex_buffer, null); ByteBuffer elements = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_WRITE_ONLY, max_element_buffer, null); try ( MemoryStack stack = stackPush() ) { // fill converting configuration NkConvertConfig config = NkConvertConfig.callocStack(stack) .global_alpha(1.0f) .shape_AA(AA) .line_AA(AA) .circle_segment_count(22) .curve_segment_count(22) .arc_segment_count(22) .null_texture(null_texture); // setup buffers to load vertices and elements NkBuffer vbuf = NkBuffer.mallocStack(stack); NkBuffer ebuf = NkBuffer.mallocStack(stack); nk_buffer_init_fixed(vbuf, vertices/*, max_vertex_buffer*/); nk_buffer_init_fixed(ebuf, elements/*, max_element_buffer*/); nk_convert(ctx, cmds, vbuf, ebuf, config); } glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); glUnmapBuffer(GL_ARRAY_BUFFER); // iterate over and execute each draw command float fb_scale_x = (float)display_width / (float)width; float fb_scale_y = (float)display_height / (float)height; long offset = NULL; for ( NkDrawCommand cmd = nk__draw_begin(ctx, cmds); cmd != null; cmd = nk__draw_next(cmd, cmds, ctx) ) { if ( cmd.elem_count() == 0 ) continue; glBindTexture(GL_TEXTURE_2D, cmd.texture().id()); glScissor( (int)(cmd.clip_rect().x() * fb_scale_x), (int)((height - (int)(cmd.clip_rect().y() + cmd.clip_rect().h())) * fb_scale_y), (int)(cmd.clip_rect().w() * fb_scale_x), (int)(cmd.clip_rect().h() * fb_scale_y) ); glDrawElements(GL_TRIANGLES, cmd.elem_count(), GL_UNSIGNED_SHORT, offset); offset += cmd.elem_count() * 2; } nk_clear(ctx); } // default OpenGL state glUseProgram(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindVertexArray(0); glDisable(GL_BLEND); glDisable(GL_SCISSOR_TEST); } private void nk_glfw3_device_destroy() { glDetachShader(prog, vert_shdr); glDetachShader(prog, frag_shdr); glDeleteShader(vert_shdr); glDeleteShader(frag_shdr); glDeleteProgram(prog); glDeleteTextures(default_font.texture().id()); glDeleteTextures(null_texture.texture().id()); glDeleteBuffers(vbo); glDeleteBuffers(ebo); nk_buffer_free(cmds); } private void nk_glfw3_shutdown() { ctx.clip().copy().free(); ctx.clip().paste().free(); nk_free(ctx); nk_glfw3_device_destroy(); default_font.query().free(); default_font.width().free(); calc.numberFilter.free(); ALLOCATOR.alloc().free(); ALLOCATOR.mfree().free(); } }
/** * This is an implementation of the Bron-Kerbosch algorithm for * finding maximal cliques in a graph. It makes use of our fully * extended language. * * @author Elvis Stansvik <elvstone@gmail.com> */ //EXT:IWE //EXT:NBD //EXT:CLE //EXT:CGT //EXT:CGE //EXT:CEQ //EXT:CNE //EXT:BDJ class FullLanguageBronKerbosch { public static void main(String[] args) { Graph g; boolean r; // Unused g = new Graph(); r = g.init(5); r = g.addEdge(0, 1); r = g.addEdge(0, 2); r = g.addEdge(2, 3); r = g.addEdge(1, 2); r = g.addEdge(3, 4); r = g.printMaxCliques(); } } // Very basic graph class. class Graph { int[] edges; int size; Set set; // Set utility methods. // Initialize the graph with N vertices. public boolean init(int N) { int i; size = N; set = new Set(); edges = new int[size * size]; i = 0; while (i <= N * N - 1) { // CLE. edges[i] = 0; i = i + 1; } return true; } // Add an edge between u and v. public boolean addEdge(int u, int v) { edges[u * size + v] = 1; edges[v * size + u] = 1; return true; } // Prints each maximal clique followed by 666. public boolean printMaxCliques() { int[] R; int[] P; int[] X; int i; boolean r; R = new int[size]; P = new int[size]; X = new int[size]; i = 0; while (R.length > i) { // CGT R[i] = 0; P[i] = 1; X[i] = 0; i = i + 1; } r = this.bronKerbosch(R, P, X); return true; } /* * The Bron-Kerbosch algorithm. * * Prints each maximal clique followed by 666. * * R is the current clique, P are candidates vertices for inclusion into R, * X are the forbidden (already evaluated vertices). */ public boolean bronKerbosch(int[] R, int[] P, int[] X) { int v; if (set.isEmpty(P) && set.isEmpty(X)) { // IWE // R is a maximal clique. boolean r; // NBD r = set.print(R); System.out.println(666); } // For each vertex v in P. v = 0; while (v < P.length) { if (P[v] == 1) { // CEQ boolean r; r = this.bronKerbosch( set.add(R, v), set.intersect(P, edges, v * size), set.intersect(X, edges, v * size)); P = set.del(P, v); X = set.add(X, v); } v = v + 1; } return true; } } /* * Some (slow) methods for treating arrays as sets. * * E.g. a[i] = 1 ==> i is in set a, a[i] = 0 ==> i is not in set a. */ class Set { // Return a copy of s with e added. public int[] add(int[] s, int e) { int[] result; int i; result = new int[s.length]; i = 0; while (result.length - 1 >= i) { // CGE if (s[i] == 1) result[i] = 1; i = i + 1; } result[e] = 1; return result; } // Return a copy of s with e removed. public int[] del(int[] s, int e) { int[] result; int i; result = new int[s.length]; i = 0; while (i < result.length) { if (s[i] == 1) result[i] = 1; i = i + 1; } result[e] = 0; return result; } // Return the union of a and b[bOffset..bOffset + a.length - 1] public int[] union(int[] a, int[] b, int bOffset) { int[] result; int i; result = new int[a.length]; i = 0; while (i < result.length) { if (a[i] == 1 || b[i + bOffset] == 1) // BDJ result[i] = 1; else result[i] = 0; i = i + 1; } return result; } // Return the intersection of a and b[bOffset..bOffset + a.length - 1] public int[] intersect(int[] a, int[] b, int bOffset) { int[] result; int i; result = new int[a.length]; i = 0; while (i < result.length) { if (a[i] == 1 && b[i + bOffset] == 1) result[i] = 1; else result[i] = 0; i = i + 1; } return result; } // Returns true if a is an empty set. public boolean isEmpty(int[] a) { int i; boolean result; result = true; i = 0; while (i < a.length) { if (a[i] == 1) result = false; i = i + 1; } return result; } // Prints the elements of s. public boolean print(int[] s) { int i; i = 0; while (i < s.length) { if (s[i] != 0) // CNE System.out.println(i); i = i + 1; } return true; } }
package nl.mpi.arbil.data; import nl.mpi.arbil.userstorage.SessionStorage; import org.junit.Before; import nl.mpi.arbil.ArbilTest; import nl.mpi.arbil.util.TreeHelper; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.util.ArrayList; import java.io.File; import java.io.FileOutputStream; import nl.mpi.arbil.MockSessionStorage; import java.io.IOException; import java.io.OutputStreamWriter; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * * @author Twan Goosen <twan.goosen@mpi.nl> */ public class TreeHelperTest extends ArbilTest { @Before public void setUp() throws Exception { inject(); } @Test public void testLocationsList() throws Exception { assertEquals(0, getTreeHelper().getLocalCorpusNodes().length); addToLocalTreeFromResource("/nl/mpi/arbil/data/testfiles/\u0131md\u0131test.imdi"); assertEquals(1, getTreeHelper().getLocalCorpusNodes().length); assertFalse(((ArbilDataNode) getTreeHelper().getLocalCorpusNodes()[0]).fileNotFound); } @Override protected SessionStorage newSessionStorage() { return new MockSessionStorage() { @Override public final String[] loadStringArray(String filename) throws IOException { File currentConfigFile = new File(getStorageDirectory(), filename + ".config"); if (currentConfigFile.exists()) { ArrayList<String> stringArrayList = new ArrayList<String>(); FileInputStream fstream = new FileInputStream(currentConfigFile); DataInputStream in = new DataInputStream(fstream); try { BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF8")); try { String strLine; while ((strLine = br.readLine()) != null) { stringArrayList.add(strLine); } } finally { br.close(); } } finally { in.close(); fstream.close(); } return stringArrayList.toArray(new String[]{}); } return null; } @Override public final void saveStringArray(String filename, String[] storableValue) throws IOException { // save the location list to a text file that admin-users can read and hand edit if they really want to File destinationConfigFile = new File(getStorageDirectory(), filename + ".config"); File tempConfigFile = new File(getStorageDirectory(), filename + ".config.tmp"); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempConfigFile), "UTF8")); for (String currentString : storableValue) { out.write(currentString + "\r\n"); } out.close(); destinationConfigFile.delete(); tempConfigFile.renameTo(destinationConfigFile); } @Override public boolean pathIsInsideCache(File fullTestFile) { return true; } @Override public boolean pathIsInFavourites(File fullTestFile) { return false; } }; } }
package org.pocketcampus.core.plugin; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.charset.Charset; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.pocketcampus.core.debug.Reporter; import org.pocketcampus.core.exception.ServerException; import org.pocketcampus.shared.utils.StringUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; /** * Server core. Singleton * @author Jonas * @author Florian * @status working, incomplete */ public class Router extends HttpServlet { /** Serialization crap */ private static final long serialVersionUID = 2912684020711306666L; private Core core_; /** Gson instance to serialize resulting objects */ private static Gson gson_; /** Displays nice HTML pages */ private static Reporter reporter_; @Override public void init() throws ServletException { super.init(); core_ = Core.getInstance(); reporter_ = new Reporter(); // .setPrettyPrinting() gson_ = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss Z").setPrettyPrinting().create(); String[] plugins = new String[] { "org.pocketcampus.plugin.food.Food", "org.pocketcampus.plugin.map.Map", "org.pocketcampus.plugin.transport.Transport", "org.pocketcampus.plugin.test.Test", "org.pocketcampus.plugin.bikes.Bikes" }; // XXX for(String s : plugins) { try { initClass(s); } catch (ServerException e) { e.printStackTrace(); } } } /** * Handle the GET request * Final because the children do not have to handle the request by themselves */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("Request: " + request.getRequestURL()); Enumeration<String> ps = request.getParameterNames(); while(ps.hasMoreElements()) { String s = ps.nextElement(); System.out.println("Parameter: " + s + " -> " + request.getParameter(s)); } // URL used to access the servlet //String path = request.getPathInfo(); String path = request.getServletPath(); if(path != null && path.endsWith(".do")) { path = path.substring(0, path.length() - 3); } // Request without any command if(path == null || path.equals("/")) { reporter_.statusReport(response, core_.getPluginList(), core_.getMethodList()); return; } // Get the object and the method connected to the command try { IPlugin obj = getObject(path); Method m = getMethod(obj, path); invoke(request, response, obj, m); } catch (ServerException e) { reporter_.errorReport(response, e); } } /** * Creates an instance of the plugin from its path. * @param plugin path * @return instance of the plugin * @throws ServerException */ private IPlugin getObject(String path) throws ServerException { String className = getClassNameFromPath(path); if(className==null || className.equals("")) { throw new ServerException("No method provided."); } IPlugin obj = initClass(className); if(obj == null) { throw new ServerException("Object initialization failed."); } return obj; } /** * Extracts the class name of a class path. * @param class path of a plugin * @return class name */ private String getClassNameFromPath(String path) { String split[] = path.split("/"); if(split.length > 1) { return "org.pocketcampus.plugin." + split[1].toLowerCase() + "." + StringUtils.capitalize(split[1]); } return null; } /** * Invokes the plugin. * @param request * @param response * @param obj * @param m * @throws IOException */ private void invoke(HttpServletRequest request, HttpServletResponse response, IPlugin obj, Method m) throws IOException { // Create the arguments to pass to the method Object arglist[] = new Object[1]; //request.setCharacterEncoding("iso-8859-15"); request.setCharacterEncoding("UTF-8"); Charset charset = Charset.forName("UTF-8"); arglist[0] = request; try { // Sets the content type final String encoding = "text/html; charset=UTF-8"; response.setContentType(encoding); // Invokes the method Object ret = m.invoke(obj, arglist); String json = gson_.toJson(ret); // Fixes the damn encoding //json = charset.encode(json).toString(); // Puts the method content into the response response.getWriter().println(json); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Get the name of the method that has to be invoked using the URL * @param path path from the request * @return the name of the request if exist, or the name of the default method */ private String getMethodNameFromPath(String path) { String split[] = path.split("/"); if(split.length < 3 || split[2] == null) { return null; } else { return split[2]; } } private Method getMethod(IPlugin obj, String path) throws ServerException { String className = getClassNameFromPath(path); String methodName = getMethodNameFromPath(path); if(methodName == null || !core_.getMethodList().get(className).containsKey(methodName)) { throw new ServerException("Method <b>"+ methodName +"</b> not found in package <b>"+ className +"</b>. Mispelled?"); } Method m = core_.getMethodList().get(className).get(methodName); return m; } private IPlugin initClass(String className) throws ServerException { // Checks if the class already exists IPlugin clazz = core_.getPluginList().get(className); if(clazz != null) { return clazz; } IPlugin obj = null; try { Class<?> c = Class.forName(className); Constructor<?> ct = c.getConstructor(); // Check that the class implements the correct interface Class<?>[] interfaces = c.getInterfaces(); boolean ok = false; for(Class<?> i : interfaces) { ok = ok || i.equals(IPlugin.class); } if(!ok) { return null; } obj = (IPlugin) ct.newInstance(new Object[0]); core_.getPluginList().put(className, obj); // Get the methods from the class Method methlist[] = c.getDeclaredMethods(); HashMap<String, Method> classMethods = new HashMap<String, Method>(); for(Method m : methlist) { // Check if the programmer wants to put the method public if(m.isAnnotationPresent(PublicMethod.class)) { classMethods.put(m.getName(), m); } } core_.getMethodList().put(className, classMethods); } catch (ClassNotFoundException e) { throw new ServerException("The class <b>" + className + "</b> was not found. Mispelled?"); } catch (IllegalArgumentException e) { throw new ServerException("IllegalArgumentException"); } catch (InstantiationException e) { throw new ServerException("InstantiationException"); } catch (IllegalAccessException e) { throw new ServerException("IllegalAccessException"); } catch (InvocationTargetException e) { throw new ServerException("InvocationTargetException"); } catch (SecurityException e) { throw new ServerException("SecurityException"); } catch (NoSuchMethodException e) { throw new ServerException("NoSuchMethodException"); } return obj; } }
package stroom.config; import com.google.common.reflect.ClassPath; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import stroom.config.app.AppConfig; import stroom.config.app.AppConfigModule; import stroom.config.app.AppConfigModule.ConfigHolder; import stroom.config.app.Config; import stroom.config.app.YamlUtil; import stroom.config.common.CommonDbConfig; import stroom.config.common.DbConfig; import stroom.config.common.HasDbConfig; import stroom.db.util.DbUtil; import stroom.util.config.PropertyUtil; import stroom.util.logging.LogUtil; import stroom.util.shared.IsConfig; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; class TestAppConfigModule { private static final Logger LOGGER = LoggerFactory.getLogger(TestAppConfigModule.class); private static final String MODIFIED_JDBC_DRIVER = "modified.jdbc.driver"; private final static String STROOM_PACKAGE_PREFIX = "stroom."; @AfterEach void afterEach() { // FileUtil.deleteContents(tmpDir); } @Test void testCommonDbConfig() throws IOException { Path devYamlPath = getDevYamlPath(); LOGGER.debug("dev yaml path: {}", devYamlPath.toAbsolutePath()); // Modify the value on the common connection pool so it gets applied to all other config objects final Config modifiedConfig = YamlUtil.readConfig(devYamlPath); modifiedConfig.getAppConfig().getCommonDbConfig().getConnectionPoolConfig().setPrepStmtCacheSize(250); int currentValue = modifiedConfig.getAppConfig().getCommonDbConfig().getConnectionPoolConfig().getPrepStmtCacheSize(); int newValue = currentValue + 1000; modifiedConfig.getAppConfig().getCommonDbConfig().getConnectionPoolConfig().setPrepStmtCacheSize(newValue); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { install(new AppConfigModule(new ConfigHolder() { @Override public AppConfig getAppConfig() { return modifiedConfig.getAppConfig(); } @Override public Path getConfigFile() { return devYamlPath; } })); } }); AppConfig appConfig = injector.getInstance(AppConfig.class); CommonDbConfig commonDbConfig = injector.getInstance(CommonDbConfig.class); Assertions.assertThat(commonDbConfig.getConnectionPoolConfig().getPrepStmtCacheSize()) .isEqualTo(newValue); // Make sure all the getters that return a HasDbConfig have the modified conn value Arrays.stream(appConfig.getClass().getDeclaredMethods()) .filter(method -> method.getName().startsWith("get")) .filter(method -> HasDbConfig.class.isAssignableFrom(method.getReturnType())) .map(method -> { try { return (HasDbConfig) method.invoke(appConfig); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } }) .forEach(hasDbConfig -> { final DbConfig mergedConfig = new DbConfig(); DbUtil.copyConfig(commonDbConfig, mergedConfig); DbUtil.copyConfig(hasDbConfig.getDbConfig(), mergedConfig); Assertions.assertThat(mergedConfig.getConnectionConfig()) .isEqualTo(commonDbConfig.getConnectionConfig()); Assertions.assertThat(mergedConfig.getConnectionPoolConfig()) .isEqualTo(commonDbConfig.getConnectionPoolConfig()); Assertions.assertThat(mergedConfig.getConnectionPoolConfig().getPrepStmtCacheSize()) .isEqualTo(newValue); }); } /** * IMPORTANT: This test must be run from stroom-app so it can see all the other modules */ @Test void testIsConfigPresence() throws IOException { final AppConfig appConfig = new AppConfig(); Predicate<String> packageNameFilter = name -> name.startsWith(STROOM_PACKAGE_PREFIX) && !name.contains("shaded"); Predicate<Class<?>> classFilter = clazz -> { return !clazz.equals(IsConfig.class) && !clazz.equals(AppConfig.class); }; LOGGER.info("Finding all IsConfig classes"); // Find all classes that implement IsConfig final ClassLoader classLoader = getClass().getClassLoader(); final Set<Class<?>> isConfigClasses = ClassPath.from(classLoader).getAllClasses() .stream() .filter(classInfo -> packageNameFilter.test(classInfo.getPackageName())) .map(ClassPath.ClassInfo::load) .filter(classFilter) .filter(IsConfig.class::isAssignableFrom) .peek(clazz -> { LOGGER.debug(clazz.getSimpleName()); }) .collect(Collectors.toSet()); LOGGER.info("Finding all classes in object tree"); // Find all stroom. classes in the AppConfig tree, i.e. config POJOs final Set<Class<?>> configClasses = new HashSet<>(); PropertyUtil.walkObjectTree( appConfig, prop -> packageNameFilter.test(prop.getValueClass().getPackageName()), prop -> { // make sure we have a getter and a setter Assertions.assertThat(prop.getGetter()) .as(LogUtil.message("{} {}", prop.getParentObject().getClass().getSimpleName(), prop.getGetter().getName())) .isNotNull(); Assertions.assertThat(prop.getSetter()) .as(LogUtil.message("{} {}", prop.getParentObject().getClass().getSimpleName(), prop.getSetter().getName())) .isNotNull(); Class<?> valueClass = prop.getValueClass(); if (classFilter.test(valueClass)) { configClasses.add(prop.getValueClass()); } }); // Make sure all config classes implement IsConfig and all IsConfig classes are in // the AppConfig tree. If there is a mismatch then it may be due to the getter/setter not // being public in the config class, else the config class may not be a property in the // AppConfig object tree Assertions.assertThat(isConfigClasses) .containsAll(configClasses); Assertions.assertThat(configClasses) .containsAll(isConfigClasses); } static Path getDevYamlPath() throws FileNotFoundException { // Load dev.yaml final String codeSourceLocation = TestAppConfigModule.class.getProtectionDomain().getCodeSource().getLocation().getPath(); Path path = Paths.get(codeSourceLocation); while (path != null && !path.getFileName().toString().equals("stroom-app")) { path = path.getParent(); } if (path != null) { path = path.getParent(); path = path.resolve("stroom-app"); path = path.resolve("dev.yml"); } if (path == null) { throw new FileNotFoundException("Unable to find dev.yml"); } return path; } }
package algorithms.imageProcessing; import algorithms.util.PairInt; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import java.util.logging.Logger; /** * * @author nichole */ public class ZhangSuenLineThinner extends AbstractLineThinner { private static final int[][] nbrs = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}}; private static int[][][] nbrGroups = {{{0, 2, 4}, {2, 4, 6}}, {{0, 2, 6}, {0, 4, 6}}}; protected boolean useLineDrawingMode = false; protected boolean debug = false; private Logger log = Logger.getLogger(this.getClass().getName()); /** * for images which are already line drawings, that is images such as * maps with only lines, or for block images, use this to avoid a gap filling * stage that fills single pixel gaps surrounded by non-zero pixels. * (Else, the filter applies such a gap filling algorithm to help avoid * creating bubbles in thick lines). */ @Override public void useLineDrawingMode() { useLineDrawingMode = true; } @Override public void setDebug(boolean setToDebug) { debug = setToDebug; } @Override public void applyFilter(final GreyscaleImage input) { GreyscaleImage summed = sumOver8Neighborhood(input); Set<PairInt> points = new HashSet<PairInt>(); for (int col = 0; col < input.getWidth(); col++) { for (int row = 0; row < input.getHeight(); row++) { if (input.getValue(col, row) > 0) { points.add(new PairInt(col, row)); } } } applyLineThinner(points, 0, input.getWidth(), 0, input.getHeight()); input.fill(0); for (PairInt p : points) { input.setValue(p.getX(), p.getY(), 1); } // make corrections for artifacts created for inclined lines /* can see a 3x3 hollow square. the correction should replace it with the diagonal of the exterior connecting slope. Is the artifact a product of the gaussian convolution size? If yes, would need to know the blur radius. */ correctForArtifacts(input); //correctForMinorOffsetsByIntensity(input, summed); } public void applyLineThinner(Set<PairInt> points, int minX, int maxX, int minY, int maxY) { // adapted from code at http://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm#Java boolean firstStep = false; boolean hasChanged; Set<PairInt> remove = new HashSet<PairInt>(); do { hasChanged = false; firstStep = !firstStep; for (int r = minY + 1; r < maxY - 1; r++) { for (int c = minX + 1; c < maxX - 1; c++) { PairInt uPoint = new PairInt(c, r); if (!points.contains(uPoint)) { continue; } int nn = numNeighbors(r, c, points); if (nn < 2 || nn > 6) { continue; } int nt = numTransitions(r, c, points); if (nt != 1) { continue; } if (!atLeastOneIsVacant(r, c, firstStep ? 0 : 1, points)) { continue; } remove.add(uPoint); } } if (!remove.isEmpty()) { for (PairInt p : remove) { points.remove(p); hasChanged = true; } remove.clear(); } } while (hasChanged || firstStep); } private int numNeighbors(int r, int c, Set<PairInt> points) { int count = 0; for (int i = 0; i < nbrs.length - 1; i++) { int x = c + nbrs[i][0]; int y = r + nbrs[i][1]; PairInt p = new PairInt(x, y); if (points.contains(p)) { count++; } else { int z = 1; } } return count; } /** * visits neighbors in counter-clockwise direction and looks for the * pattern 0:1 in the current and next neighbor. each such pattern * is counted as a transition. * @param r * @param c * @param points * @return */ static int numTransitions(int r, int c, Set<PairInt> points) { /* 5 4 3 1 6 2 0 7 0 1 -1 -1 0 1 */ int count = 0; for (int i = 0; i < nbrs.length - 1; i++) { int x = c + nbrs[i][0]; int y = r + nbrs[i][1]; PairInt p = new PairInt(x, y); if (!points.contains(p)) { int x2 = c + nbrs[i + 1][0]; int y2 = r + nbrs[i + 1][1]; PairInt p2 = new PairInt(x2, y2); if (points.contains(p2)) { count++; } } } return count; } /** * looking for 2 zeroes within the 4 neighborhood pattern of point (c,r). * @param r * @param c * @param step * @param points * @return */ static boolean atLeastOneIsVacant(int r, int c, int step, Set<PairInt> points) { int count = 0; int[][] group = nbrGroups[step]; for (int i = 0; i < 2; i++) { for (int j = 0; j < group[i].length; j++) { int[] nbr = nbrs[group[i][j]]; int x = c + nbr[0]; int y = r + nbr[1]; PairInt p = new PairInt(x, y); if (!points.contains(p)) { count++; break; } } } return (count > 1); } private void correctForArtifacts(GreyscaleImage input) { //correctForHoleArtifacts3(input); //correctForHoleArtifacts2(input); correctForHoleArtifacts1(input); correctForZigZag0(input); correctForZigZag1(input); correctForZigZag2(input); correctForZigZag3(input); correctForZigZag4(input); correctForLine0(input); } private void correctForZigZag0(GreyscaleImage input) { /* looking for pattern 0 0 2 0 # # 1 #* #< 0 0 # 0 0 -1 -1 0 1 2 and removing the topmost left #'s */ LinkedHashSet<PairInt> ones = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> zeroes = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> changeToZeroes = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> changeToOnes = new LinkedHashSet<PairInt>(); // y's are inverted here because sketch above is top left is (0,0) zeroes.add(new PairInt(0, -1)); zeroes.add(new PairInt(0, -2)); zeroes.add(new PairInt(1, 1)); zeroes.add(new PairInt(1, -2)); zeroes.add(new PairInt(2, 0)); zeroes.add(new PairInt(2, 1)); ones.add(new PairInt(-1, 1)); ones.add(new PairInt(1, -1)); ones.add(new PairInt(1, 0)); ones.add(new PairInt(2, -1)); changeToZeroes.add(new PairInt(1, 0)); int startValue = 1; replacePattern(input, zeroes, ones, changeToZeroes, changeToOnes, startValue); rotate90ThreeTimes(input, zeroes, ones, changeToZeroes, changeToOnes, startValue); } private void correctForZigZag1(GreyscaleImage input) { /* looking for pattern # 3 0 # 2 0 0 # 0 1 0 #* #< 0 0 # 0 -1 -1 0 1 2 and removing the topmost left #'s */ LinkedHashSet<PairInt> ones = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> zeroes = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> changeToZeroes = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> changeToOnes = new LinkedHashSet<PairInt>(); // y's are inverted here because sketch above is top left is (0,0) zeroes.add(new PairInt(-1, 0)); zeroes.add(new PairInt(-1, -1)); zeroes.add(new PairInt(0, -1)); zeroes.add(new PairInt(0, -2)); zeroes.add(new PairInt(2, 0)); zeroes.add(new PairInt(2, -1)); zeroes.add(new PairInt(1, 1)); ones.add(new PairInt(-1, 1)); ones.add(new PairInt(1, 0)); ones.add(new PairInt(1, -1)); ones.add(new PairInt(2, -2)); ones.add(new PairInt(2, -3)); changeToZeroes.add(new PairInt(1, 0)); int startValue = 1; replacePattern(input, zeroes, ones, changeToZeroes, changeToOnes, startValue); rotate90ThreeTimes(input, zeroes, ones, changeToZeroes, changeToOnes, startValue); } private void correctForZigZag2(GreyscaleImage input) { /* looking for pattern 0 0 0 # 1 0 #* # 0 0 0 # 0 -1 # 0 -2 -2 -1 0 1 2 and removing the topmost left #'s */ LinkedHashSet<PairInt> ones = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> zeroes = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> changeToZeroes = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> changeToOnes = new LinkedHashSet<PairInt>(); // y's are inverted here because sketch above is top left is (0,0) zeroes.add(new PairInt(-1, 1)); zeroes.add(new PairInt(-1, 0)); zeroes.add(new PairInt(-1, -1)); zeroes.add(new PairInt(0, 2)); zeroes.add(new PairInt(0, -1)); zeroes.add(new PairInt(1, 1)); zeroes.add(new PairInt(1, -1)); zeroes.add(new PairInt(2, 0)); ones.add(new PairInt(-1, 2)); ones.add(new PairInt(0, 1)); ones.add(new PairInt(1, 0)); ones.add(new PairInt(2, -1)); changeToZeroes.add(new PairInt(0, 0)); int startValue = 1; replacePattern(input, zeroes, ones, changeToZeroes, changeToOnes, startValue); rotate90ThreeTimes(input, zeroes, ones, changeToZeroes, changeToOnes, startValue); } private void correctForZigZag3(GreyscaleImage input) { /* looking for pattern 0 # 3 0 # 2 0 #< # 0 1 0 #* 0 0 # 0 0 -1 -2 -1 0 1 2 and removing the topmost left #'s */ LinkedHashSet<PairInt> ones = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> zeroes = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> changeToZeroes = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> changeToOnes = new LinkedHashSet<PairInt>(); // y's are inverted here because sketch above is top left is (0,0) zeroes.add(new PairInt(-1, 0)); zeroes.add(new PairInt(-1, -1)); zeroes.add(new PairInt(0, 1)); zeroes.add(new PairInt(0, -2)); zeroes.add(new PairInt(1, 1)); zeroes.add(new PairInt(1, 0)); zeroes.add(new PairInt(1, -3)); zeroes.add(new PairInt(2, -1)); ones.add(new PairInt(-1, 1)); ones.add(new PairInt(0, -1)); ones.add(new PairInt(1, -1)); ones.add(new PairInt(1, -2)); ones.add(new PairInt(2, -3)); changeToZeroes.add(new PairInt(0, -1)); int startValue = 1; replacePattern(input, zeroes, ones, changeToZeroes, changeToOnes, startValue); rotate90ThreeTimes(input, zeroes, ones, changeToZeroes, changeToOnes, startValue); } private void correctForZigZag4(GreyscaleImage input) { /* looking for pattern 3 # # 0 0 2 0 # 0 0 1 0 #* # # 0 0 0 0 0 # -1 -2 -1 0 1 2 and removing the topmost left #'s */ LinkedHashSet<PairInt> ones = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> zeroes = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> changeToZeroes = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> changeToOnes = new LinkedHashSet<PairInt>(); // y's are inverted here because sketch above is top left is (0,0) zeroes.add(new PairInt(-1, 1)); zeroes.add(new PairInt(-1, 0)); zeroes.add(new PairInt(-1, -1)); zeroes.add(new PairInt(0, 1)); zeroes.add(new PairInt(0, -2)); zeroes.add(new PairInt(1, 1)); zeroes.add(new PairInt(1, -1)); zeroes.add(new PairInt(1, -2)); zeroes.add(new PairInt(2, 1)); zeroes.add(new PairInt(2, -1)); ones.add(new PairInt(-2, -2)); ones.add(new PairInt(-1, -2)); ones.add(new PairInt(0, -1)); ones.add(new PairInt(1, 0)); ones.add(new PairInt(2, 0)); ones.add(new PairInt(3, 1)); changeToZeroes.add(new PairInt(0, 0)); int startValue = 1; replacePattern(input, zeroes, ones, changeToZeroes, changeToOnes, startValue); rotate90ThreeTimes(input, zeroes, ones, changeToZeroes, changeToOnes, startValue); } private void rotate90ThreeTimes(GreyscaleImage input, final LinkedHashSet<PairInt> zeroes, final LinkedHashSet<PairInt> ones, LinkedHashSet<PairInt> changeToZeroes, final LinkedHashSet<PairInt> changeToOnes, final int startCenterValue) { for (PairInt p : zeroes) { p.setX(-1 * p.getX()); } for (PairInt p : ones) { p.setX(-1 * p.getX()); } for (PairInt p : changeToZeroes) { p.setX(-1 * p.getX()); } for (PairInt p : changeToOnes) { p.setX(-1 * p.getX()); } replacePattern(input, zeroes, ones, changeToZeroes, changeToOnes, startCenterValue); for (PairInt p : zeroes) { p.setY(-1 * p.getY()); } for (PairInt p : ones) { p.setY(-1 * p.getY()); } for (PairInt p : changeToZeroes) { p.setY(-1 * p.getY()); } for (PairInt p : changeToOnes) { p.setY(-1 * p.getY()); } replacePattern(input, zeroes, ones, changeToZeroes, changeToOnes, startCenterValue); for (PairInt p : zeroes) { p.setX(-1 * p.getX()); } for (PairInt p : ones) { p.setX(-1 * p.getX()); } for (PairInt p : changeToZeroes) { p.setX(-1 * p.getX()); } for (PairInt p : changeToOnes) { p.setX(-1 * p.getX()); } replacePattern(input, zeroes, ones, changeToZeroes, changeToOnes, startCenterValue); } private void replacePattern(GreyscaleImage input, final LinkedHashSet<PairInt> zeroes, final LinkedHashSet<PairInt> ones, final LinkedHashSet<PairInt> changeToZeroes, final LinkedHashSet<PairInt> changeToOnes, final int startCenterValue) { int w = input.getWidth(); int h = input.getHeight(); for (int col = 0; col < w; col++) { for (int row = 0; row < h; row++) { int v = input.getValue(col, row); if (v != startCenterValue) { continue; } boolean foundPattern = true; for (PairInt p : zeroes) { int x = col + p.getX(); int y = row + p.getY(); if ((x < 0) || (y < 0) || (x > (w - 1)) || (y > (h - 1))) { //TODO: revisit this foundPattern = false; break; } int vz = input.getValue(x, y); if (vz != 0) { foundPattern = false; break; } } if (!foundPattern) { continue; } for (PairInt p : ones) { int x = col + p.getX(); int y = row + p.getY(); if ((x < 0) || (y < 0) || (x > (w - 1)) || (y > (h - 1))) { foundPattern = false; break; } int vz = input.getValue(x, y); if (vz != 1) { foundPattern = false; break; } } if (!foundPattern) { continue; } for (PairInt p : changeToZeroes) { int x = col + p.getX(); int y = row + p.getY(); if ((x < 0) || (y < 0) || (x > (w - 1)) || (y > (h - 1))) { continue; } input.setValue(x, y, 0); } for (PairInt p : changeToOnes) { int x = col + p.getX(); int y = row + p.getY(); if ((x < 0) || (y < 0) || (x > (w - 1)) || (y > (h - 1))) { continue; } input.setValue(x, y, 1); } } } } private void debugPrint(GreyscaleImage input, int xStart, int xStop, int yStart, int yStop) { StringBuilder sb = new StringBuilder(); for (int row = yStart; row <= yStop; row++) { sb.append(String.format("%3d: ", row)); for (int col = xStart; col <= xStop; col++) { sb.append(String.format(" %3d ", input.getValue(col, row))); } sb.append(String.format("\n")); } System.out.println(sb.toString()); } /** * removes a hole artifact in inclined lines. note that this should * probably be adjusted for gaussian convolution combined radius * if used outside of the gradientXY image produced by the * CannyEdgeFilter. * @param input */ private void correctForHoleArtifacts3(GreyscaleImage input) { /* looking for pattern 0 0 0 0 0 0 3 0 0 0 0 1 1 1 2 0 0 0 1 0 1 0 1 0 0 1 0* 1 1 0 0 0 1 0 1 1 0 0 -1 0 1 1 1 0 0 0 -2 0 1 0 0 0 0 0 -3 -3 -2 -1 0 1 2 3 and removing the topmost left #'s */ LinkedHashSet<PairInt> ones = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> zeroes = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> changeToZeroes = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> changeToOnes = new LinkedHashSet<PairInt>(); // y's are inverted here because sketch above is top left is (0,0) zeroes.add(new PairInt(-1, -1)); zeroes.add(new PairInt(-1, 1)); zeroes.add(new PairInt(1, -1)); zeroes.add(new PairInt(0, -2)); zeroes.add(new PairInt(1, 2)); zeroes.add(new PairInt(2, 2)); zeroes.add(new PairInt(2, 1)); zeroes.add(new PairInt(0, -3)); zeroes.add(new PairInt(1, -3)); zeroes.add(new PairInt(-1, -2)); zeroes.add(new PairInt(-1, -3)); zeroes.add(new PairInt(2, -3)); zeroes.add(new PairInt(-2, -3)); zeroes.add(new PairInt(-2, -2)); zeroes.add(new PairInt(-2, -1)); zeroes.add(new PairInt(-2, 0)); zeroes.add(new PairInt(-1, 3)); zeroes.add(new PairInt(0, 3)); zeroes.add(new PairInt(1, 3)); zeroes.add(new PairInt(2, 3)); zeroes.add(new PairInt(3, 3)); zeroes.add(new PairInt(3, 2)); zeroes.add(new PairInt(3, 1)); zeroes.add(new PairInt(3, 0)); zeroes.add(new PairInt(3, -1)); zeroes.add(new PairInt(-3, -3)); zeroes.add(new PairInt(-3, 2)); zeroes.add(new PairInt(-3, -1)); zeroes.add(new PairInt(-3, 0)); zeroes.add(new PairInt(-3, -1)); zeroes.add(new PairInt(-3, -2)); zeroes.add(new PairInt(-3, -3)); ones.add(new PairInt(0, 1)); ones.add(new PairInt(0, 2)); ones.add(new PairInt(0, -1)); ones.add(new PairInt(-1, 0)); ones.add(new PairInt(-1, 2)); ones.add(new PairInt(1, -2)); ones.add(new PairInt(1, 0)); ones.add(new PairInt(1, 1)); ones.add(new PairInt(2, -2)); ones.add(new PairInt(2, -1)); ones.add(new PairInt(2, 0)); ones.add(new PairInt(3, -2)); ones.add(new PairInt(-2, 1)); ones.add(new PairInt(-2, 2)); ones.add(new PairInt(-2, 3)); changeToZeroes.add(new PairInt(-2, 2)); changeToZeroes.add(new PairInt(-2, 1)); changeToZeroes.add(new PairInt(-1, 0)); changeToZeroes.add(new PairInt(0, -1)); changeToZeroes.add(new PairInt(1, -2)); changeToZeroes.add(new PairInt(2, -2)); changeToZeroes.add(new PairInt(2, 0)); changeToZeroes.add(new PairInt(1, 1)); changeToZeroes.add(new PairInt(0, 2)); int centralValue = 0; replacePattern(input, zeroes, ones, changeToZeroes, changeToOnes, centralValue); rotate90ThreeTimes(input, zeroes, ones, changeToZeroes, changeToOnes, centralValue); } /** * removes a hole artifact in inclined lines. note that this should * probably be adjusted for gaussian convolution combined radius * if used outside of the gradientXY image produced by the * CannyEdgeFilter. * @param input */ private void correctForHoleArtifacts2(GreyscaleImage input) { /* looking for pattern 0 0 0 0 0 0 3 0 0 0 1 1 1 2 0 0 1 0 1 0 1 0 1 0* 1 1 0 0 0 1 1 1 0 0 -1 0 1 0 0 0 0 -2 -2 -1 0 1 2 3 */ LinkedHashSet<PairInt> ones = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> zeroes = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> changeToZeroes = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> changeToOnes = new LinkedHashSet<PairInt>(); // y's are inverted here because sketch above is top left is (0,0) zeroes.add(new PairInt(0, 2)); zeroes.add(new PairInt(0, -2)); zeroes.add(new PairInt(-1, -1)); zeroes.add(new PairInt(-1, -2)); zeroes.add(new PairInt(-1, -3)); zeroes.add(new PairInt(0, -3)); zeroes.add(new PairInt(1, -3)); zeroes.add(new PairInt(1, -1)); zeroes.add(new PairInt(1, 2)); zeroes.add(new PairInt(2, -3)); zeroes.add(new PairInt(2, 1)); zeroes.add(new PairInt(2, 2)); zeroes.add(new PairInt(-2, -3)); zeroes.add(new PairInt(-2, -2)); zeroes.add(new PairInt(-2, -1)); zeroes.add(new PairInt(-2, 0)); zeroes.add(new PairInt(-2, 1)); zeroes.add(new PairInt(-2, 2)); zeroes.add(new PairInt(3, -3)); zeroes.add(new PairInt(3, -1)); zeroes.add(new PairInt(3, 0)); zeroes.add(new PairInt(3, 1)); zeroes.add(new PairInt(3, 2)); ones.add(new PairInt(0, -1)); ones.add(new PairInt(0, 1)); ones.add(new PairInt(-1, 0)); ones.add(new PairInt(-1, 1)); ones.add(new PairInt(-1, 2)); ones.add(new PairInt(1, -2)); ones.add(new PairInt(1, 0)); ones.add(new PairInt(1, 1)); ones.add(new PairInt(2, -2)); ones.add(new PairInt(2, -1)); ones.add(new PairInt(2, 0)); ones.add(new PairInt(3, -2)); changeToZeroes.add(new PairInt(-1, 0)); changeToZeroes.add(new PairInt(-1, 1)); changeToZeroes.add(new PairInt(0, -1)); changeToZeroes.add(new PairInt(1, -2)); changeToZeroes.add(new PairInt(1, 1)); changeToZeroes.add(new PairInt(2, -2)); changeToZeroes.add(new PairInt(2, 0)); int centralValue = 0; replacePattern(input, zeroes, ones, changeToZeroes, changeToOnes, centralValue); rotate90ThreeTimes(input, zeroes, ones, changeToZeroes, changeToOnes, centralValue); } private void correctForLine0(GreyscaleImage input) { /* looking for pattern # 2 # 0 1 0 0* # 0 0 # 0 -1 # -1 0 1 2 and removing the topmost left #'s */ LinkedHashSet<PairInt> ones = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> zeroes = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> changeToZeroes = new LinkedHashSet<PairInt>(); LinkedHashSet<PairInt> changeToOnes = new LinkedHashSet<PairInt>(); /* looking for pattern # 2 # 0 1 0 0* # 0 0 # 0 -1 # -2 -1 0 1 2 and removing the topmost left #'s */ // y's are inverted here because sketch above is top left is (0,0) zeroes.add(new PairInt(-1, 0)); zeroes.add(new PairInt(1, 1)); zeroes.add(new PairInt(1, -1)); zeroes.add(new PairInt(2, 0)); ones.add(new PairInt(0, 2)); ones.add(new PairInt(0, 1)); ones.add(new PairInt(0, -1)); ones.add(new PairInt(0, -2)); ones.add(new PairInt(1, 0)); changeToZeroes.add(new PairInt(1, 0)); changeToOnes.add(new PairInt(0, 0)); int startValue = 0; replacePattern(input, zeroes, ones, changeToZeroes, changeToOnes, startValue); rotate90ThreeTimes(input, zeroes, ones, changeToZeroes, changeToOnes, startValue); } private void correctForHoleArtifacts1(GreyscaleImage input) { /* look for pattern with hole in middle, fill the hole, then use boolean nullable = erosionFilter.process(input, input, neighborX, neighborY); 1 1 1 0* 1 0 1 -1 -2 -2 -1 0 1 2 */ ErosionFilter erosionFilter = new ErosionFilter(); int w = input.getWidth(); int h = input.getHeight(); int[] nbX = new int[]{-1, -1, 0, 1, 1, 1, 0, -1}; int[] nbY = new int[]{ 0, 1, 1, 1, 0, -1,-1, -1}; Set<PairInt> ones = new HashSet<PairInt>(); // y's are inverted here because sketch above is top left is (0,0) ones.add(new PairInt(-1, 0)); ones.add(new PairInt(0, -1)); ones.add(new PairInt(0, 1)); ones.add(new PairInt(1, 0)); int centralValue = 0; for (int col = 0; col < w; col++) { for (int row = 0; row < h; row++) { int v = input.getValue(col, row); if (v != centralValue) { continue; } boolean foundPattern = true; for (PairInt p : ones) { int x = col + p.getX(); int y = row + p.getY(); if ((x < 0) || (y < 0) || (x > (w - 1)) || (y > (h - 1))) { foundPattern = false; break; } int vz = input.getValue(x, y); if (vz != 1) { foundPattern = false; break; } } if (!foundPattern) { continue; } // set the center pixel to '1' and visit each in 8 neighbor // hood to determine if can null it input.setValue(col, row, 1); for (int k = 0; k < nbX.length; k++) { int x = col + nbX[k]; int y = row + nbY[k]; if ((x < 0) || (y < 0) || (x > (w - 1)) || (y > (h - 1))) { continue; } boolean nullable = erosionFilter.process(input, input, x, y); if (nullable) { input.setValue(x, y, 0); } } } } } protected GreyscaleImage sumOver8Neighborhood(GreyscaleImage img) { GreyscaleImage summed = img.copyImage(); int[] dxs = new int[]{-1, -1, 0, 1, 1, 1, 0, -1}; int[] dys = new int[]{ 0, -1, -1, -1, 0, 1, 1, 1}; int w = img.getWidth(); int h = img.getHeight(); // for each pixel, sum it's neighbors for (int col = 0; col < w; col++) { for (int row = 0; row < h; row++) { int sum = 0; for (int nIdx = 0; nIdx < dxs.length; nIdx++) { int x = dxs[nIdx] + col; int y = dys[nIdx] + row; if ((x<0) || (y<0) || (x>(w-1)) || (y>(h-1))) { continue; } int v = img.getValue(x, y); sum += v; } summed.setValue(col, row, sum); } } return summed; } private void correctForMinorOffsetsByIntensity(GreyscaleImage input, GreyscaleImage summed) { int[] dxs = new int[]{-1, -1, 0, 1, 1, 1, 0, -1}; int[] dys = new int[]{ 0, -1, -1, -1, 0, 1, 1, 1}; ErosionFilter erosionFilter = new ErosionFilter(); int w = input.getWidth(); int h = input.getHeight(); for (int col = 1; col < (w - 1); col++) { for (int row = 1; row < (h - 1); row++) { int v = input.getValue(col, row); if (v == 0) { continue; } int vSum = summed.getValue(col, row); if (vSum == 8) { continue; } if (erosionFilter.doesDisconnect(input, col, row)) { continue; } int maxSum = vSum; int maxIdx = -1; for (int nIdx = 0; nIdx < dxs.length; nIdx++) { int x = dxs[nIdx] + col; int y = dys[nIdx] + row; if ((x<0) || (y<0) || (x>(w-1)) || (y>(h-1))) { continue; } // only compare the neighbors which are swappable if (input.getValue(x, y) == 0) { int sum = summed.getValue(x, y); if (sum > maxSum) { maxIdx = nIdx; maxSum = sum; } } } if (maxIdx > -1) { int x = dxs[maxIdx] + col; int y = dys[maxIdx] + row; input.setValue(x, y, 1); input.setValue(col, row, 0); } } } } }
package cn.cerc.mis.task; import cn.cerc.core.IHandle; import cn.cerc.core.TDateTime; import cn.cerc.db.cache.Redis; import cn.cerc.db.core.ServerConfig; import cn.cerc.mis.core.Application; import cn.cerc.mis.other.BufferType; import cn.cerc.mis.rds.StubHandle; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.time.LocalTime; import java.util.Calendar; @Component @Slf4j @Deprecated // StartTaskDefault public class ProcessTimerTask implements ApplicationContextAware { // 120 private static final int C_SCHEDULE_HOUR = 0; private static boolean isRunning = false; private static final String One_O_Clock = "01:00:00"; private static String lock; private IHandle handle; private ApplicationContext context; @Scheduled(fixedDelay = 3 * 1000) public void run() { if (!ServerConfig.enableTaskService()) { return; } Calendar calendar = Calendar.getInstance(); if (!isRunning) { isRunning = true; if (C_SCHEDULE_HOUR == calendar.get(Calendar.HOUR_OF_DAY)) { try { report(); } catch (Exception e) { e.printStackTrace(); } } else if (ServerConfig.enableTaskService()) { try { runTask(); } catch (Exception e) { e.printStackTrace(); } } isRunning = false; } else { log.info(""); } } private void runTask() { init(); String str = TDateTime.Now().getTime(); if (str.equals(lock)) { return; } lock = str; for (String beanId : context.getBeanNamesForType(AbstractTask.class)) { AbstractTask task = getTask(handle, beanId); if (task == null) { continue; } try { String timeNow = TDateTime.Now().getTime().substring(0, 5); if (!"".equals(task.getTime()) && !task.getTime().equals(timeNow)) { continue; } int timeOut = task.getInterval(); String buffKey = String.format("%d.%s.%s.%s", BufferType.getObject.ordinal(), ServerConfig.getAppName(), this.getClass().getName(), task.getClass().getName()); if (Redis.get(buffKey) != null) { continue; } Redis.set(buffKey, "ok", timeOut); if (task.getInterval() > 1) { log.debug(" {}", task.getClass().getName()); } task.execute(); } catch (Exception e) { e.printStackTrace(); log.error(e.getMessage()); } } } /** * handle */ private void init() { if (handle == null) { handle = new StubHandle(); } // 1token LocalTime now = LocalTime.now().withNano(0); if (One_O_Clock.equals(now.toString())) { if (handle != null) { handle.close(); handle = null; } log.warn("{} ", TDateTime.Now()); handle = new StubHandle(); } } public static AbstractTask getTask(IHandle handle, String beanId) { AbstractTask task = Application.getBean(beanId, AbstractTask.class); if (task != null) { task.setHandle(handle); } return task; } private void report() { return; } @Override public void setApplicationContext(ApplicationContext context) throws BeansException { this.context = context; } }
package bd.edu.daffodilvarsity.studentdatabase; import java.awt.Color; import java.util.ArrayList; import java.util.Objects; import javax.swing.JFrame; import javax.swing.JOptionPane; public class AddPanel extends javax.swing.JPanel { public AddPanel() { initComponents(); panelVisiblity(true, false, false, false); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { welcomePanel = new javax.swing.JPanel(); welcomeText = new javax.swing.JLabel(); findButton = new javax.swing.JPanel(); jLabel23 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); viewResultButton = new javax.swing.JPanel(); jLabel40 = new javax.swing.JLabel(); jSeparator3 = new javax.swing.JSeparator(); admitStudentButton = new javax.swing.JPanel(); jLabel41 = new javax.swing.JLabel(); jSeparator4 = new javax.swing.JSeparator(); dropStudentButton = new javax.swing.JPanel(); jSeparator9 = new javax.swing.JSeparator(); jLabel43 = new javax.swing.JLabel(); findStudentField = new javax.swing.JTextField(); findStudentErrorText = new javax.swing.JLabel(); addStudentPanel = new javax.swing.JPanel(); jLabel11 = new javax.swing.JLabel(); jSeparator21 = new javax.swing.JSeparator(); jLabel12 = new javax.swing.JLabel(); nameLabel4 = new javax.swing.JLabel(); addStudentFullName = new javax.swing.JTextField(); jSeparator22 = new javax.swing.JSeparator(); idLabel4 = new javax.swing.JLabel(); addStudentID = new javax.swing.JTextField(); jSeparator23 = new javax.swing.JSeparator(); addFathersNameField = new javax.swing.JTextField(); jLabel24 = new javax.swing.JLabel(); jSeparator24 = new javax.swing.JSeparator(); genderLabel4 = new javax.swing.JLabel(); jSeparator25 = new javax.swing.JSeparator(); motherLabel4 = new javax.swing.JLabel(); addFemaleCheck = new javax.swing.JRadioButton(); addMaleCheck = new javax.swing.JRadioButton(); createProfileButtonPanel4 = new javax.swing.JPanel(); jLabel26 = new javax.swing.JLabel(); showSelectedCoursesCount = new javax.swing.JLabel(); addMothersNameField = new javax.swing.JTextField(); fatherLabel4 = new javax.swing.JLabel(); mainFromAdmit = new javax.swing.JPanel(); jLabel38 = new javax.swing.JLabel(); jSeparator5 = new javax.swing.JSeparator(); cse101CheckBox = new javax.swing.JCheckBox(); cse201CheckBox = new javax.swing.JCheckBox(); cse301CheckBox = new javax.swing.JCheckBox(); cse102CheckBox = new javax.swing.JCheckBox(); cse202CheckBox = new javax.swing.JCheckBox(); cse302CheckBox = new javax.swing.JCheckBox(); cse103CheckBox = new javax.swing.JCheckBox(); cse203CheckBox = new javax.swing.JCheckBox(); cse303CheckBox = new javax.swing.JCheckBox(); jLabel13 = new javax.swing.JLabel(); jLabel25 = new javax.swing.JLabel(); showSelectedLabCoursesCount = new javax.swing.JLabel(); cse111CheckBox = new javax.swing.JCheckBox(); cse112CheckBox = new javax.swing.JCheckBox(); cse211CheckBox = new javax.swing.JCheckBox(); cse212CheckBox = new javax.swing.JCheckBox(); cse311CheckBox = new javax.swing.JCheckBox(); cse312CheckBox = new javax.swing.JCheckBox(); updateStudentPanel = new javax.swing.JPanel(); updateSearchStudentPanel = new javax.swing.JPanel(); findStudentDropField = new javax.swing.JTextField(); mainFromDrop1 = new javax.swing.JPanel(); jLabel46 = new javax.swing.JLabel(); jSeparator13 = new javax.swing.JSeparator(); dropStudentSearchButton1 = new javax.swing.JPanel(); dropStudentSearchButtonLabel1 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jSeparator2 = new javax.swing.JSeparator(); updateFindStudentErrorText = new javax.swing.JLabel(); updateFoundStudentPanel = new javax.swing.JPanel(); cancelFromUpdate = new javax.swing.JPanel(); jSeparator15 = new javax.swing.JSeparator(); cancelFromUpdateLabel = new javax.swing.JLabel(); backToMainFromUpdateLabel = new javax.swing.JLabel(); dropStudentSearchButton2 = new javax.swing.JPanel(); dropStudentSearchButtonLabel2 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); nameLabel5 = new javax.swing.JLabel(); nameLabel6 = new javax.swing.JLabel(); nameLabel7 = new javax.swing.JLabel(); nameLabel8 = new javax.swing.JLabel(); nameLabel9 = new javax.swing.JLabel(); jLabel14 = new javax.swing.JLabel(); jLabel19 = new javax.swing.JLabel(); courseBName = new javax.swing.JLabel(); nameLabel11 = new javax.swing.JLabel(); jSeparator26 = new javax.swing.JSeparator(); updateID = new javax.swing.JTextField(); updateFullName = new javax.swing.JTextField(); updateMothersName = new javax.swing.JTextField(); updateFathersName = new javax.swing.JTextField(); updateGender = new javax.swing.JTextField(); nameLabel12 = new javax.swing.JLabel(); courseAName = new javax.swing.JLabel(); courseDName = new javax.swing.JLabel(); courseCName = new javax.swing.JLabel(); courseFName = new javax.swing.JLabel(); courseEName = new javax.swing.JLabel(); courseDNameGrade = new javax.swing.JLabel(); courseANameGrade = new javax.swing.JLabel(); courseBNameGrade = new javax.swing.JLabel(); courseCNameGrade = new javax.swing.JLabel(); courseFNameGrade = new javax.swing.JLabel(); courseENameGrade = new javax.swing.JLabel(); jLabel20 = new javax.swing.JLabel(); jLabel21 = new javax.swing.JLabel(); courseBGrade = new javax.swing.JTextField(); courseAGrade = new javax.swing.JTextField(); courseDGrade = new javax.swing.JTextField(); courseCGrade = new javax.swing.JTextField(); courseFGrade = new javax.swing.JTextField(); courseEGrade = new javax.swing.JTextField(); updateButton = new javax.swing.JPanel(); dropStudentSearchButtonLabel3 = new javax.swing.JLabel(); resultPanel = new javax.swing.JPanel(); resultSearchPanel = new javax.swing.JPanel(); jLabel15 = new javax.swing.JLabel(); resultSearchButton1 = new javax.swing.JPanel(); jLabel36 = new javax.swing.JLabel(); mainFromResult1 = new javax.swing.JPanel(); jLabel42 = new javax.swing.JLabel(); jSeparator7 = new javax.swing.JSeparator(); resultSearchField = new javax.swing.JTextField(); jSeparator10 = new javax.swing.JSeparator(); resultFindStudentErrorText = new javax.swing.JLabel(); resultViewPanel = new javax.swing.JPanel(); backFromResultView = new javax.swing.JPanel(); backLabelResult = new javax.swing.JLabel(); backSepResult = new javax.swing.JSeparator(); backFromMainLabelResult = new javax.swing.JLabel(); backFromMainSepResult = new javax.swing.JSeparator(); jLabel22 = new javax.swing.JLabel(); nameLabel10 = new javax.swing.JLabel(); nameLabel13 = new javax.swing.JLabel(); nameLabel14 = new javax.swing.JLabel(); nameLabel15 = new javax.swing.JLabel(); nameLabel16 = new javax.swing.JLabel(); jLabel27 = new javax.swing.JLabel(); jLabel28 = new javax.swing.JLabel(); resultCourseBName = new javax.swing.JLabel(); nameLabel17 = new javax.swing.JLabel(); jSeparator27 = new javax.swing.JSeparator(); resultUpdateID = new javax.swing.JTextField(); resultFullName = new javax.swing.JTextField(); resultMothersName = new javax.swing.JTextField(); resultFathersName = new javax.swing.JTextField(); resultGender = new javax.swing.JTextField(); nameLabel18 = new javax.swing.JLabel(); resultCourseAName = new javax.swing.JLabel(); resultCourseDName = new javax.swing.JLabel(); resultCourseCName = new javax.swing.JLabel(); resultCourseFName = new javax.swing.JLabel(); resultCourseEName = new javax.swing.JLabel(); resultCourseDNameGrade = new javax.swing.JLabel(); resultCourseANameGrade = new javax.swing.JLabel(); resultCourseBNameGrade = new javax.swing.JLabel(); resultCourseCNameGrade = new javax.swing.JLabel(); resultCourseFNameGrade = new javax.swing.JLabel(); resultCourseENameGrade = new javax.swing.JLabel(); jLabel29 = new javax.swing.JLabel(); jLabel30 = new javax.swing.JLabel(); resultCourseBGrade = new javax.swing.JTextField(); resultCGPA = new javax.swing.JTextField(); resultCourseDGrade = new javax.swing.JTextField(); resultCourseCGrade = new javax.swing.JTextField(); resultCourseFGrade = new javax.swing.JTextField(); resultCourseEGrade = new javax.swing.JTextField(); jLabel31 = new javax.swing.JLabel(); resultCourseAGrade = new javax.swing.JTextField(); jLabel32 = new javax.swing.JLabel(); resultRemarks = new javax.swing.JTextField(); setBackground(new java.awt.Color(36, 47, 65)); setForeground(new java.awt.Color(204, 204, 204)); setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); welcomePanel.setBackground(new java.awt.Color(36, 47, 65)); welcomePanel.setForeground(new java.awt.Color(204, 204, 204)); welcomePanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); welcomeText.setFont(new java.awt.Font("Century Gothic", 1, 24)); // NOI18N welcomeText.setForeground(new java.awt.Color(255, 255, 255)); welcomeText.setText("Welcome to Student Database"); welcomePanel.add(welcomeText, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 60, 420, 50)); findButton.setBackground(new java.awt.Color(50, 132, 255)); findButton.setForeground(new java.awt.Color(255, 255, 255)); findButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { findButtonMouseClicked(evt); } }); findButton.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel23.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N jLabel23.setForeground(new java.awt.Color(255, 255, 255)); jLabel23.setText("FIND"); findButton.add(jLabel23, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 0, 70, 40)); welcomePanel.add(findButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 250, 90, 40)); jSeparator1.setForeground(new java.awt.Color(255, 255, 255)); jSeparator1.setFont(new java.awt.Font("Dialog", 0, 10)); // NOI18N welcomePanel.add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 290, 340, 10)); viewResultButton.setBackground(new java.awt.Color(36, 47, 65)); viewResultButton.setForeground(new java.awt.Color(255, 255, 255)); viewResultButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { viewResultButtonMouseClicked(evt); } }); viewResultButton.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel40.setFont(new java.awt.Font("Century Gothic", 0, 16)); // NOI18N jLabel40.setForeground(new java.awt.Color(255, 255, 255)); jLabel40.setText("RESULT"); viewResultButton.add(jLabel40, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 70, 30)); jSeparator3.setForeground(new java.awt.Color(255, 255, 255)); viewResultButton.add(jSeparator3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 40, 80, 20)); welcomePanel.add(viewResultButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 450, 100, 50)); admitStudentButton.setBackground(new java.awt.Color(36, 47, 65)); admitStudentButton.setForeground(new java.awt.Color(255, 255, 255)); admitStudentButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { admitStudentButtonMouseClicked(evt); } }); admitStudentButton.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel41.setFont(new java.awt.Font("Century Gothic", 0, 16)); // NOI18N jLabel41.setForeground(new java.awt.Color(255, 255, 255)); jLabel41.setText("ADMIT"); admitStudentButton.add(jLabel41, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 70, 30)); jSeparator4.setForeground(new java.awt.Color(255, 255, 255)); admitStudentButton.add(jSeparator4, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 40, 70, 20)); welcomePanel.add(admitStudentButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 450, 90, 50)); dropStudentButton.setBackground(new java.awt.Color(36, 47, 65)); dropStudentButton.setForeground(new java.awt.Color(255, 255, 255)); dropStudentButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { dropStudentButtonMouseClicked(evt); } }); dropStudentButton.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jSeparator9.setForeground(new java.awt.Color(255, 255, 255)); dropStudentButton.add(jSeparator9, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 40, 80, 20)); jLabel43.setFont(new java.awt.Font("Century Gothic", 0, 16)); // NOI18N jLabel43.setForeground(new java.awt.Color(255, 255, 255)); jLabel43.setText("UPDATE"); dropStudentButton.add(jLabel43, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 70, 30)); welcomePanel.add(dropStudentButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 450, 90, 50)); findStudentField.setBackground(new java.awt.Color(36, 47, 65)); findStudentField.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N findStudentField.setForeground(new java.awt.Color(255, 255, 255)); findStudentField.setText("Enter ID to find"); findStudentField.setBorder(null); findStudentField.setCaretColor(new java.awt.Color(255, 255, 255)); findStudentField.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { findStudentFieldMouseClicked(evt); } }); welcomePanel.add(findStudentField, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 250, 330, 40)); findStudentErrorText.setBackground(new java.awt.Color(255, 0, 153)); findStudentErrorText.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N findStudentErrorText.setForeground(new java.awt.Color(255, 0, 51)); welcomePanel.add(findStudentErrorText, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 310, 430, 40)); add(welcomePanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); addStudentPanel.setBackground(new java.awt.Color(36, 47, 65)); addStudentPanel.setForeground(new java.awt.Color(204, 204, 204)); addStudentPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel11.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N jLabel11.setForeground(new java.awt.Color(255, 255, 255)); jLabel11.setText("STUDENT DETAILS"); addStudentPanel.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 30, -1, -1)); jSeparator21.setForeground(new java.awt.Color(255, 255, 255)); jSeparator21.setOrientation(javax.swing.SwingConstants.VERTICAL); addStudentPanel.add(jSeparator21, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 80, 20, 390)); jLabel12.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N jLabel12.setForeground(new java.awt.Color(255, 255, 255)); jLabel12.setText("SELECT COURSES"); addStudentPanel.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 30, -1, -1)); nameLabel4.setFont(new java.awt.Font("Century Gothic", 1, 16)); // NOI18N nameLabel4.setForeground(new java.awt.Color(255, 255, 255)); nameLabel4.setText("FULL NAME"); addStudentPanel.add(nameLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 80, -1, -1)); addStudentFullName.setBackground(new java.awt.Color(36, 47, 65)); addStudentFullName.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N addStudentFullName.setForeground(new java.awt.Color(204, 204, 204)); addStudentFullName.setText("Enter name"); addStudentFullName.setBorder(null); addStudentFullName.setCaretColor(new java.awt.Color(255, 255, 255)); addStudentFullName.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { addStudentFullNameMouseClicked(evt); } }); addStudentPanel.add(addStudentFullName, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 100, 200, 40)); jSeparator22.setForeground(new java.awt.Color(255, 255, 255)); addStudentPanel.add(jSeparator22, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 140, 200, -1)); idLabel4.setFont(new java.awt.Font("Century Gothic", 1, 16)); // NOI18N idLabel4.setForeground(new java.awt.Color(255, 255, 255)); idLabel4.setText("ID"); addStudentPanel.add(idLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 150, -1, -1)); addStudentID.setBackground(new java.awt.Color(36, 47, 65)); addStudentID.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N addStudentID.setForeground(new java.awt.Color(204, 204, 204)); addStudentID.setText("Enter student ID"); addStudentID.setBorder(null); addStudentID.setCaretColor(new java.awt.Color(255, 255, 255)); addStudentID.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { addStudentIDMouseClicked(evt); } }); addStudentPanel.add(addStudentID, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 170, 200, 40)); jSeparator23.setForeground(new java.awt.Color(255, 255, 255)); addStudentPanel.add(jSeparator23, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 210, 200, -1)); addFathersNameField.setBackground(new java.awt.Color(36, 47, 65)); addFathersNameField.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N addFathersNameField.setForeground(new java.awt.Color(204, 204, 204)); addFathersNameField.setText("Enter name"); addFathersNameField.setBorder(null); addFathersNameField.setCaretColor(new java.awt.Color(255, 255, 255)); addFathersNameField.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { addFathersNameFieldMouseClicked(evt); } }); addStudentPanel.add(addFathersNameField, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 250, 200, 40)); jLabel24.setFont(new java.awt.Font("Century Gothic", 0, 16)); // NOI18N jLabel24.setForeground(new java.awt.Color(255, 255, 255)); jLabel24.setText("SELECTED COURSES:"); addStudentPanel.add(jLabel24, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 190, -1, -1)); jSeparator24.setForeground(new java.awt.Color(255, 255, 255)); addStudentPanel.add(jSeparator24, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 290, 200, -1)); genderLabel4.setFont(new java.awt.Font("Century Gothic", 1, 16)); // NOI18N genderLabel4.setForeground(new java.awt.Color(255, 255, 255)); genderLabel4.setText("GENDER"); addStudentPanel.add(genderLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 390, -1, -1)); jSeparator25.setForeground(new java.awt.Color(255, 255, 255)); addStudentPanel.add(jSeparator25, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 370, 200, -1)); motherLabel4.setFont(new java.awt.Font("Century Gothic", 1, 16)); // NOI18N motherLabel4.setForeground(new java.awt.Color(255, 255, 255)); motherLabel4.setText("MOTHER'S NAME"); addStudentPanel.add(motherLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 310, -1, -1)); addFemaleCheck.setBackground(new java.awt.Color(36, 47, 65)); addFemaleCheck.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N addFemaleCheck.setForeground(new java.awt.Color(255, 255, 255)); addFemaleCheck.setText("FEMALE"); addStudentPanel.add(addFemaleCheck, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 420, -1, -1)); addMaleCheck.setBackground(new java.awt.Color(36, 47, 65)); addMaleCheck.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N addMaleCheck.setForeground(new java.awt.Color(255, 255, 255)); addMaleCheck.setText("MALE"); addStudentPanel.add(addMaleCheck, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 420, -1, -1)); createProfileButtonPanel4.setBackground(new java.awt.Color(50, 132, 255)); createProfileButtonPanel4.setForeground(new java.awt.Color(255, 255, 255)); createProfileButtonPanel4.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { createProfileButtonPanel4MouseClicked(evt); } }); createProfileButtonPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel26.setFont(new java.awt.Font("Century Gothic", 1, 16)); // NOI18N jLabel26.setForeground(new java.awt.Color(255, 255, 255)); jLabel26.setText("CREATE PROFILE"); createProfileButtonPanel4.add(jLabel26, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 0, 160, 50)); addStudentPanel.add(createProfileButtonPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 500, 190, 50)); showSelectedCoursesCount.setFont(new java.awt.Font("Century Gothic", 0, 16)); // NOI18N showSelectedCoursesCount.setForeground(new java.awt.Color(255, 0, 102)); showSelectedCoursesCount.setText("0"); addStudentPanel.add(showSelectedCoursesCount, new org.netbeans.lib.awtextra.AbsoluteConstraints(670, 180, 60, 40)); addMothersNameField.setBackground(new java.awt.Color(36, 47, 65)); addMothersNameField.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N addMothersNameField.setForeground(new java.awt.Color(204, 204, 204)); addMothersNameField.setText("Enter name"); addMothersNameField.setBorder(null); addMothersNameField.setCaretColor(new java.awt.Color(255, 255, 255)); addMothersNameField.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { addMothersNameFieldMouseClicked(evt); } }); addStudentPanel.add(addMothersNameField, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 330, 200, 40)); fatherLabel4.setFont(new java.awt.Font("Century Gothic", 1, 16)); // NOI18N fatherLabel4.setForeground(new java.awt.Color(255, 255, 255)); fatherLabel4.setText("FATHER'S NAME"); addStudentPanel.add(fatherLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 230, -1, -1)); mainFromAdmit.setBackground(new java.awt.Color(36, 47, 65)); mainFromAdmit.setForeground(new java.awt.Color(255, 255, 255)); mainFromAdmit.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { mainFromAdmitMouseClicked(evt); } }); mainFromAdmit.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel38.setFont(new java.awt.Font("Century Gothic", 0, 12)); // NOI18N jLabel38.setForeground(new java.awt.Color(255, 255, 255)); jLabel38.setText("BACK TO MAIN MENU"); mainFromAdmit.add(jLabel38, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 0, 140, 40)); mainFromAdmit.add(jSeparator5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, 140, 20)); addStudentPanel.add(mainFromAdmit, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 500, 170, 50)); cse101CheckBox.setBackground(new java.awt.Color(36, 47, 65)); cse101CheckBox.setFont(new java.awt.Font("Century Gothic", 1, 12)); // NOI18N cse101CheckBox.setForeground(new java.awt.Color(255, 255, 255)); cse101CheckBox.setText("CSE 101"); cse101CheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cse101CheckBoxActionPerformed(evt); } }); addStudentPanel.add(cse101CheckBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 80, 90, 30)); cse201CheckBox.setBackground(new java.awt.Color(36, 47, 65)); cse201CheckBox.setFont(new java.awt.Font("Century Gothic", 1, 12)); // NOI18N cse201CheckBox.setForeground(new java.awt.Color(255, 255, 255)); cse201CheckBox.setText("CSE 201"); cse201CheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cse201CheckBoxActionPerformed(evt); } }); addStudentPanel.add(cse201CheckBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 110, 90, 30)); cse301CheckBox.setBackground(new java.awt.Color(36, 47, 65)); cse301CheckBox.setFont(new java.awt.Font("Century Gothic", 1, 12)); // NOI18N cse301CheckBox.setForeground(new java.awt.Color(255, 255, 255)); cse301CheckBox.setText("CSE 301"); cse301CheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cse301CheckBoxActionPerformed(evt); } }); addStudentPanel.add(cse301CheckBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 140, 90, 30)); cse102CheckBox.setBackground(new java.awt.Color(36, 47, 65)); cse102CheckBox.setFont(new java.awt.Font("Century Gothic", 1, 12)); // NOI18N cse102CheckBox.setForeground(new java.awt.Color(255, 255, 255)); cse102CheckBox.setText("CSE 102"); cse102CheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cse102CheckBoxActionPerformed(evt); } }); addStudentPanel.add(cse102CheckBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 80, 90, 30)); cse202CheckBox.setBackground(new java.awt.Color(36, 47, 65)); cse202CheckBox.setFont(new java.awt.Font("Century Gothic", 1, 12)); // NOI18N cse202CheckBox.setForeground(new java.awt.Color(255, 255, 255)); cse202CheckBox.setText("CSE 202"); cse202CheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cse202CheckBoxActionPerformed(evt); } }); addStudentPanel.add(cse202CheckBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 110, 90, 30)); cse302CheckBox.setBackground(new java.awt.Color(36, 47, 65)); cse302CheckBox.setFont(new java.awt.Font("Century Gothic", 1, 12)); // NOI18N cse302CheckBox.setForeground(new java.awt.Color(255, 255, 255)); cse302CheckBox.setText("CSE 302"); cse302CheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cse302CheckBoxActionPerformed(evt); } }); addStudentPanel.add(cse302CheckBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 140, 90, 30)); cse103CheckBox.setBackground(new java.awt.Color(36, 47, 65)); cse103CheckBox.setFont(new java.awt.Font("Century Gothic", 1, 12)); // NOI18N cse103CheckBox.setForeground(new java.awt.Color(255, 255, 255)); cse103CheckBox.setText("CSE 103"); cse103CheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cse103CheckBoxActionPerformed(evt); } }); addStudentPanel.add(cse103CheckBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(670, 80, 90, 30)); cse203CheckBox.setBackground(new java.awt.Color(36, 47, 65)); cse203CheckBox.setFont(new java.awt.Font("Century Gothic", 1, 12)); // NOI18N cse203CheckBox.setForeground(new java.awt.Color(255, 255, 255)); cse203CheckBox.setText("CSE 203"); cse203CheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cse203CheckBoxActionPerformed(evt); } }); addStudentPanel.add(cse203CheckBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(670, 110, 90, 30)); cse303CheckBox.setBackground(new java.awt.Color(36, 47, 65)); cse303CheckBox.setFont(new java.awt.Font("Century Gothic", 1, 12)); // NOI18N cse303CheckBox.setForeground(new java.awt.Color(255, 255, 255)); cse303CheckBox.setText("CSE 303"); cse303CheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cse303CheckBoxActionPerformed(evt); } }); addStudentPanel.add(cse303CheckBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(670, 140, 90, 30)); jLabel13.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N jLabel13.setForeground(new java.awt.Color(255, 255, 255)); jLabel13.setText("SELECT LAB COURSES"); addStudentPanel.add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 270, -1, -1)); jLabel25.setFont(new java.awt.Font("Century Gothic", 0, 16)); // NOI18N jLabel25.setForeground(new java.awt.Color(255, 255, 255)); jLabel25.setText("SELECTED LAB COURSES:"); addStudentPanel.add(jLabel25, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 410, -1, -1)); showSelectedLabCoursesCount.setFont(new java.awt.Font("Century Gothic", 0, 16)); // NOI18N showSelectedLabCoursesCount.setForeground(new java.awt.Color(255, 0, 102)); showSelectedLabCoursesCount.setText("0"); addStudentPanel.add(showSelectedLabCoursesCount, new org.netbeans.lib.awtextra.AbsoluteConstraints(700, 400, 100, 40)); cse111CheckBox.setBackground(new java.awt.Color(36, 47, 65)); cse111CheckBox.setFont(new java.awt.Font("Century Gothic", 1, 12)); // NOI18N cse111CheckBox.setForeground(new java.awt.Color(255, 255, 255)); cse111CheckBox.setText("CSE 111"); cse111CheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cse111CheckBoxActionPerformed(evt); } }); addStudentPanel.add(cse111CheckBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 320, 90, 30)); cse112CheckBox.setBackground(new java.awt.Color(36, 47, 65)); cse112CheckBox.setFont(new java.awt.Font("Century Gothic", 1, 12)); // NOI18N cse112CheckBox.setForeground(new java.awt.Color(255, 255, 255)); cse112CheckBox.setText("CSE 112"); cse112CheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cse112CheckBoxActionPerformed(evt); } }); addStudentPanel.add(cse112CheckBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 350, 90, 30)); cse211CheckBox.setBackground(new java.awt.Color(36, 47, 65)); cse211CheckBox.setFont(new java.awt.Font("Century Gothic", 1, 12)); // NOI18N cse211CheckBox.setForeground(new java.awt.Color(255, 255, 255)); cse211CheckBox.setText("CSE 211"); cse211CheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cse211CheckBoxActionPerformed(evt); } }); addStudentPanel.add(cse211CheckBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 320, 90, 30)); cse212CheckBox.setBackground(new java.awt.Color(36, 47, 65)); cse212CheckBox.setFont(new java.awt.Font("Century Gothic", 1, 12)); // NOI18N cse212CheckBox.setForeground(new java.awt.Color(255, 255, 255)); cse212CheckBox.setText("CSE 212"); cse212CheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cse212CheckBoxActionPerformed(evt); } }); addStudentPanel.add(cse212CheckBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 350, 90, 30)); cse311CheckBox.setBackground(new java.awt.Color(36, 47, 65)); cse311CheckBox.setFont(new java.awt.Font("Century Gothic", 1, 12)); // NOI18N cse311CheckBox.setForeground(new java.awt.Color(255, 255, 255)); cse311CheckBox.setText("CSE 311"); cse311CheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cse311CheckBoxActionPerformed(evt); } }); addStudentPanel.add(cse311CheckBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(670, 320, 90, 30)); cse312CheckBox.setBackground(new java.awt.Color(36, 47, 65)); cse312CheckBox.setFont(new java.awt.Font("Century Gothic", 1, 12)); // NOI18N cse312CheckBox.setForeground(new java.awt.Color(255, 255, 255)); cse312CheckBox.setText("CSE 312"); cse312CheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cse312CheckBoxActionPerformed(evt); } }); addStudentPanel.add(cse312CheckBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(670, 350, 90, 30)); add(addStudentPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); updateStudentPanel.setBackground(new java.awt.Color(36, 47, 65)); updateStudentPanel.setForeground(new java.awt.Color(204, 204, 204)); updateStudentPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); updateSearchStudentPanel.setBackground(new java.awt.Color(36, 47, 65)); updateSearchStudentPanel.setForeground(new java.awt.Color(204, 204, 204)); updateSearchStudentPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); findStudentDropField.setBackground(new java.awt.Color(36, 47, 65)); findStudentDropField.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N findStudentDropField.setForeground(new java.awt.Color(204, 204, 204)); findStudentDropField.setText("Enter Student ID"); findStudentDropField.setBorder(null); findStudentDropField.setCaretColor(new java.awt.Color(255, 255, 255)); findStudentDropField.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { findStudentDropFieldMouseClicked(evt); } }); updateSearchStudentPanel.add(findStudentDropField, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 250, 330, 40)); mainFromDrop1.setBackground(new java.awt.Color(36, 47, 65)); mainFromDrop1.setForeground(new java.awt.Color(255, 255, 255)); mainFromDrop1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { mainFromDrop1MouseClicked(evt); } }); mainFromDrop1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel46.setFont(new java.awt.Font("Century Gothic", 0, 12)); // NOI18N jLabel46.setForeground(new java.awt.Color(255, 255, 255)); jLabel46.setText("BACK TO MAIN MENU"); mainFromDrop1.add(jLabel46, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 0, 150, 50)); jSeparator13.setForeground(new java.awt.Color(255, 255, 255)); mainFromDrop1.add(jSeparator13, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, 150, 20)); updateSearchStudentPanel.add(mainFromDrop1, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 450, 170, 50)); dropStudentSearchButton1.setBackground(new java.awt.Color(50, 132, 255)); dropStudentSearchButton1.setForeground(new java.awt.Color(255, 255, 255)); dropStudentSearchButton1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { dropStudentSearchButton1MouseClicked(evt); } }); dropStudentSearchButton1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); dropStudentSearchButtonLabel1.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N dropStudentSearchButtonLabel1.setForeground(new java.awt.Color(255, 255, 255)); dropStudentSearchButtonLabel1.setText("FIND"); dropStudentSearchButton1.add(dropStudentSearchButtonLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 0, 70, 40)); updateSearchStudentPanel.add(dropStudentSearchButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 250, 90, 40)); jLabel16.setFont(new java.awt.Font("Century Gothic", 1, 24)); // NOI18N jLabel16.setForeground(new java.awt.Color(255, 255, 255)); jLabel16.setText("Update student data"); updateSearchStudentPanel.add(jLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 60, 240, 40)); jSeparator2.setForeground(new java.awt.Color(255, 255, 255)); jSeparator2.setFont(new java.awt.Font("Dialog", 0, 10)); // NOI18N updateSearchStudentPanel.add(jSeparator2, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 290, 350, 10)); updateFindStudentErrorText.setBackground(new java.awt.Color(255, 0, 153)); updateFindStudentErrorText.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N updateFindStudentErrorText.setForeground(new java.awt.Color(255, 0, 51)); updateSearchStudentPanel.add(updateFindStudentErrorText, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 310, 450, 40)); updateStudentPanel.add(updateSearchStudentPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); updateFoundStudentPanel.setBackground(new java.awt.Color(36, 47, 65)); updateFoundStudentPanel.setForeground(new java.awt.Color(204, 204, 204)); updateFoundStudentPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); cancelFromUpdate.setBackground(new java.awt.Color(36, 47, 65)); cancelFromUpdate.setForeground(new java.awt.Color(255, 255, 255)); cancelFromUpdate.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { cancelFromUpdateMouseClicked(evt); } }); cancelFromUpdate.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jSeparator15.setForeground(new java.awt.Color(255, 255, 255)); cancelFromUpdate.add(jSeparator15, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, 70, 20)); cancelFromUpdateLabel.setFont(new java.awt.Font("Century Gothic", 0, 12)); // NOI18N cancelFromUpdateLabel.setForeground(new java.awt.Color(255, 255, 255)); cancelFromUpdateLabel.setText("CANCEL"); cancelFromUpdate.add(cancelFromUpdateLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 0, 50, 50)); backToMainFromUpdateLabel.setFont(new java.awt.Font("Century Gothic", 0, 12)); // NOI18N backToMainFromUpdateLabel.setForeground(new java.awt.Color(255, 255, 255)); backToMainFromUpdateLabel.setText("BACK"); cancelFromUpdate.add(backToMainFromUpdateLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 0, 50, 50)); updateFoundStudentPanel.add(cancelFromUpdate, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 500, 90, 50)); dropStudentSearchButton2.setBackground(new java.awt.Color(255, 0, 51)); dropStudentSearchButton2.setForeground(new java.awt.Color(255, 255, 255)); dropStudentSearchButton2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { dropStudentSearchButton2MouseClicked(evt); } }); dropStudentSearchButton2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); dropStudentSearchButtonLabel2.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N dropStudentSearchButtonLabel2.setForeground(new java.awt.Color(255, 255, 255)); dropStudentSearchButtonLabel2.setText("DROP"); dropStudentSearchButton2.add(dropStudentSearchButtonLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 0, 80, 40)); updateFoundStudentPanel.add(dropStudentSearchButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(630, 500, 110, 40)); jLabel17.setFont(new java.awt.Font("Century Gothic", 1, 24)); // NOI18N jLabel17.setForeground(new java.awt.Color(255, 255, 255)); jLabel17.setText("UPDATE STUDENT DATA"); updateFoundStudentPanel.add(jLabel17, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 20, 310, 40)); nameLabel5.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N nameLabel5.setForeground(new java.awt.Color(255, 255, 255)); nameLabel5.setText("GENDER"); updateFoundStudentPanel.add(nameLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 290, 120, 30)); nameLabel6.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N nameLabel6.setForeground(new java.awt.Color(255, 255, 255)); nameLabel6.setText("NAME"); updateFoundStudentPanel.add(nameLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 130, 50, 30)); nameLabel7.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N nameLabel7.setForeground(new java.awt.Color(255, 255, 255)); nameLabel7.setText("ID"); updateFoundStudentPanel.add(nameLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 170, 110, 30)); nameLabel8.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N nameLabel8.setForeground(new java.awt.Color(255, 255, 255)); nameLabel8.setText("FATHER'S NAME"); updateFoundStudentPanel.add(nameLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 210, 110, 30)); nameLabel9.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N nameLabel9.setForeground(new java.awt.Color(255, 255, 255)); nameLabel9.setText("MOTHER'S NAME"); updateFoundStudentPanel.add(nameLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 250, 120, 30)); jLabel14.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N jLabel14.setForeground(new java.awt.Color(255, 255, 255)); jLabel14.setText("GRADE"); updateFoundStudentPanel.add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 80, 80, -1)); jLabel19.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N jLabel19.setForeground(new java.awt.Color(255, 255, 255)); jLabel19.setText("SELECTED COURSES"); updateFoundStudentPanel.add(jLabel19, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 350, 170, -1)); courseBName.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N courseBName.setForeground(new java.awt.Color(0, 255, 204)); courseBName.setText("CSE XXX"); updateFoundStudentPanel.add(courseBName, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 390, 70, 30)); nameLabel11.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N nameLabel11.setForeground(new java.awt.Color(255, 255, 255)); nameLabel11.setText("LAB"); updateFoundStudentPanel.add(nameLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 430, 60, 30)); jSeparator26.setForeground(new java.awt.Color(255, 255, 255)); jSeparator26.setOrientation(javax.swing.SwingConstants.VERTICAL); updateFoundStudentPanel.add(jSeparator26, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 80, 20, 390)); updateID.setEditable(false); updateID.setBackground(new java.awt.Color(36, 47, 65)); updateID.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N updateID.setForeground(new java.awt.Color(0, 204, 255)); updateID.setText("DUMMY TEXT"); updateID.setBorder(null); updateID.setCaretColor(new java.awt.Color(255, 255, 255)); updateFoundStudentPanel.add(updateID, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 170, 240, 30)); updateFullName.setBackground(new java.awt.Color(36, 47, 65)); updateFullName.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N updateFullName.setForeground(new java.awt.Color(0, 204, 255)); updateFullName.setText("DUMMY TEXT"); updateFullName.setBorder(null); updateFullName.setCaretColor(new java.awt.Color(255, 255, 255)); updateFoundStudentPanel.add(updateFullName, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 130, 240, 30)); updateMothersName.setBackground(new java.awt.Color(36, 47, 65)); updateMothersName.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N updateMothersName.setForeground(new java.awt.Color(0, 204, 255)); updateMothersName.setText("DUMMY TEXT"); updateMothersName.setBorder(null); updateMothersName.setCaretColor(new java.awt.Color(255, 255, 255)); updateFoundStudentPanel.add(updateMothersName, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 250, 240, 30)); updateFathersName.setBackground(new java.awt.Color(36, 47, 65)); updateFathersName.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N updateFathersName.setForeground(new java.awt.Color(0, 204, 255)); updateFathersName.setText("DUMMY TEXT"); updateFathersName.setBorder(null); updateFathersName.setCaretColor(new java.awt.Color(255, 255, 255)); updateFoundStudentPanel.add(updateFathersName, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 210, 240, 30)); updateGender.setEditable(false); updateGender.setBackground(new java.awt.Color(36, 47, 65)); updateGender.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N updateGender.setForeground(new java.awt.Color(0, 204, 255)); updateGender.setText("DUMMY TEXT"); updateGender.setBorder(null); updateGender.setCaretColor(new java.awt.Color(255, 255, 255)); updateFoundStudentPanel.add(updateGender, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 290, 240, 30)); nameLabel12.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N nameLabel12.setForeground(new java.awt.Color(255, 255, 255)); nameLabel12.setText("MAIN"); updateFoundStudentPanel.add(nameLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 390, 50, 30)); courseAName.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N courseAName.setForeground(new java.awt.Color(0, 255, 204)); courseAName.setText("CSE XXX"); updateFoundStudentPanel.add(courseAName, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 390, 70, 30)); courseDName.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N courseDName.setForeground(new java.awt.Color(0, 255, 204)); courseDName.setText("CSE XXX"); updateFoundStudentPanel.add(courseDName, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 390, 70, 30)); courseCName.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N courseCName.setForeground(new java.awt.Color(0, 255, 204)); courseCName.setText("CSE XXX"); updateFoundStudentPanel.add(courseCName, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 390, 70, 30)); courseFName.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N courseFName.setForeground(new java.awt.Color(0, 255, 204)); courseFName.setText("CSE XXX"); updateFoundStudentPanel.add(courseFName, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 430, 70, 30)); courseEName.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N courseEName.setForeground(new java.awt.Color(0, 255, 204)); courseEName.setText("CSE XXX"); updateFoundStudentPanel.add(courseEName, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 430, 70, 30)); courseDNameGrade.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N courseDNameGrade.setForeground(new java.awt.Color(255, 255, 255)); courseDNameGrade.setText("CSE XXX"); updateFoundStudentPanel.add(courseDNameGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 250, 110, 30)); courseANameGrade.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N courseANameGrade.setForeground(new java.awt.Color(255, 255, 255)); courseANameGrade.setText("CSE XXX"); updateFoundStudentPanel.add(courseANameGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 130, 110, 30)); courseBNameGrade.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N courseBNameGrade.setForeground(new java.awt.Color(255, 255, 255)); courseBNameGrade.setText("CSE XXX"); updateFoundStudentPanel.add(courseBNameGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 170, 110, 30)); courseCNameGrade.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N courseCNameGrade.setForeground(new java.awt.Color(255, 255, 255)); courseCNameGrade.setText("CSE XXX"); updateFoundStudentPanel.add(courseCNameGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 210, 110, 30)); courseFNameGrade.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N courseFNameGrade.setForeground(new java.awt.Color(255, 255, 255)); courseFNameGrade.setText("CSE XXX"); updateFoundStudentPanel.add(courseFNameGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 330, 110, 30)); courseENameGrade.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N courseENameGrade.setForeground(new java.awt.Color(255, 255, 255)); courseENameGrade.setText("CSE XXX"); updateFoundStudentPanel.add(courseENameGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 290, 110, 30)); jLabel20.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N jLabel20.setForeground(new java.awt.Color(255, 255, 255)); jLabel20.setText("STUDENT BIO"); updateFoundStudentPanel.add(jLabel20, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 90, 170, -1)); jLabel21.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N jLabel21.setForeground(new java.awt.Color(255, 255, 255)); jLabel21.setText("COURSE"); updateFoundStudentPanel.add(jLabel21, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 80, 80, -1)); courseBGrade.setBackground(new java.awt.Color(36, 47, 65)); courseBGrade.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N courseBGrade.setForeground(new java.awt.Color(0, 204, 255)); courseBGrade.setText("DUMMY TEXT"); courseBGrade.setBorder(null); courseBGrade.setCaretColor(new java.awt.Color(255, 255, 255)); updateFoundStudentPanel.add(courseBGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 170, 90, 30)); courseAGrade.setBackground(new java.awt.Color(36, 47, 65)); courseAGrade.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N courseAGrade.setForeground(new java.awt.Color(0, 204, 255)); courseAGrade.setText("DUMMY TEXT"); courseAGrade.setBorder(null); courseAGrade.setCaretColor(new java.awt.Color(255, 255, 255)); updateFoundStudentPanel.add(courseAGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 130, 90, 30)); courseDGrade.setBackground(new java.awt.Color(36, 47, 65)); courseDGrade.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N courseDGrade.setForeground(new java.awt.Color(0, 204, 255)); courseDGrade.setText("DUMMY TEXT"); courseDGrade.setBorder(null); courseDGrade.setCaretColor(new java.awt.Color(255, 255, 255)); updateFoundStudentPanel.add(courseDGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 250, 90, 30)); courseCGrade.setBackground(new java.awt.Color(36, 47, 65)); courseCGrade.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N courseCGrade.setForeground(new java.awt.Color(0, 204, 255)); courseCGrade.setText("DUMMY TEXT"); courseCGrade.setBorder(null); courseCGrade.setCaretColor(new java.awt.Color(255, 255, 255)); updateFoundStudentPanel.add(courseCGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 210, 90, 30)); courseFGrade.setBackground(new java.awt.Color(36, 47, 65)); courseFGrade.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N courseFGrade.setForeground(new java.awt.Color(0, 204, 255)); courseFGrade.setText("DUMMY TEXT"); courseFGrade.setBorder(null); courseFGrade.setCaretColor(new java.awt.Color(255, 255, 255)); updateFoundStudentPanel.add(courseFGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 330, 90, 30)); courseEGrade.setBackground(new java.awt.Color(36, 47, 65)); courseEGrade.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N courseEGrade.setForeground(new java.awt.Color(0, 204, 255)); courseEGrade.setText("DUMMY TEXT"); courseEGrade.setBorder(null); courseEGrade.setCaretColor(new java.awt.Color(255, 255, 255)); updateFoundStudentPanel.add(courseEGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 290, 90, 30)); updateButton.setBackground(new java.awt.Color(50, 132, 255)); updateButton.setForeground(new java.awt.Color(255, 255, 255)); updateButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { updateButtonMouseClicked(evt); } }); updateButton.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); dropStudentSearchButtonLabel3.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N dropStudentSearchButtonLabel3.setForeground(new java.awt.Color(255, 255, 255)); dropStudentSearchButtonLabel3.setText("UPDATE"); updateButton.add(dropStudentSearchButtonLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 0, 80, 40)); updateFoundStudentPanel.add(updateButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 500, 110, 40)); updateStudentPanel.add(updateFoundStudentPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); add(updateStudentPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); resultPanel.setBackground(new java.awt.Color(36, 47, 65)); resultPanel.setForeground(new java.awt.Color(204, 204, 204)); resultPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); resultSearchPanel.setBackground(new java.awt.Color(36, 47, 65)); resultSearchPanel.setForeground(new java.awt.Color(204, 204, 204)); resultSearchPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel15.setFont(new java.awt.Font("Century Gothic", 1, 24)); // NOI18N jLabel15.setForeground(new java.awt.Color(255, 255, 255)); jLabel15.setText("Result"); resultSearchPanel.add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 40, 190, 40)); resultSearchButton1.setBackground(new java.awt.Color(50, 132, 255)); resultSearchButton1.setForeground(new java.awt.Color(255, 255, 255)); resultSearchButton1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { resultSearchButton1MouseClicked(evt); } }); resultSearchButton1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel36.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N jLabel36.setForeground(new java.awt.Color(255, 255, 255)); jLabel36.setText("RESULT"); resultSearchButton1.add(jLabel36, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 0, 80, 40)); resultSearchPanel.add(resultSearchButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 250, 100, 40)); mainFromResult1.setBackground(new java.awt.Color(36, 47, 65)); mainFromResult1.setForeground(new java.awt.Color(255, 255, 255)); mainFromResult1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { mainFromResult1MouseClicked(evt); } }); mainFromResult1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel42.setFont(new java.awt.Font("Century Gothic", 0, 12)); // NOI18N jLabel42.setForeground(new java.awt.Color(255, 255, 255)); jLabel42.setText("BACK TO MAIN MENU"); mainFromResult1.add(jLabel42, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 0, 150, 50)); jSeparator7.setForeground(new java.awt.Color(255, 255, 255)); mainFromResult1.add(jSeparator7, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, 150, 20)); resultSearchPanel.add(mainFromResult1, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 450, 170, 50)); resultSearchField.setBackground(new java.awt.Color(36, 47, 65)); resultSearchField.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N resultSearchField.setForeground(new java.awt.Color(204, 204, 204)); resultSearchField.setText("Enter Student ID"); resultSearchField.setBorder(null); resultSearchField.setCaretColor(new java.awt.Color(255, 255, 255)); resultSearchField.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { resultSearchFieldMouseClicked(evt); } }); resultSearchPanel.add(resultSearchField, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 250, 330, 40)); jSeparator10.setForeground(new java.awt.Color(255, 255, 255)); resultSearchPanel.add(jSeparator10, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 290, 330, 10)); resultFindStudentErrorText.setBackground(new java.awt.Color(255, 0, 153)); resultFindStudentErrorText.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N resultFindStudentErrorText.setForeground(new java.awt.Color(255, 0, 51)); resultSearchPanel.add(resultFindStudentErrorText, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 310, 450, 40)); resultPanel.add(resultSearchPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); resultViewPanel.setBackground(new java.awt.Color(36, 47, 65)); resultViewPanel.setForeground(new java.awt.Color(204, 204, 204)); resultViewPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); backFromResultView.setBackground(new java.awt.Color(36, 47, 65)); backFromResultView.setForeground(new java.awt.Color(255, 255, 255)); backFromResultView.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { backFromResultViewMouseClicked(evt); } }); backFromResultView.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); backLabelResult.setFont(new java.awt.Font("Century Gothic", 0, 12)); // NOI18N backLabelResult.setForeground(new java.awt.Color(255, 255, 255)); backLabelResult.setText("BACK"); backFromResultView.add(backLabelResult, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 0, 50, 50)); backSepResult.setForeground(new java.awt.Color(255, 255, 255)); backFromResultView.add(backSepResult, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 40, 50, 20)); backFromMainLabelResult.setFont(new java.awt.Font("Century Gothic", 0, 12)); // NOI18N backFromMainLabelResult.setForeground(new java.awt.Color(255, 255, 255)); backFromMainLabelResult.setText("BACK TO MAIN MENU"); backFromResultView.add(backFromMainLabelResult, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 0, 130, 50)); backFromMainSepResult.setForeground(new java.awt.Color(255, 255, 255)); backFromResultView.add(backFromMainSepResult, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 40, 160, 20)); resultViewPanel.add(backFromResultView, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 510, 230, 50)); jLabel22.setFont(new java.awt.Font("Century Gothic", 1, 24)); // NOI18N jLabel22.setForeground(new java.awt.Color(255, 255, 255)); jLabel22.setText("RESULT"); resultViewPanel.add(jLabel22, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 20, 240, 40)); nameLabel10.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N nameLabel10.setForeground(new java.awt.Color(255, 255, 255)); nameLabel10.setText("GENDER"); resultViewPanel.add(nameLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 290, 120, 30)); nameLabel13.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N nameLabel13.setForeground(new java.awt.Color(255, 255, 255)); nameLabel13.setText("NAME"); resultViewPanel.add(nameLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 130, 50, 30)); nameLabel14.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N nameLabel14.setForeground(new java.awt.Color(255, 255, 255)); nameLabel14.setText("ID"); resultViewPanel.add(nameLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 170, 110, 30)); nameLabel15.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N nameLabel15.setForeground(new java.awt.Color(255, 255, 255)); nameLabel15.setText("FATHER'S NAME"); resultViewPanel.add(nameLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 210, 110, 30)); nameLabel16.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N nameLabel16.setForeground(new java.awt.Color(255, 255, 255)); nameLabel16.setText("MOTHER'S NAME"); resultViewPanel.add(nameLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 250, 120, 30)); jLabel27.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N jLabel27.setForeground(new java.awt.Color(255, 255, 255)); jLabel27.setText("GRADE"); resultViewPanel.add(jLabel27, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 80, 80, -1)); jLabel28.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N jLabel28.setForeground(new java.awt.Color(255, 255, 255)); jLabel28.setText("SELECTED COURSES"); resultViewPanel.add(jLabel28, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 350, 170, -1)); resultCourseBName.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N resultCourseBName.setForeground(new java.awt.Color(0, 204, 255)); resultCourseBName.setText("CSE XXX"); resultViewPanel.add(resultCourseBName, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 390, 70, 30)); nameLabel17.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N nameLabel17.setForeground(new java.awt.Color(255, 255, 255)); nameLabel17.setText("LAB"); resultViewPanel.add(nameLabel17, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 430, 60, 30)); jSeparator27.setForeground(new java.awt.Color(255, 255, 255)); jSeparator27.setOrientation(javax.swing.SwingConstants.VERTICAL); resultViewPanel.add(jSeparator27, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 80, 20, 390)); resultUpdateID.setEditable(false); resultUpdateID.setBackground(new java.awt.Color(36, 47, 65)); resultUpdateID.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N resultUpdateID.setForeground(new java.awt.Color(0, 204, 255)); resultUpdateID.setText("DUMMY TEXT"); resultUpdateID.setBorder(null); resultUpdateID.setCaretColor(new java.awt.Color(255, 255, 255)); resultViewPanel.add(resultUpdateID, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 170, 240, 30)); resultFullName.setEditable(false); resultFullName.setBackground(new java.awt.Color(36, 47, 65)); resultFullName.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N resultFullName.setForeground(new java.awt.Color(0, 204, 255)); resultFullName.setText("DUMMY TEXT"); resultFullName.setBorder(null); resultFullName.setCaretColor(new java.awt.Color(255, 255, 255)); resultViewPanel.add(resultFullName, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 130, 240, 30)); resultMothersName.setEditable(false); resultMothersName.setBackground(new java.awt.Color(36, 47, 65)); resultMothersName.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N resultMothersName.setForeground(new java.awt.Color(0, 204, 255)); resultMothersName.setText("DUMMY TEXT"); resultMothersName.setBorder(null); resultMothersName.setCaretColor(new java.awt.Color(255, 255, 255)); resultViewPanel.add(resultMothersName, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 250, 240, 30)); resultFathersName.setEditable(false); resultFathersName.setBackground(new java.awt.Color(36, 47, 65)); resultFathersName.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N resultFathersName.setForeground(new java.awt.Color(0, 204, 255)); resultFathersName.setText("DUMMY TEXT"); resultFathersName.setBorder(null); resultFathersName.setCaretColor(new java.awt.Color(255, 255, 255)); resultViewPanel.add(resultFathersName, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 210, 240, 30)); resultGender.setEditable(false); resultGender.setBackground(new java.awt.Color(36, 47, 65)); resultGender.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N resultGender.setForeground(new java.awt.Color(0, 204, 255)); resultGender.setText("DUMMY TEXT"); resultGender.setBorder(null); resultGender.setCaretColor(new java.awt.Color(255, 255, 255)); resultViewPanel.add(resultGender, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 290, 240, 30)); nameLabel18.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N nameLabel18.setForeground(new java.awt.Color(255, 255, 255)); nameLabel18.setText("MAIN"); resultViewPanel.add(nameLabel18, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 390, 50, 30)); resultCourseAName.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N resultCourseAName.setForeground(new java.awt.Color(0, 204, 255)); resultCourseAName.setText("CSE XXX"); resultViewPanel.add(resultCourseAName, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 390, 70, 30)); resultCourseDName.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N resultCourseDName.setForeground(new java.awt.Color(0, 204, 255)); resultCourseDName.setText("CSE XXX"); resultViewPanel.add(resultCourseDName, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 390, 70, 30)); resultCourseCName.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N resultCourseCName.setForeground(new java.awt.Color(0, 204, 255)); resultCourseCName.setText("CSE XXX"); resultViewPanel.add(resultCourseCName, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 390, 70, 30)); resultCourseFName.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N resultCourseFName.setForeground(new java.awt.Color(0, 204, 255)); resultCourseFName.setText("CSE XXX"); resultViewPanel.add(resultCourseFName, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 430, 70, 30)); resultCourseEName.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N resultCourseEName.setForeground(new java.awt.Color(0, 204, 255)); resultCourseEName.setText("CSE XXX"); resultViewPanel.add(resultCourseEName, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 430, 70, 30)); resultCourseDNameGrade.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N resultCourseDNameGrade.setForeground(new java.awt.Color(255, 255, 255)); resultCourseDNameGrade.setText("CSE XXX"); resultViewPanel.add(resultCourseDNameGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 250, 110, 30)); resultCourseANameGrade.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N resultCourseANameGrade.setForeground(new java.awt.Color(255, 255, 255)); resultCourseANameGrade.setText("CSE XXX"); resultViewPanel.add(resultCourseANameGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 130, 110, 30)); resultCourseBNameGrade.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N resultCourseBNameGrade.setForeground(new java.awt.Color(255, 255, 255)); resultCourseBNameGrade.setText("CSE XXX"); resultViewPanel.add(resultCourseBNameGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 170, 110, 30)); resultCourseCNameGrade.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N resultCourseCNameGrade.setForeground(new java.awt.Color(255, 255, 255)); resultCourseCNameGrade.setText("CSE XXX"); resultViewPanel.add(resultCourseCNameGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 210, 110, 30)); resultCourseFNameGrade.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N resultCourseFNameGrade.setForeground(new java.awt.Color(255, 255, 255)); resultCourseFNameGrade.setText("CSE XXX"); resultViewPanel.add(resultCourseFNameGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 330, 110, 30)); resultCourseENameGrade.setFont(new java.awt.Font("Century Gothic", 1, 14)); // NOI18N resultCourseENameGrade.setForeground(new java.awt.Color(255, 255, 255)); resultCourseENameGrade.setText("CSE XXX"); resultViewPanel.add(resultCourseENameGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 290, 110, 30)); jLabel29.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N jLabel29.setForeground(new java.awt.Color(255, 255, 255)); jLabel29.setText("STUDENT BIO"); resultViewPanel.add(jLabel29, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 90, 170, -1)); jLabel30.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N jLabel30.setForeground(new java.awt.Color(255, 255, 255)); jLabel30.setText("CGPA"); resultViewPanel.add(jLabel30, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 390, 60, 40)); resultCourseBGrade.setEditable(false); resultCourseBGrade.setBackground(new java.awt.Color(36, 47, 65)); resultCourseBGrade.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N resultCourseBGrade.setForeground(new java.awt.Color(0, 204, 255)); resultCourseBGrade.setText("DUMMY TEXT"); resultCourseBGrade.setBorder(null); resultCourseBGrade.setCaretColor(new java.awt.Color(255, 255, 255)); resultViewPanel.add(resultCourseBGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 170, 90, 30)); resultCGPA.setEditable(false); resultCGPA.setBackground(new java.awt.Color(36, 47, 65)); resultCGPA.setFont(new java.awt.Font("Century Gothic", 0, 18)); // NOI18N resultCGPA.setForeground(new java.awt.Color(0, 204, 255)); resultCGPA.setText("DUMMY TEXT"); resultCGPA.setBorder(null); resultCGPA.setCaretColor(new java.awt.Color(255, 255, 255)); resultViewPanel.add(resultCGPA, new org.netbeans.lib.awtextra.AbsoluteConstraints(590, 400, 120, -1)); resultCourseDGrade.setEditable(false); resultCourseDGrade.setBackground(new java.awt.Color(36, 47, 65)); resultCourseDGrade.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N resultCourseDGrade.setForeground(new java.awt.Color(0, 204, 255)); resultCourseDGrade.setText("DUMMY TEXT"); resultCourseDGrade.setBorder(null); resultCourseDGrade.setCaretColor(new java.awt.Color(255, 255, 255)); resultViewPanel.add(resultCourseDGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 250, 90, 30)); resultCourseCGrade.setEditable(false); resultCourseCGrade.setBackground(new java.awt.Color(36, 47, 65)); resultCourseCGrade.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N resultCourseCGrade.setForeground(new java.awt.Color(0, 204, 255)); resultCourseCGrade.setText("DUMMY TEXT"); resultCourseCGrade.setBorder(null); resultCourseCGrade.setCaretColor(new java.awt.Color(255, 255, 255)); resultViewPanel.add(resultCourseCGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 210, 90, 30)); resultCourseFGrade.setEditable(false); resultCourseFGrade.setBackground(new java.awt.Color(36, 47, 65)); resultCourseFGrade.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N resultCourseFGrade.setForeground(new java.awt.Color(0, 204, 255)); resultCourseFGrade.setText("DUMMY TEXT"); resultCourseFGrade.setBorder(null); resultCourseFGrade.setCaretColor(new java.awt.Color(255, 255, 255)); resultViewPanel.add(resultCourseFGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 330, 90, 30)); resultCourseEGrade.setEditable(false); resultCourseEGrade.setBackground(new java.awt.Color(36, 47, 65)); resultCourseEGrade.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N resultCourseEGrade.setForeground(new java.awt.Color(0, 204, 255)); resultCourseEGrade.setText("DUMMY TEXT"); resultCourseEGrade.setBorder(null); resultCourseEGrade.setCaretColor(new java.awt.Color(255, 255, 255)); resultViewPanel.add(resultCourseEGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 290, 90, 30)); jLabel31.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N jLabel31.setForeground(new java.awt.Color(255, 255, 255)); jLabel31.setText("COURSE"); resultViewPanel.add(jLabel31, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 80, 80, -1)); resultCourseAGrade.setEditable(false); resultCourseAGrade.setBackground(new java.awt.Color(36, 47, 65)); resultCourseAGrade.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N resultCourseAGrade.setForeground(new java.awt.Color(0, 204, 255)); resultCourseAGrade.setText("DUMMY TEXT"); resultCourseAGrade.setBorder(null); resultCourseAGrade.setCaretColor(new java.awt.Color(255, 255, 255)); resultViewPanel.add(resultCourseAGrade, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 130, 90, 30)); jLabel32.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N jLabel32.setForeground(new java.awt.Color(255, 255, 255)); jLabel32.setText("REMARKS"); resultViewPanel.add(jLabel32, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 420, 80, 40)); resultRemarks.setEditable(false); resultRemarks.setBackground(new java.awt.Color(36, 47, 65)); resultRemarks.setFont(new java.awt.Font("Century Gothic", 0, 18)); // NOI18N resultRemarks.setForeground(new java.awt.Color(0, 204, 255)); resultRemarks.setText("DUMMY TEXT"); resultRemarks.setBorder(null); resultRemarks.setCaretColor(new java.awt.Color(255, 255, 255)); resultViewPanel.add(resultRemarks, new org.netbeans.lib.awtextra.AbsoluteConstraints(590, 430, 120, 20)); resultPanel.add(resultViewPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); add(resultPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); }// </editor-fold>//GEN-END:initComponents /** Below this line are the IDE Generated methods **/ // <editor-fold defaultstate="collapsed" desc="Generated methods"> private void addStudentFullNameMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addStudentFullNameMouseClicked this.addStudentFullName.setText(""); clearText(); }//GEN-LAST:event_addStudentFullNameMouseClicked private void addStudentIDMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addStudentIDMouseClicked this.addStudentID.setText(""); clearText(); }//GEN-LAST:event_addStudentIDMouseClicked private void addFathersNameFieldMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addFathersNameFieldMouseClicked this.addFathersNameField.setText(""); }//GEN-LAST:event_addFathersNameFieldMouseClicked private void addMothersNameFieldMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addMothersNameFieldMouseClicked this.addMothersNameField.setText(""); }//GEN-LAST:event_addMothersNameFieldMouseClicked private void viewResultButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_viewResultButtonMouseClicked //TODO implement dynamic views after setting up search fucntion if(this.dataLoader.getCurrentStudentIndex() >= 0) { this.fromMain = true; this.backFromMainLabelResult.setVisible(true); this.backFromMainSepResult.setVisible(true); this.backLabelResult.setVisible(false); this.backSepResult.setVisible(false); resultShowDetails(); displayResultPanel(false, true); clearText(); } else { this.fromMain = false; this.backFromMainLabelResult.setVisible(false); this.backFromMainSepResult.setVisible(false); this.backLabelResult.setVisible(true); this.backSepResult.setVisible(true); displayResultPanel(true, false); } }//GEN-LAST:event_viewResultButtonMouseClicked private void admitStudentButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_admitStudentButtonMouseClicked panelVisiblity(false, true, false, false); clearText(); }//GEN-LAST:event_admitStudentButtonMouseClicked private void mainFromAdmitMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_mainFromAdmitMouseClicked panelVisiblity(true, false, false, false); clearText(); //DONE }//GEN-LAST:event_mainFromAdmitMouseClicked private void dropStudentButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dropStudentButtonMouseClicked //Need to implement dynamic views after setting up search fucntion if(this.dataLoader.getCurrentStudentIndex() >= 0) { this.fromMain = true; this.backToMainFromUpdateLabel.setVisible(true); this.cancelFromUpdateLabel.setVisible(false); updateStudentShowDetails(); displayUpdateStudentPanel(false, true); clearText(); } else { this.fromMain = false; this.backToMainFromUpdateLabel.setVisible(false); this.cancelFromUpdateLabel.setVisible(true); displayUpdateStudentPanel(true, false); } }//GEN-LAST:event_dropStudentButtonMouseClicked private void findStudentFieldMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_findStudentFieldMouseClicked this.findStudentField.setText("171-15-"); clearText(); }//GEN-LAST:event_findStudentFieldMouseClicked private void findStudentDropFieldMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_findStudentDropFieldMouseClicked this.findStudentDropField.setText("171-15-"); clearText(); }//GEN-LAST:event_findStudentDropFieldMouseClicked private void mainFromDrop1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_mainFromDrop1MouseClicked refreshData(); panelVisiblity(true, false, false, false); //DONE }//GEN-LAST:event_mainFromDrop1MouseClicked private void cancelFromUpdateMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelFromUpdateMouseClicked displayUpdateStudentPanel(true, false); this.updateFindStudentErrorText.setText(""); if(this.fromMain) { displayUpdateStudentPanel(false, false); panelVisiblity(true, false, false, false); refreshData(); return; } refreshData(); displayUpdateStudentPanel(true, false); //DONE }//GEN-LAST:event_cancelFromUpdateMouseClicked private void mainFromResult1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_mainFromResult1MouseClicked refreshData(); panelVisiblity(true, false, false, false); //DONE }//GEN-LAST:event_mainFromResult1MouseClicked private void resultSearchFieldMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_resultSearchFieldMouseClicked this.resultSearchField.setText("171-15-"); }//GEN-LAST:event_resultSearchFieldMouseClicked private void createProfileButtonPanel4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_createProfileButtonPanel4MouseClicked createStudentProfile(); }//GEN-LAST:event_createProfileButtonPanel4MouseClicked private void cse101CheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cse101CheckBoxActionPerformed mainCourseCheckBoxAction(this.cse101CheckBox); }//GEN-LAST:event_cse101CheckBoxActionPerformed private void cse201CheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cse201CheckBoxActionPerformed mainCourseCheckBoxAction(this.cse201CheckBox); }//GEN-LAST:event_cse201CheckBoxActionPerformed private void cse301CheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cse301CheckBoxActionPerformed mainCourseCheckBoxAction(this.cse301CheckBox); }//GEN-LAST:event_cse301CheckBoxActionPerformed private void cse102CheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cse102CheckBoxActionPerformed mainCourseCheckBoxAction(this.cse102CheckBox); }//GEN-LAST:event_cse102CheckBoxActionPerformed private void cse202CheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cse202CheckBoxActionPerformed mainCourseCheckBoxAction(this.cse202CheckBox); }//GEN-LAST:event_cse202CheckBoxActionPerformed private void cse302CheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cse302CheckBoxActionPerformed mainCourseCheckBoxAction(this.cse302CheckBox); }//GEN-LAST:event_cse302CheckBoxActionPerformed private void cse103CheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cse103CheckBoxActionPerformed mainCourseCheckBoxAction(this.cse103CheckBox); }//GEN-LAST:event_cse103CheckBoxActionPerformed private void cse203CheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cse203CheckBoxActionPerformed mainCourseCheckBoxAction(this.cse203CheckBox); }//GEN-LAST:event_cse203CheckBoxActionPerformed private void cse303CheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cse303CheckBoxActionPerformed mainCourseCheckBoxAction(this.cse303CheckBox); }//GEN-LAST:event_cse303CheckBoxActionPerformed //Lab Checkboxes private void cse111CheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cse111CheckBoxActionPerformed labCourseCheckBoxAction(this.cse111CheckBox); }//GEN-LAST:event_cse111CheckBoxActionPerformed private void cse112CheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cse112CheckBoxActionPerformed labCourseCheckBoxAction(this.cse112CheckBox); }//GEN-LAST:event_cse112CheckBoxActionPerformed private void cse211CheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cse211CheckBoxActionPerformed labCourseCheckBoxAction(this.cse211CheckBox); }//GEN-LAST:event_cse211CheckBoxActionPerformed private void cse212CheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cse212CheckBoxActionPerformed labCourseCheckBoxAction(this.cse212CheckBox); }//GEN-LAST:event_cse212CheckBoxActionPerformed private void cse311CheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cse311CheckBoxActionPerformed labCourseCheckBoxAction(this.cse311CheckBox); }//GEN-LAST:event_cse311CheckBoxActionPerformed private void cse312CheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cse312CheckBoxActionPerformed labCourseCheckBoxAction(this.cse312CheckBox); }//GEN-LAST:event_cse312CheckBoxActionPerformed private void findButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_findButtonMouseClicked if(checkIdNum(this.findStudentField.getText())) { int n = searchByID(this.findStudentField.getText()); if(n != -1) { setCurrentStudent(n); this.findStudentErrorText.setForeground(Color.GREEN); this.findStudentErrorText.setText(this.findStudentField.getText()+" is registered."+" \nPress XXX or XXX for more."); } else { this.findStudentErrorText.setText(this.findStudentField.getText()+" was not found!"); } } else { errorDialogue("Please enter the ID in correct format!\n" + " Format: 171-15-XXXX", 1); } }//GEN-LAST:event_findButtonMouseClicked private void dropStudentSearchButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dropStudentSearchButton1MouseClicked if(checkIdNum(this.findStudentDropField.getText())) { int n = searchByID(this.findStudentDropField.getText()); if(n != -1) { setCurrentStudent(n); updateStudentShowDetails(); displayUpdateStudentPanel(false, true); } else { this.updateFindStudentErrorText.setText(this.findStudentDropField.getText()+" was not found!"); } } else { errorDialogue("Please enter the ID in correct format!\n" + " Format: 171-15-XXXX", 1); } }//GEN-LAST:event_dropStudentSearchButton1MouseClicked private void dropStudentSearchButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dropStudentSearchButton2MouseClicked errorDialogueTwoButtonDrop("Are you sure you want to drop this student?"); }//GEN-LAST:event_dropStudentSearchButton2MouseClicked private void backFromResultViewMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_backFromResultViewMouseClicked if(this.fromMain) { displayResultPanel(false, false); panelVisiblity(true, false, false, false); refreshData(); return; } refreshData(); displayResultPanel(true, false); }//GEN-LAST:event_backFromResultViewMouseClicked private void resultSearchButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_resultSearchButton1MouseClicked if(checkIdNum(this.resultSearchField.getText())) { int n = searchByID(this.resultSearchField.getText()); if(n != -1) { setCurrentStudent(n); resultShowDetails(); displayResultPanel(false, true); } else { this.resultFindStudentErrorText.setText(this.findStudentDropField.getText()+" was not found!"); } } else { errorDialogue("Please enter the ID in correct format!\n" + " Format: 171-15-XXXX", 1); } }//GEN-LAST:event_resultSearchButton1MouseClicked private void updateButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_updateButtonMouseClicked if(getUpdateData()) { this.dataLoader.getStudents().add(this.dataLoader.getCurrentStudentIndex(), this.dataLoader.getCurrentStudent()); this.dataLoader.saveStudentData(); refreshData(); errorDialogue("Student data was updated!", 4); } else { errorDialogue("Student data was not updated!\nMake sure you typed the grades correctly.", -1); } }//GEN-LAST:event_updateButtonMouseClicked // </editor-fold> /** Below this line are the IDE generated variables **/ // <editor-fold defaultstate="collapsed" desc="Generated variables"> // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField addFathersNameField; private javax.swing.JRadioButton addFemaleCheck; private javax.swing.JRadioButton addMaleCheck; private javax.swing.JTextField addMothersNameField; private javax.swing.JTextField addStudentFullName; private javax.swing.JTextField addStudentID; private javax.swing.JPanel addStudentPanel; private javax.swing.JPanel admitStudentButton; private javax.swing.JLabel backFromMainLabelResult; private javax.swing.JSeparator backFromMainSepResult; private javax.swing.JPanel backFromResultView; private javax.swing.JLabel backLabelResult; private javax.swing.JSeparator backSepResult; private javax.swing.JLabel backToMainFromUpdateLabel; private javax.swing.JPanel cancelFromUpdate; private javax.swing.JLabel cancelFromUpdateLabel; private javax.swing.JTextField courseAGrade; private javax.swing.JLabel courseAName; private javax.swing.JLabel courseANameGrade; private javax.swing.JTextField courseBGrade; private javax.swing.JLabel courseBName; private javax.swing.JLabel courseBNameGrade; private javax.swing.JTextField courseCGrade; private javax.swing.JLabel courseCName; private javax.swing.JLabel courseCNameGrade; private javax.swing.JTextField courseDGrade; private javax.swing.JLabel courseDName; private javax.swing.JLabel courseDNameGrade; private javax.swing.JTextField courseEGrade; private javax.swing.JLabel courseEName; private javax.swing.JLabel courseENameGrade; private javax.swing.JTextField courseFGrade; private javax.swing.JLabel courseFName; private javax.swing.JLabel courseFNameGrade; private javax.swing.JPanel createProfileButtonPanel4; private javax.swing.JCheckBox cse101CheckBox; private javax.swing.JCheckBox cse102CheckBox; private javax.swing.JCheckBox cse103CheckBox; private javax.swing.JCheckBox cse111CheckBox; private javax.swing.JCheckBox cse112CheckBox; private javax.swing.JCheckBox cse201CheckBox; private javax.swing.JCheckBox cse202CheckBox; private javax.swing.JCheckBox cse203CheckBox; private javax.swing.JCheckBox cse211CheckBox; private javax.swing.JCheckBox cse212CheckBox; private javax.swing.JCheckBox cse301CheckBox; private javax.swing.JCheckBox cse302CheckBox; private javax.swing.JCheckBox cse303CheckBox; private javax.swing.JCheckBox cse311CheckBox; private javax.swing.JCheckBox cse312CheckBox; private javax.swing.JPanel dropStudentButton; private javax.swing.JPanel dropStudentSearchButton1; private javax.swing.JPanel dropStudentSearchButton2; private javax.swing.JLabel dropStudentSearchButtonLabel1; private javax.swing.JLabel dropStudentSearchButtonLabel2; private javax.swing.JLabel dropStudentSearchButtonLabel3; private javax.swing.JLabel fatherLabel4; private javax.swing.JPanel findButton; private javax.swing.JTextField findStudentDropField; private javax.swing.JLabel findStudentErrorText; private javax.swing.JTextField findStudentField; private javax.swing.JLabel genderLabel4; private javax.swing.JLabel idLabel4; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel22; private javax.swing.JLabel jLabel23; private javax.swing.JLabel jLabel24; private javax.swing.JLabel jLabel25; private javax.swing.JLabel jLabel26; private javax.swing.JLabel jLabel27; private javax.swing.JLabel jLabel28; private javax.swing.JLabel jLabel29; private javax.swing.JLabel jLabel30; private javax.swing.JLabel jLabel31; private javax.swing.JLabel jLabel32; private javax.swing.JLabel jLabel36; private javax.swing.JLabel jLabel38; private javax.swing.JLabel jLabel40; private javax.swing.JLabel jLabel41; private javax.swing.JLabel jLabel42; private javax.swing.JLabel jLabel43; private javax.swing.JLabel jLabel46; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator10; private javax.swing.JSeparator jSeparator13; private javax.swing.JSeparator jSeparator15; private javax.swing.JSeparator jSeparator2; private javax.swing.JSeparator jSeparator21; private javax.swing.JSeparator jSeparator22; private javax.swing.JSeparator jSeparator23; private javax.swing.JSeparator jSeparator24; private javax.swing.JSeparator jSeparator25; private javax.swing.JSeparator jSeparator26; private javax.swing.JSeparator jSeparator27; private javax.swing.JSeparator jSeparator3; private javax.swing.JSeparator jSeparator4; private javax.swing.JSeparator jSeparator5; private javax.swing.JSeparator jSeparator7; private javax.swing.JSeparator jSeparator9; private javax.swing.JPanel mainFromAdmit; private javax.swing.JPanel mainFromDrop1; private javax.swing.JPanel mainFromResult1; private javax.swing.JLabel motherLabel4; private javax.swing.JLabel nameLabel10; private javax.swing.JLabel nameLabel11; private javax.swing.JLabel nameLabel12; private javax.swing.JLabel nameLabel13; private javax.swing.JLabel nameLabel14; private javax.swing.JLabel nameLabel15; private javax.swing.JLabel nameLabel16; private javax.swing.JLabel nameLabel17; private javax.swing.JLabel nameLabel18; private javax.swing.JLabel nameLabel4; private javax.swing.JLabel nameLabel5; private javax.swing.JLabel nameLabel6; private javax.swing.JLabel nameLabel7; private javax.swing.JLabel nameLabel8; private javax.swing.JLabel nameLabel9; private javax.swing.JTextField resultCGPA; private javax.swing.JTextField resultCourseAGrade; private javax.swing.JLabel resultCourseAName; private javax.swing.JLabel resultCourseANameGrade; private javax.swing.JTextField resultCourseBGrade; private javax.swing.JLabel resultCourseBName; private javax.swing.JLabel resultCourseBNameGrade; private javax.swing.JTextField resultCourseCGrade; private javax.swing.JLabel resultCourseCName; private javax.swing.JLabel resultCourseCNameGrade; private javax.swing.JTextField resultCourseDGrade; private javax.swing.JLabel resultCourseDName; private javax.swing.JLabel resultCourseDNameGrade; private javax.swing.JTextField resultCourseEGrade; private javax.swing.JLabel resultCourseEName; private javax.swing.JLabel resultCourseENameGrade; private javax.swing.JTextField resultCourseFGrade; private javax.swing.JLabel resultCourseFName; private javax.swing.JLabel resultCourseFNameGrade; private javax.swing.JTextField resultFathersName; private javax.swing.JLabel resultFindStudentErrorText; private javax.swing.JTextField resultFullName; private javax.swing.JTextField resultGender; private javax.swing.JTextField resultMothersName; private javax.swing.JPanel resultPanel; private javax.swing.JTextField resultRemarks; private javax.swing.JPanel resultSearchButton1; private javax.swing.JTextField resultSearchField; private javax.swing.JPanel resultSearchPanel; private javax.swing.JTextField resultUpdateID; private javax.swing.JPanel resultViewPanel; private javax.swing.JLabel showSelectedCoursesCount; private javax.swing.JLabel showSelectedLabCoursesCount; private javax.swing.JPanel updateButton; private javax.swing.JTextField updateFathersName; private javax.swing.JLabel updateFindStudentErrorText; private javax.swing.JPanel updateFoundStudentPanel; private javax.swing.JTextField updateFullName; private javax.swing.JTextField updateGender; private javax.swing.JTextField updateID; private javax.swing.JTextField updateMothersName; private javax.swing.JPanel updateSearchStudentPanel; private javax.swing.JPanel updateStudentPanel; private javax.swing.JPanel viewResultButton; private javax.swing.JPanel welcomePanel; private javax.swing.JLabel welcomeText; // End of variables declaration//GEN-END:variables // </editor-fold> /** Custom variables **/ private DataHandler dataLoader = new DataHandler(); private Student student = new Student(); private ArrayList<Course> mainCourses = new ArrayList<>(); private ArrayList<Course> labCourses = new ArrayList<>(); private ArrayList<Course> courses; private int mainCourseCount = 0; private int labCourseCount = 0; private boolean fromMain = false; //K THEN LET IT RAIN DATA /** Admit panel methods **/ //Creates a empty course arraylist private void courseInit() { this.courses = new ArrayList<>(); for(int i=0; i < 6; i++) { if(i < 4) { this.courses.add(this.mainCourses.get(i)); } else { this.courses.add(this.labCourses.get(i-4)); } } } //GOAL Have to find out a better way to do this without repeating all these codes. DONE (for now) private void mainCourseCheckBoxAction(javax.swing.JCheckBox checkBox) { if(checkBox.isSelected() && this.mainCourseCount < 4) { this.mainCourses.add(new Course(checkBox.getText(), 0.0)); this.mainCourseCount++; //DEBUG System.out.println(""+this.mainCourseCount); this.showSelectedCoursesCount.setForeground(Color.RED); if(this.mainCourseCount == 4) { this.showSelectedCoursesCount.setForeground(Color.GREEN); } this.showSelectedCoursesCount.setText(""+this.mainCourseCount); } else if(this.mainCourseCount >= 4 && checkBox.isSelected()) { checkBox.setSelected(false); } else { deleteMainCourse(checkBox.getText()); this.mainCourseCount this.showSelectedCoursesCount.setForeground(Color.RED); this.showSelectedCoursesCount.setText(""+this.mainCourseCount); } } private void labCourseCheckBoxAction(javax.swing.JCheckBox checkBox) { if(checkBox.isSelected() && this.labCourseCount < 2) { this.labCourses.add(new Course(checkBox.getText(), 0.0)); this.labCourseCount++; //DEBUG System.out.println(""+this.labCourseCount); this.showSelectedLabCoursesCount.setForeground(Color.RED); if (this.labCourseCount == 2) { this.showSelectedLabCoursesCount.setForeground(Color.GREEN); } this.showSelectedLabCoursesCount.setText(""+(this.labCourseCount)); } else if(this.labCourseCount >= 2 && checkBox.isSelected()) { checkBox.setSelected(false); } else { deleteLabCourse(checkBox.getText()); this.labCourseCount this.showSelectedLabCoursesCount.setForeground(Color.RED); this.showSelectedLabCoursesCount.setText(""+(this.labCourseCount)); } } //This fucntion finds the index number of a Course array and deletes it private void deleteMainCourse(String courseName) { for(int i = 0; i < this.mainCourses.size(); i++) { if(this.mainCourses.get(i).getCourseName().equals(courseName)) { this.mainCourses.remove(i); return; } } } private void deleteLabCourse(String courseName) { for(int i = 0; i < this.labCourses.size(); i++) { if(this.labCourses.get(i).getCourseName().equals(courseName)) { this.labCourses.remove(i); return; } } } //Moar data, unverified private boolean addStudentInputERRPRN() { String fullName = this.addStudentFullName.getText(); String id = this.addStudentID.getText(); String fathersName = this.addFathersNameField.getText(); String mothersName = this.addMothersNameField.getText(); boolean verifiedFullName = checkFullName(fullName); boolean verifiedID = checkIdNum(id); boolean verifiedFathersName = checkFatherName(fathersName); boolean verifiedMothersName = checkMotherName(mothersName); if(this.addMaleCheck.isSelected() || this.addFemaleCheck.isSelected()) { if (this.addMaleCheck.isSelected()) { String gender = this.addMaleCheck.getText(); gender = gender.substring(0,1).toUpperCase() + gender.substring(1); this.student.setGender(gender); } if (this.addFemaleCheck.isSelected()) { String gender = this.addFemaleCheck.getText(); gender = gender.substring(0,1).toUpperCase() + gender.substring(1); this.student.setGender(gender); } } else { errorDialogue("Enter student's gender!", -1); } if (!verifiedFullName) { errorDialogue("Enter student's full name!", 0); } if (!verifiedID) { errorDialogue("Please enter the ID in correct format!\n" + " Format: 171-15-XXXX", 1); } if (!verifiedFathersName) { errorDialogue("Enter student's father's name!", 2); } if (!verifiedMothersName) { errorDialogue("Enter student's mother's name!", 3); } if(verifiedFullName && verifiedID && verifiedFathersName && verifiedMothersName && searchByID(id) < 0) { this.student.setIdNum(id); this.student.setFullName(fullName); this.student.setMotherName(mothersName); this.student.setFatherName(fathersName); return true; } else if(searchByID(id) > -1) { errorDialogue("There is aleady a student admitted under this id!", -1); return false; } return false; } private boolean checkIdNum(String idNum) { if(idNum.length() == 11) { if(Objects.equals(idNum.substring(0, 1), "1") && Objects.equals(idNum.substring(1, 2), "7") && Objects.equals(idNum.substring(2, 3), "1") && Objects.equals(idNum.substring(3, 4), "-") && Objects.equals(idNum.substring(4, 5), "1") && Objects.equals(idNum.substring(5, 6), "5") && Objects.equals(idNum.substring(6, 7), "-")) { return true; } } return false; } private boolean checkFullName(String fullName) { return !fullName.equals(""); } private boolean checkFatherName(String fatherName) { return !fatherName.equals(""); } private boolean checkMotherName(String motherName) { return !motherName.equals(""); } private boolean addCourseData() { if((this.mainCourseCount+this.labCourseCount) == 6) { courseInit(); this.student.setA(this.courses.get(0)); this.student.setB(this.courses.get(1)); this.student.setC(this.courses.get(2)); this.student.setD(this.courses.get(3)); this.student.setE(this.courses.get(4)); this.student.setF(this.courses.get(5)); return true; } else { return false; } } //Creates profile upon button press private void createStudentProfile() { if(addStudentInputERRPRN() && addCourseData()) { this.dataLoader.addStudent(this.student); this.dataLoader.saveStudentData(); refreshData(); errorDialogue("Student was admitted!", 5); } else { errorDialogue("Please check if all the informations were typed correctly.", -1); } } /** These methods are for update panel **/ //These methods are for displaying the Drop Student Panel private void displayUpdateStudentPanel(boolean search, boolean found) { panelVisiblity(false,false, true, false); this.updateSearchStudentPanel.setVisible(search); this.updateFoundStudentPanel.setVisible(found); } private boolean getUpdateData() { if(isValidGrade(this.courseAGrade.getText()) && isValidGrade(this.courseBGrade.getText()) && isValidGrade(this.courseCGrade.getText()) && isValidGrade(this.courseDGrade.getText()) && isValidGrade(this.courseEGrade.getText()) && isValidGrade(this.courseFGrade.getText())) { this.dataLoader.getCurrentStudent().setFullName(this.updateFullName.getText()); this.dataLoader.getCurrentStudent().setFatherName(this.updateFathersName.getText()); this.dataLoader.getCurrentStudent().setMotherName(this.updateMothersName.getText()); this.dataLoader.getCurrentStudent().getA().setGradePoints(Double.parseDouble(this.courseAGrade.getText())); this.dataLoader.getCurrentStudent().getB().setGradePoints(Double.parseDouble(this.courseBGrade.getText())); this.dataLoader.getCurrentStudent().getC().setGradePoints(Double.parseDouble(this.courseCGrade.getText())); this.dataLoader.getCurrentStudent().getD().setGradePoints(Double.parseDouble(this.courseDGrade.getText())); this.dataLoader.getCurrentStudent().getE().setGradePoints(Double.parseDouble(this.courseEGrade.getText())); this.dataLoader.getCurrentStudent().getF().setGradePoints(Double.parseDouble(this.courseFGrade.getText())); return true; } return false; } private void updateStudentShowDetails() { this.updateFullName.setText(this.dataLoader.getCurrentStudent().getFullName().toUpperCase()); this.updateFathersName.setText(this.dataLoader.getCurrentStudent().getFatherName().toUpperCase()); this.updateMothersName.setText(this.dataLoader.getCurrentStudent().getMotherName().toUpperCase()); this.updateID.setText(this.dataLoader.getCurrentStudent().getIdNum()); this.updateGender.setText(this.dataLoader.getCurrentStudent().getGender().toUpperCase()); this.courseAName.setText(this.dataLoader.getCurrentStudent().getA().getCourseName().toUpperCase()); this.courseBName.setText(this.dataLoader.getCurrentStudent().getB().getCourseName().toUpperCase()); this.courseCName.setText(this.dataLoader.getCurrentStudent().getC().getCourseName().toUpperCase()); this.courseDName.setText(this.dataLoader.getCurrentStudent().getD().getCourseName().toUpperCase()); this.courseEName.setText(this.dataLoader.getCurrentStudent().getE().getCourseName().toUpperCase()); this.courseFName.setText(this.dataLoader.getCurrentStudent().getF().getCourseName().toUpperCase()); this.courseANameGrade.setText(this.dataLoader.getCurrentStudent().getA().getCourseName().toUpperCase()); this.courseBNameGrade.setText(this.dataLoader.getCurrentStudent().getB().getCourseName().toUpperCase()); this.courseCNameGrade.setText(this.dataLoader.getCurrentStudent().getC().getCourseName().toUpperCase()); this.courseDNameGrade.setText(this.dataLoader.getCurrentStudent().getD().getCourseName().toUpperCase()); this.courseENameGrade.setText(this.dataLoader.getCurrentStudent().getE().getCourseName().toUpperCase()); this.courseFNameGrade.setText(this.dataLoader.getCurrentStudent().getF().getCourseName().toUpperCase()); this.courseAGrade.setText(""+this.dataLoader.getCurrentStudent().getA().getGradePoints()); this.courseBGrade.setText(""+this.dataLoader.getCurrentStudent().getB().getGradePoints()); this.courseCGrade.setText(""+this.dataLoader.getCurrentStudent().getC().getGradePoints()); this.courseDGrade.setText(""+this.dataLoader.getCurrentStudent().getD().getGradePoints()); this.courseEGrade.setText(""+this.dataLoader.getCurrentStudent().getE().getGradePoints()); this.courseFGrade.setText(""+this.dataLoader.getCurrentStudent().getF().getGradePoints()); } //Grade value checker private boolean isDouble(String str) { try { Double.parseDouble(str); return true; } catch (NumberFormatException e) { return false; } } private boolean isValidGrade(String str) { boolean isDouble = isDouble(str); if(isDouble) { double grade = Double.parseDouble(str); return grade == 0.0d || grade == 2.0d || grade == 2.25d || grade == 2.5d || grade == 2.75d || grade == 3.0d || grade == 3.25d || grade == 3.5d || grade == 3.75d || grade == 4.0d; } return false; } /** These methods are for the Result Panel **/ private void displayResultPanel(boolean search, boolean view) { panelVisiblity(false,false, false, true); this.resultSearchPanel.setVisible(search); this.resultViewPanel.setVisible(view); } private void resultShowDetails() { this.resultFullName.setText(this.dataLoader.getCurrentStudent().getFullName().toUpperCase()); this.resultFathersName.setText(this.dataLoader.getCurrentStudent().getFatherName().toUpperCase()); this.resultMothersName.setText(this.dataLoader.getCurrentStudent().getMotherName().toUpperCase()); this.resultUpdateID.setText(this.dataLoader.getCurrentStudent().getIdNum()); this.resultGender.setText(this.dataLoader.getCurrentStudent().getGender().toUpperCase()); this.resultCourseAName.setText(this.dataLoader.getCurrentStudent().getA().getCourseName().toUpperCase()); this.resultCourseBName.setText(this.dataLoader.getCurrentStudent().getB().getCourseName().toUpperCase()); this.resultCourseCName.setText(this.dataLoader.getCurrentStudent().getC().getCourseName().toUpperCase()); this.resultCourseDName.setText(this.dataLoader.getCurrentStudent().getD().getCourseName().toUpperCase()); this.resultCourseEName.setText(this.dataLoader.getCurrentStudent().getE().getCourseName().toUpperCase()); this.resultCourseFName.setText(this.dataLoader.getCurrentStudent().getF().getCourseName().toUpperCase()); this.resultCourseANameGrade.setText(this.dataLoader.getCurrentStudent().getA().getCourseName().toUpperCase()); this.resultCourseBNameGrade.setText(this.dataLoader.getCurrentStudent().getB().getCourseName().toUpperCase()); this.resultCourseCNameGrade.setText(this.dataLoader.getCurrentStudent().getC().getCourseName().toUpperCase()); this.resultCourseDNameGrade.setText(this.dataLoader.getCurrentStudent().getD().getCourseName().toUpperCase()); this.resultCourseENameGrade.setText(this.dataLoader.getCurrentStudent().getE().getCourseName().toUpperCase()); this.resultCourseFNameGrade.setText(this.dataLoader.getCurrentStudent().getF().getCourseName().toUpperCase()); this.resultCourseAGrade.setText(""+this.dataLoader.getCurrentStudent().getA().getGradePoints()); this.resultCourseBGrade.setText(""+this.dataLoader.getCurrentStudent().getB().getGradePoints()); this.resultCourseCGrade.setText(""+this.dataLoader.getCurrentStudent().getC().getGradePoints()); this.resultCourseDGrade.setText(""+this.dataLoader.getCurrentStudent().getD().getGradePoints()); this.resultCourseEGrade.setText(""+this.dataLoader.getCurrentStudent().getE().getGradePoints()); this.resultCourseFGrade.setText(""+this.dataLoader.getCurrentStudent().getF().getGradePoints()); generateRemarks(); } private void generateRemarks() { double mainPoints = 0; double labPoints = 0; mainPoints += this.dataLoader.getCurrentStudent().getA().getGradePoints(); mainPoints += this.dataLoader.getCurrentStudent().getB().getGradePoints(); mainPoints += this.dataLoader.getCurrentStudent().getC().getGradePoints(); mainPoints += this.dataLoader.getCurrentStudent().getD().getGradePoints(); labPoints += this.dataLoader.getCurrentStudent().getE().getGradePoints(); labPoints += this.dataLoader.getCurrentStudent().getF().getGradePoints(); double cgpa = ((mainPoints*3d) + (labPoints*1d)) / 14d; if(cgpa == 0.0) { this.resultCGPA.setForeground(Color.red); this.resultCGPA.setText(""+cgpa); this.resultRemarks.setForeground(Color.red); this.resultRemarks.setText("FAILED"); } else if(cgpa == 2.0) { this.resultCGPA.setForeground(Color.green); this.resultCGPA.setText(""+cgpa); this.resultRemarks.setForeground(Color.green); this.resultRemarks.setText("PASS"); } else if(cgpa == 2.25) { this.resultCGPA.setForeground(Color.green); this.resultCGPA.setText(""+cgpa); this.resultRemarks.setForeground(Color.green); this.resultRemarks.setText("BELOW AVERAGE"); } else if(cgpa == 2.50) { this.resultCGPA.setForeground(Color.green); this.resultCGPA.setText(""+cgpa); this.resultRemarks.setForeground(Color.green); this.resultRemarks.setText("AVERAGE"); } else if(cgpa == 2.75) { this.resultCGPA.setForeground(Color.green); this.resultCGPA.setText(""+cgpa); this.resultRemarks.setForeground(Color.green); this.resultRemarks.setText("ABOVE AVERAGE"); } else if(cgpa == 3.0) { this.resultCGPA.setForeground(Color.green); this.resultCGPA.setText(""+cgpa); this.resultRemarks.setForeground(Color.green); this.resultRemarks.setText("SATISFACTORY"); } else if(cgpa == 3.25) { this.resultCGPA.setForeground(Color.green); this.resultCGPA.setText(""+cgpa); this.resultRemarks.setForeground(Color.green); this.resultRemarks.setText("GOOD"); } else if(cgpa == 3.5) { this.resultCGPA.setForeground(Color.green); this.resultCGPA.setText(""+cgpa); this.resultRemarks.setForeground(Color.green); this.resultRemarks.setText("VERY GOOD"); } else if(cgpa == 3.75) { this.resultCGPA.setForeground(Color.green); this.resultCGPA.setText(""+cgpa); this.resultRemarks.setForeground(Color.green); this.resultRemarks.setText("EXCELLENT"); } else if(cgpa == 4.0) { this.resultCGPA.setForeground(Color.blue); this.resultCGPA.setText(""+cgpa); this.resultRemarks.setForeground(Color.blue); this.resultRemarks.setText("OUTSTANDING"); } } /** Universal methods **/ //This method shows one panel at a time on screen private void panelVisiblity(boolean welcomePanel, boolean addStudentPanel, boolean dropStudentPanel, boolean viewResultPanel){ this.welcomePanel.setVisible(welcomePanel); this.addStudentPanel.setVisible(addStudentPanel); this.updateStudentPanel.setVisible(dropStudentPanel); this.resultPanel.setVisible(viewResultPanel); } //Screen clearing methods private void clearText() { this.findStudentErrorText.setForeground(Color.RED); this.findStudentErrorText.setText(""); } //Universal ID search method private int searchByID(String id) { for(Student eachStudent: this.dataLoader.getStudents()) { if(eachStudent.getIdNum().equals(id)) { return this.dataLoader.getStudents().indexOf(eachStudent); } } return -1; } //Sets current student for eiditing/updating (if found) private void setCurrentStudent(int index) { this.dataLoader.setCurrentStudent(this.dataLoader.getStudents().get(index)); this.dataLoader.setCurrentStudentIndex(index); } private void refreshData() { this.dataLoader.setCurrentStudent(null); this.dataLoader.setCurrentStudentIndex(-1); this.student = new Student(); this.courses = new ArrayList<>(6); this.mainCourseCount = 0; } //Shows context based error dialogue private void errorDialogue(String messageString, int whichField) { Object[] message = {messageString}; Object[] options = {"OK"}; int n = JOptionPane.showOptionDialog(new JFrame(), message, "Alert!", JOptionPane.ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE, null, options, options[0]); if(JOptionPane.ERROR_MESSAGE == n && whichField == 0){ this.addStudentFullName.setText(""); } else if(n == JOptionPane.ERROR_MESSAGE && whichField == 1){ this.addStudentID.setText("171-15-XXXX"); } else if(n == JOptionPane.ERROR_MESSAGE && whichField == 2){ this.addFathersNameField.setText(""); } else if(n == JOptionPane.ERROR_MESSAGE && whichField == 3){ this.addMothersNameField.setText(""); } else if(n == JOptionPane.ERROR_MESSAGE && whichField == 4){ displayUpdateStudentPanel(true, false); } else if(n == JOptionPane.ERROR_MESSAGE && whichField == 5){ panelVisiblity(true, false, false, false); } else { //DO NOTHING JUST DISPLAY MESSAGE } } private void errorDialogueTwoButtonDrop(String messageString) { Object[] message = {messageString}; Object[] options = {"YES", "NO"}; int n = JOptionPane.showOptionDialog(new JFrame(), message, "Alert!", JOptionPane.OK_OPTION, JOptionPane.CANCEL_OPTION, null, options, options[1]); switch (n) { case JOptionPane.OK_OPTION: this.dataLoader.dropStudent(this.dataLoader.getCurrentStudentIndex()); this.dataLoader.saveStudentData(); refreshData(); panelVisiblity(true, false, false, false); break; case JOptionPane.CANCEL_OPTION: break; default: break; } } private void backToMainVisible(boolean value) { } }
package be.ibridge.kettle.core.dialog; import java.util.List; import org.eclipse.swt.SWT; import be.ibridge.kettle.core.GUIResource; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import be.ibridge.kettle.core.ColumnInfo; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.Props; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.WindowProperty; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.core.widget.TableView; import be.ibridge.kettle.trans.step.BaseStepDialog; /** * Displays an ArrayList of rows in a TableView. * * @author Matt * @since 19-06-2003 */ public class PreviewRowsDialog extends Dialog { private String stepname; private Label wlFields; private TableView wFields; private FormData fdlFields, fdFields; private Button wClose; private Listener lsClose; private Button wLog; private Listener lsLog; private Shell shell; private List buffer; private Props props; private String title, message; private Rectangle bounds; private int hscroll, vscroll; private int hmax, vmax; private String loggingText; /** * @deprecated Use CT without the <i>log</i> and <i>props</i> parameter */ public PreviewRowsDialog(Shell parent, int style, LogWriter log, Props props, String stepName, List rowBuffer) { this(parent, style, stepName, rowBuffer, null); this.props = props; } public PreviewRowsDialog(Shell parent, int style, String stepName, List rowBuffer) { this(parent, style, stepName, rowBuffer, null); } public PreviewRowsDialog(Shell parent, int style, String stepName, List rowBuffer, String loggingText) { super(parent, style); this.stepname = stepName; this.buffer = rowBuffer; this.loggingText = loggingText; props = Props.getInstance(); bounds = null; hscroll = -1; vscroll = -1; title = null; message = null; } public void setTitleMessage(String title, String message) { this.title = title; this.message = message; } public Object open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX); props.setLook(shell); shell.setImage(GUIResource.getInstance().getImageConnection()); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; if (title == null) title = Messages.getString("PreviewRowsDialog.Title"); if (message == null) message = Messages.getString("PreviewRowsDialog.Header", stepname); shell.setLayout(formLayout); shell.setText(title); // int middle = props.getMiddlePct(); int margin = Const.MARGIN; wlFields = new Label(shell, SWT.LEFT); wlFields.setText(message); props.setLook(wlFields); fdlFields = new FormData(); fdlFields.left = new FormAttachment(0, 0); fdlFields.right = new FormAttachment(100, 0); fdlFields.top = new FormAttachment(0, margin); wlFields.setLayoutData(fdlFields); // Mmm, if we don't get any rows in the buffer: show a dialog box. if (buffer == null || buffer.size() == 0) { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING); mb.setMessage(Messages.getString("PreviewRowsDialog.NoRows.Message")); mb.setText(Messages.getString("PreviewRowsDialog.NoRows.Text")); mb.open(); shell.dispose(); return null; } Row row = (Row) buffer.get(0); int FieldsRows = buffer.size(); ColumnInfo[] colinf = new ColumnInfo[row.size()]; for (int i = 0; i < row.size(); i++) { Value v = row.getValue(i); colinf[i] = new ColumnInfo(v.getName(), ColumnInfo.COLUMN_TYPE_TEXT, v.isNumeric()); colinf[i].setToolTip(v.toStringMeta()); colinf[i].setValueType(v.getType()); } wFields = new TableView(shell, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, colinf, FieldsRows, null, props); fdFields = new FormData(); fdFields.left = new FormAttachment(0, 0); fdFields.top = new FormAttachment(wlFields, margin); fdFields.right = new FormAttachment(100, 0); fdFields.bottom = new FormAttachment(100, -50); wFields.setLayoutData(fdFields); wClose = new Button(shell, SWT.PUSH); wClose.setText(Messages.getString("System.Button.Close")); wLog = new Button(shell, SWT.PUSH); wLog.setText(Messages.getString("PreviewRowsDialog.Button.ShowLog")); if (loggingText == null || loggingText.length() == 0) wLog.setEnabled(false); // Add listeners lsClose = new Listener() { public void handleEvent(Event e) { close(); } }; lsLog = new Listener() { public void handleEvent(Event e) { log(); } }; wClose.addListener(SWT.Selection, lsClose ); wLog.addListener(SWT.Selection, lsLog ); BaseStepDialog.positionBottomButtons(shell, new Button[] { wClose, wLog }, margin, null); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { close(); } } ); getData(); BaseStepDialog.setSize(shell); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return stepname; } public void dispose() { props.setScreen(new WindowProperty(shell)); bounds = shell.getBounds(); hscroll = wFields.getHorizontalBar().getSelection(); vscroll = wFields.getVerticalBar().getSelection(); shell.dispose(); } /** * Copy information from the meta-data input to the dialog fields. */ private void getData() { shell.getDisplay().asyncExec(new Runnable() { public void run() { for (int i = 0; i < buffer.size(); i++) { TableItem item = wFields.table.getItem(i); Row row = (Row) buffer.get(i); for (int c = 0; c < row.size(); c++) { Value v = row.getValue(c); String show = v.toString(false); /* if (v.isNumeric()) show = v.toString(true); else show = v.toString(false); */ if (show != null) item.setText(c + 1, show); } } wFields.optWidth(true, 200); } }); } private void close() { stepname = null; dispose(); } /** * Show the logging of the preview (in case errors occurred */ private void log() { if (loggingText != null) { EnterTextDialog etd = new EnterTextDialog(shell, Messages .getString("PreviewRowsDialog.ShowLogging.Title"), Messages .getString("PreviewRowsDialog.ShowLogging.Message"), loggingText); etd.open(); } }; public boolean isDisposed() { return shell.isDisposed(); } public Rectangle getBounds() { return bounds; } public void setBounds(Rectangle b) { bounds = b; } public int getHScroll() { return hscroll; } public void setHScroll(int s) { hscroll = s; } public int getVScroll() { return vscroll; } public void setVScroll(int s) { vscroll = s; } public int getHMax() { return hmax; } public void setHMax(int m) { hmax = m; } public int getVMax() { return vmax; } public void setVMax(int m) { vmax = m; } }
package com.bluetag.api.search.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; //import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.bluetag.api.search.service.SearchService; @Path("/search/users") public class SearchResource { @GET @Produces(MediaType.APPLICATION_JSON) public String searchUsers(@QueryParam("q") String queryString){ SearchService searchService = new SearchService(); System.out.println("SearchResource.searchUsers - queryString: "+ queryString); return searchService.searchUsers(queryString); } }
package com.rethinkdb.net; import com.rethinkdb.gen.ast.Datum; import com.rethinkdb.gen.exc.ReqlDriverError; import com.rethinkdb.model.GroupedResult; import com.rethinkdb.model.MapObject; import com.rethinkdb.model.OptArgs; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.Base64; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Converter { private static final Base64.Decoder b64decoder = Base64.getMimeDecoder(); private static final Base64.Encoder b64encoder = Base64.getMimeEncoder(); public static final String PSEUDOTYPE_KEY = "$reql_type$"; public static final String TIME = "TIME"; public static final String GROUPED_DATA = "GROUPED_DATA"; public static final String GEOMETRY = "GEOMETRY"; public static final String BINARY = "BINARY"; /* Compact way of keeping these flags around through multiple recursive passes */ public static class FormatOptions{ public final boolean rawTime; public final boolean rawGroups; public final boolean rawBinary; public FormatOptions(OptArgs args){ this.rawTime = ((Datum)args.getOrDefault("time_format", new Datum("native"))).datum.equals("raw"); this.rawBinary = ((Datum)args.getOrDefault("binary_format", new Datum("native"))).datum.equals("raw"); this.rawGroups = ((Datum)args.getOrDefault("group_format", new Datum("native"))).datum.equals("raw"); } } @SuppressWarnings("unchecked") public static Object convertPseudotypes(Object obj, FormatOptions fmt){ if(obj instanceof List) { return ((List) obj).stream() .map(item -> convertPseudotypes(item, fmt)) .collect(Collectors.toList()); } else if(obj instanceof Map) { Map<String, Object> mapobj = (Map) obj; if(mapobj.containsKey(PSEUDOTYPE_KEY)){ return convertPseudo(mapobj, fmt); } return mapobj.entrySet().stream() .collect( HashMap::new, (map, entry) -> map.put( entry.getKey(), convertPseudotypes(entry.getValue(), fmt) ), HashMap<String, Object>::putAll ); } else { return obj; } } public static Object convertPseudo(Map<String, Object> value, FormatOptions fmt) { if(value == null){ return null; } String reqlType = (String) value.get(PSEUDOTYPE_KEY); switch (reqlType) { case TIME: return fmt.rawTime ? value : getTime(value); case GROUPED_DATA: return fmt.rawGroups ? value : getGrouped(value); case BINARY: return fmt.rawBinary ? value : getBinary(value); case GEOMETRY: // Nothing specific here return value; default: // Just leave unknown pseudo-types alone return value; } } @SuppressWarnings("unchecked") private static List<GroupedResult> getGrouped(Map<String, Object> value) { return ((List<List<Object>>) value.get("data")).stream() .map(g -> new GroupedResult(g.remove(0), g)) .collect(Collectors.toList()); } private static OffsetDateTime getTime(Map<String, Object> obj) { try { ZoneOffset offset = ZoneOffset.of((String) obj.get("timezone")); Double epochTime = ((Number) obj.get("epoch_time")).doubleValue(); Instant timeInstant = Instant.ofEpochMilli(((Double) (epochTime * 1000.0)).longValue()); return OffsetDateTime.ofInstant(timeInstant, offset); } catch (Exception ex) { throw new ReqlDriverError("Error handling date", ex); } } @SuppressWarnings("unchecked") private static byte[] getBinary(Map<String, Object> value) { String str = (String) value.get("data"); return b64decoder.decode(str); } public static Map<String,Object> toBinary(byte[] data){ MapObject mob = new MapObject(); mob.with("$reql_type$", BINARY); mob.with("data", b64encoder.encodeToString(data)); return mob; } }
package org.drools.core.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.DatagramSocket; import java.net.ServerSocket; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class IoUtils { public static final Charset UTF8_CHARSET = Charset.forName("UTF-8"); public static int findPort() { for( int i = 1024; i < 65535; i++) { if ( validPort( i ) ) { return i; } } throw new RuntimeException( "No valid port could be found" ); } public static boolean validPort(int port) { ServerSocket ss = null; DatagramSocket ds = null; try { ss = new ServerSocket(port); ss.setReuseAddress(true); ds = new DatagramSocket(port); ds.setReuseAddress(true); return true; } catch (IOException e) { } finally { if (ds != null) { ds.close(); } if (ss != null) { try { ss.close(); } catch (IOException e) { /* should not be thrown */ } } } return false; } public static String readFileAsString(File file) { StringBuffer sb = new StringBuffer(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), IoUtils.UTF8_CHARSET)); for (String line = reader.readLine(); line != null; line = reader.readLine()) { sb.append(line).append("\n"); } } catch (IOException e) { throw new RuntimeException(e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } return sb.toString(); } public static void copyFile(File sourceFile, File destFile) { destFile.getParentFile().mkdirs(); if(!destFile.exists()) { try { destFile.createNewFile(); } catch (IOException ioe) { throw new RuntimeException("Unable to create file " + destFile.getAbsolutePath(), ioe); } } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } catch (IOException ioe) { throw new RuntimeException("Unable to copy " + sourceFile.getAbsolutePath() + " to " + destFile.getAbsolutePath(), ioe); } finally { if(source != null) { try { source.close(); } catch (IOException e) { } } if(destination != null) { try { destination.close(); } catch (IOException e) { } } } } public static Map<String, byte[]> indexZipFile(java.io.File jarFile) { Map<String, byte[]> files = new HashMap<String, byte[]>(); ZipFile zipFile = null; try { zipFile = new ZipFile( jarFile ); Enumeration< ? extends ZipEntry> entries = zipFile.entries(); while ( entries.hasMoreElements() ) { ZipEntry entry = entries.nextElement(); byte[] bytes = readBytesFromInputStream( zipFile.getInputStream( entry ) ); files.put( entry.getName(), bytes ); } } catch ( IOException e ) { throw new RuntimeException( "Unable to get all ZipFile entries: " + jarFile, e ); } finally { if ( zipFile != null ) { try { zipFile.close(); } catch ( IOException e ) { throw new RuntimeException( "Unable to get all ZipFile entries: " + jarFile, e ); } } } return files; } public static List<String> recursiveListFile(File folder) { return recursiveListFile(folder, "", Predicate.PassAll.INSTANCE); } public static List<String> recursiveListFile(File folder, String prefix, Predicate<? super File> filter) { List<String> files = new ArrayList<String>(); for (File child : safeListFiles(folder)) { filesInFolder(files, child, prefix, filter); } return files; } private static void filesInFolder(List<String> files, File file, String relativePath, Predicate<? super File> filter) { if (file.isDirectory()) { relativePath += file.getName() + "/"; for (File child : safeListFiles(file)) { filesInFolder(files, child, relativePath, filter); } } else { if (filter.apply(file)) { files.add(relativePath + file.getName()); } } } private static File[] safeListFiles(final File file) { final File[] children = file.listFiles(); if (children != null) { return children; } else { throw new IllegalArgumentException(String.format("Unable to retrieve contents of directory '%s'.", file.getAbsolutePath())); } } public static byte[] readBytesFromInputStream(InputStream input) throws IOException { int length = input.available(); byte[] buffer = new byte[Math.max(length, 8192)]; ByteArrayOutputStream output = new ByteArrayOutputStream(buffer.length); if (length > 0) { int n = input.read(buffer); output.write(buffer, 0, n); } int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); } return output.toByteArray(); } public static byte[] readBytesFromZipEntry(File file, ZipEntry entry) throws IOException { if ( entry == null ) { return null; } ZipFile zipFile = null; byte[] bytes = null; try { zipFile = new ZipFile( file ); bytes = IoUtils.readBytesFromInputStream( zipFile.getInputStream( entry ) ); } finally { if ( zipFile != null ) { zipFile.close(); } } return bytes; } public static byte[] readBytes(File f) throws IOException { byte[] buf = new byte[1024]; BufferedInputStream bais = null; ByteArrayOutputStream baos = null; try { bais = new BufferedInputStream( new FileInputStream( f ) ); baos = new ByteArrayOutputStream(); int len; while ( (len = bais.read( buf )) > 0 ) { baos.write( buf, 0, len ); } } finally { if ( baos != null ) { baos.close(); } if ( bais != null ) { bais.close(); } } return baos.toByteArray(); } public static void write(File f, byte[] data) throws IOException { if ( f.exists() ) { // we want to make sure there is a time difference for lastModified and lastRead checks as Linux and http often round to seconds try { Thread.sleep( 1000 ); } catch ( Exception e ) { throw new RuntimeException( "Unable to sleep" ); } } // Attempt to write the file writeBytes(f, data ); // Now check the file was written and re-attempt if it was not // Need to do this for testing, to ensure the texts are read the same way, otherwise sometimes you get tail \n sometimes you don't int count = 0; while ( !areByteArraysEqual(data, readBytes( f ) ) && count < 5 ) { // The file failed to write, try 5 times, calling GC and sleep between each iteration // Sometimes windows takes a while to release a lock on a file System.gc(); try { Thread.sleep( 250 ); } catch ( InterruptedException e ) { throw new RuntimeException( "This should never happen" ); } writeBytes(f, data ); count++; } //areByteArraysEqual if ( count == 5 ) { throw new IOException( "Unable to write to file:" + f.getCanonicalPath() ); } } public static void writeBytes(File f, byte[] data) throws IOException { byte[] buf = new byte[1024]; BufferedOutputStream bos = null; ByteArrayInputStream bais = null; try { bos = new BufferedOutputStream( new FileOutputStream(f) ); bais = new ByteArrayInputStream( data ); int len; while ( (len = bais.read( buf )) > 0 ) { bos.write( buf, 0, len ); } } finally { if ( bos != null ) { bos.close(); } if ( bais != null ) { bais.close(); } } } public static boolean areByteArraysEqual(byte[] b1, byte[] b2) { if ( b1.length != b2.length ) { return false; } for ( int i = 0, length = b1.length; i < length; i++ ) { if ( b1[i] != b2[i] ) { return false; } } return true; } public static String asSystemSpecificPath(String urlPath, int colonIndex) { String ic = urlPath.substring( Math.max( 0, colonIndex - 2 ), colonIndex + 1 ); if ( ic.matches( "\\/[A-Z]:" ) ) { return urlPath.substring( colonIndex - 2 ); } else if ( ic.matches( "[A-Z]:" ) ) { return urlPath.substring( colonIndex - 1 ); } else { return urlPath.substring( colonIndex + 1 ); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.edinarobotics.zephyr.autonomous; import com.edinarobotics.utils.autonomous.AutonomousStep; import com.edinarobotics.zephyr.Zephyr; import edu.wpi.first.wpilibj.Timer; /** * * @author Danny */ public class ShooterStep extends AutonomousStep{ private static final double SHOOTER_WARMUP_DELAY = 3; private static final double SHOOTER_PISTON_UP_TIME = 0.5; double shooterSpeed; Zephyr robot; Timer time; boolean isFinished; public ShooterStep(double shooterSpeed,Zephyr robot) { this.shooterSpeed = shooterSpeed; this.robot = robot; time = new Timer(); isFinished = false; } public void start() { robot.shooterSpeed = -shooterSpeed; robot.mechanismSet(); time.start(); } public void run() { if(time.get() >= SHOOTER_WARMUP_DELAY+SHOOTER_PISTON_UP_TIME){ robot.ballLoaderUp = false; robot.mechanismSet(); isFinished = true; } else if(time.get() >= SHOOTER_WARMUP_DELAY){ robot.ballLoaderUp = true; robot.mechanismSet(); } else{ robot.mechanismSet(); } } public boolean isFinished() { return isFinished; } public void stop(){ robot.shooterSpeed = 0; robot.mechanismSet(); } }
package com.frc4732.AerialAssist.commands; import com.frc4732.AerialAssist.RobotMap; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * * @author qasim */ public class OperatorDrive extends CommandBase { public OperatorDrive() { // Use requires() here to declare subsystem dependencies requires(driveTrain); } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { double moveAxis = oi.getMoveAxis(), rotateAxis = oi.getRotateAxis(); if(Math.abs(moveAxis) >= 0.02 || Math.abs(rotateAxis) >= 0.02) { if(!oi.isHeld(RobotMap.XBOX_CONTROLLER.LEFT_STICK_BUTTON)) { moveAxis *= 0.77; } if(!oi.isHeld(RobotMap.XBOX_CONTROLLER.RIGHT_STICK_BUTTON)) { rotateAxis *= 0.77; } if(oi.isHeld(RobotMap.XBOX_CONTROLLER.L_BUTTON)) { moveAxis *= -1; moveAxis *= 0.5; rotateAxis *= 0.6; } driveTrain.arcadeDrive((Math.abs(moveAxis) >= 0.02) ? moveAxis : 0, (Math.abs(rotateAxis) >= 0.02) ? rotateAxis : 0); } SmartDashboard.putNumber("Move Axis", moveAxis); SmartDashboard.putNumber("Rotate Axis", rotateAxis); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { end(); } }
package com.jcwhatever.bukkit.pvs.listeners; import com.jcwhatever.bukkit.generic.extended.MaterialExt; import com.jcwhatever.bukkit.generic.items.ItemStackHelper; import com.jcwhatever.bukkit.pvs.PVArenaPlayer; import com.jcwhatever.bukkit.pvs.api.arena.Arena; import com.jcwhatever.bukkit.pvs.api.arena.ArenaPlayer; import com.jcwhatever.bukkit.pvs.api.arena.ArenaTeam; import com.jcwhatever.bukkit.pvs.api.arena.settings.PlayerManagerSettings; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.projectiles.ProjectileSource; public class PvpListener implements Listener { /* Handle player item repair */ @EventHandler private void onPlayerInteract(PlayerInteractEvent event) { if (!event.hasBlock()) return; ArenaPlayer player = PVArenaPlayer.get(event.getPlayer()); Arena arena = player.getArena(); if (arena == null) return; ItemStack inHand = event.getPlayer().getItemInHand(); if (inHand == null) return; PlayerManagerSettings settings = player.getRelatedSettings(); if (settings == null) return; MaterialExt materialExt = MaterialExt.from(inHand.getType()); if ((materialExt.isTool() && !settings.isToolsDamageable()) || (materialExt.isWeapon() && !settings.isWeaponsDamageable())) { event.setCancelled(true); } } @EventHandler private void onArmorDamage(EntityDamageEvent event) { Entity entity = event.getEntity(); if (!(entity instanceof Player)) return; Player p = (Player)entity; ArenaPlayer player =PVArenaPlayer.get(p); Arena arena = player.getArena(); if (arena == null) return; // get settings PlayerManagerSettings settings = player.getRelatedSettings(); if (settings == null) return; // prevent armor damage if (!settings.isArmorDamageable()) { ItemStackHelper.repair(p.getInventory().getArmorContents()); } } /* Handle PVP */ @EventHandler(priority= EventPriority.NORMAL) private void onPVP(EntityDamageByEntityEvent event) { Entity entity = event.getEntity(); if (!(entity instanceof Player)) return; Player p = (Player)entity; ArenaPlayer player =PVArenaPlayer.get(p); Arena arena = player.getArena(); if (arena == null) return; // no damage when game is over if (arena.getGameManager().isGameOver()) { event.setDamage(0.0); event.setCancelled(true); return; } // get settings PlayerManagerSettings settings = player.getRelatedSettings(); if (settings == null) return; // prevent pvp if (!settings.isPvpEnabled() || !settings.isTeamPvpEnabled()) { Entity damagerEntity = event.getDamager(); Player damager = null; // get damager if (damagerEntity instanceof Projectile) { ProjectileSource source = ((Projectile) damagerEntity).getShooter(); if (source instanceof Player) { damager = (Player) source; } } else if (damagerEntity instanceof Player) { damager = (Player) damagerEntity; } // handle player on player damage if (damager != null) { // check for pvp if (!settings.isPvpEnabled()) { event.setDamage(0.0); event.setCancelled(true); } // check for team pvp else //noinspection ConstantConditions if (!settings.isTeamPvpEnabled()) { // always true, statement is for readability ArenaPlayer damagerPlayer =PVArenaPlayer.get(p); // prevent team pvp if (damagerPlayer.getTeam() == player.getTeam() && damagerPlayer.getTeam() != ArenaTeam.NONE || player.getTeam() != ArenaTeam.NONE) { event.setDamage(0.0D); event.setCancelled(true); } } } } } }