repo_name
stringlengths 7
104
| file_path
stringlengths 13
198
| context
stringlengths 67
7.15k
| import_statement
stringlengths 16
4.43k
| code
stringlengths 40
6.98k
| prompt
stringlengths 227
8.27k
| next_line
stringlengths 8
795
|
---|---|---|---|---|---|---|
AlexisChevalier/CarRental-Android-Application | app/src/main/java/com/vehiclerental/utils/DateUtils.java | // Path: app/src/main/java/com/vehiclerental/CarRentalApplication.java
// public class CarRentalApplication extends Application {
//
// //Static access to context and ssl parameters
// private static Application application;
// private static SSLContext sslContext;
//
// /**
// * Returns the current application object
// *
// * @return application object
// */
// public static Application getApplication() {
// return application;
// }
//
// /**
// * Returns the current application context
// *
// * @return application context
// */
// public static Context getAppContext() {
// return getApplication().getApplicationContext();
// }
//
// /**
// * Returns the current SSL parameters
// *
// * @return SSL context parameters
// */
// public static SSLContext getSslContext() {
// return sslContext;
// }
//
// @Override
// public void onCreate() {
// //At the beginning of the application, a reference to the app is stored and the SSL parameters are initialized
// super.onCreate();
// application = this;
//
// setupSslTrustStore();
// }
//
// /**
// * Sets up the SSL trust store, containing the encryption keys for encrypted socket communication
// *
// * The keystore was generated with this tool: http://www.keystore-explorer.org/downloads.php
// */
// private void setupSslTrustStore() {
// try {
// char[] password = "carrental".toCharArray();
//
// KeyStore keyStore = KeyStore.getInstance("BKS");
// keyStore.load(this.getResources().openRawResource(R.raw.carrental_keystore), password);
//
// TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// trustManagerFactory.init(keyStore);
//
// KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// keyManagerFactory.init(keyStore, password);
//
// // Create a SSLContext with the certificate
// sslContext = SSLContext.getInstance("TLS");
// sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
// } catch (NoSuchAlgorithmException | KeyStoreException | IOException | KeyManagementException | CertificateException | UnrecoverableKeyException e) {
// e.printStackTrace();
// Log.e("SSL", "Failed to create SSL context");
// }
// }
// }
| import com.vehiclerental.R;
import com.vehiclerental.CarRentalApplication;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone; | /**
* CarRental
*
* This file provides date management abstraction methods
* I am using UTC as common timezone
* The dates are encoded using the ISO8601 format to be sent over the network
*/
package com.vehiclerental.utils;
public class DateUtils {
//Results of the comparison system
public final static int DATE1_BEFORE_DATE2 = -1;
public final static int DATE1_AFTER_DATE2 = 1;
public final static int DATE1_EQUAL_DATE2 = 0;
//Default timezone
private final static TimeZone timeZone = TimeZone.getTimeZone("UTC");
/**
* Returns a Java calendar rounded to the current day
* @return the calendar
*/
public static Calendar getCurrentDate() {
Calendar calendar = Calendar.getInstance(timeZone);
calendar.setTimeZone(timeZone);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar;
}
/**
* Converts an ISO8601 string to a properly formatted android date (dd/mm/yyyy)
* @param iso8601String ISO8601 date string
* @return the formatted date string
*/
public static String getFormattedDateFromIso8601String(String iso8601String) { | // Path: app/src/main/java/com/vehiclerental/CarRentalApplication.java
// public class CarRentalApplication extends Application {
//
// //Static access to context and ssl parameters
// private static Application application;
// private static SSLContext sslContext;
//
// /**
// * Returns the current application object
// *
// * @return application object
// */
// public static Application getApplication() {
// return application;
// }
//
// /**
// * Returns the current application context
// *
// * @return application context
// */
// public static Context getAppContext() {
// return getApplication().getApplicationContext();
// }
//
// /**
// * Returns the current SSL parameters
// *
// * @return SSL context parameters
// */
// public static SSLContext getSslContext() {
// return sslContext;
// }
//
// @Override
// public void onCreate() {
// //At the beginning of the application, a reference to the app is stored and the SSL parameters are initialized
// super.onCreate();
// application = this;
//
// setupSslTrustStore();
// }
//
// /**
// * Sets up the SSL trust store, containing the encryption keys for encrypted socket communication
// *
// * The keystore was generated with this tool: http://www.keystore-explorer.org/downloads.php
// */
// private void setupSslTrustStore() {
// try {
// char[] password = "carrental".toCharArray();
//
// KeyStore keyStore = KeyStore.getInstance("BKS");
// keyStore.load(this.getResources().openRawResource(R.raw.carrental_keystore), password);
//
// TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// trustManagerFactory.init(keyStore);
//
// KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// keyManagerFactory.init(keyStore, password);
//
// // Create a SSLContext with the certificate
// sslContext = SSLContext.getInstance("TLS");
// sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
// } catch (NoSuchAlgorithmException | KeyStoreException | IOException | KeyManagementException | CertificateException | UnrecoverableKeyException e) {
// e.printStackTrace();
// Log.e("SSL", "Failed to create SSL context");
// }
// }
// }
// Path: app/src/main/java/com/vehiclerental/utils/DateUtils.java
import com.vehiclerental.R;
import com.vehiclerental.CarRentalApplication;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* CarRental
*
* This file provides date management abstraction methods
* I am using UTC as common timezone
* The dates are encoded using the ISO8601 format to be sent over the network
*/
package com.vehiclerental.utils;
public class DateUtils {
//Results of the comparison system
public final static int DATE1_BEFORE_DATE2 = -1;
public final static int DATE1_AFTER_DATE2 = 1;
public final static int DATE1_EQUAL_DATE2 = 0;
//Default timezone
private final static TimeZone timeZone = TimeZone.getTimeZone("UTC");
/**
* Returns a Java calendar rounded to the current day
* @return the calendar
*/
public static Calendar getCurrentDate() {
Calendar calendar = Calendar.getInstance(timeZone);
calendar.setTimeZone(timeZone);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar;
}
/**
* Converts an ISO8601 string to a properly formatted android date (dd/mm/yyyy)
* @param iso8601String ISO8601 date string
* @return the formatted date string
*/
public static String getFormattedDateFromIso8601String(String iso8601String) { | return android.text.format.DateFormat.format(CarRentalApplication.getAppContext().getString(R.string.display_date_format), getDateFromIso8601String(iso8601String)).toString(); |
AlexisChevalier/CarRental-Android-Application | app/src/main/java/com/vehiclerental/adapters/BookingSearchResultListAdapter.java | // Path: app/src/main/java/com/vehiclerental/CarRentalApplication.java
// public class CarRentalApplication extends Application {
//
// //Static access to context and ssl parameters
// private static Application application;
// private static SSLContext sslContext;
//
// /**
// * Returns the current application object
// *
// * @return application object
// */
// public static Application getApplication() {
// return application;
// }
//
// /**
// * Returns the current application context
// *
// * @return application context
// */
// public static Context getAppContext() {
// return getApplication().getApplicationContext();
// }
//
// /**
// * Returns the current SSL parameters
// *
// * @return SSL context parameters
// */
// public static SSLContext getSslContext() {
// return sslContext;
// }
//
// @Override
// public void onCreate() {
// //At the beginning of the application, a reference to the app is stored and the SSL parameters are initialized
// super.onCreate();
// application = this;
//
// setupSslTrustStore();
// }
//
// /**
// * Sets up the SSL trust store, containing the encryption keys for encrypted socket communication
// *
// * The keystore was generated with this tool: http://www.keystore-explorer.org/downloads.php
// */
// private void setupSslTrustStore() {
// try {
// char[] password = "carrental".toCharArray();
//
// KeyStore keyStore = KeyStore.getInstance("BKS");
// keyStore.load(this.getResources().openRawResource(R.raw.carrental_keystore), password);
//
// TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// trustManagerFactory.init(keyStore);
//
// KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// keyManagerFactory.init(keyStore, password);
//
// // Create a SSLContext with the certificate
// sslContext = SSLContext.getInstance("TLS");
// sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
// } catch (NoSuchAlgorithmException | KeyStoreException | IOException | KeyManagementException | CertificateException | UnrecoverableKeyException e) {
// e.printStackTrace();
// Log.e("SSL", "Failed to create SSL context");
// }
// }
// }
//
// Path: app/src/main/java/com/vehiclerental/contracts/BookingSearchResultContract.java
// public class BookingSearchResultContract {
// public boolean requireVehicleMove;
// public VehicleContract vehicle;
// public String pickupDate;
// public String returnDate;
// public long daysCount;
// public double price;
// }
| import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.vehiclerental.R;
import com.vehiclerental.CarRentalApplication;
import com.vehiclerental.contracts.BookingSearchResultContract;
import java.text.DecimalFormat;
import java.util.List; | @Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
v = layoutInflater.inflate(R.layout.booking_search_result_list_item, null);
}
BookingSearchResultContract bookingResult = getItem(position);
if (v != null) {
/* CREATE VIEW */
TextView carName = (TextView) v.findViewById(R.id.carName);
TextView carSeats = (TextView) v.findViewById(R.id.carSeats);
TextView carDoors = (TextView) v.findViewById(R.id.carDoors);
TextView carTransmission = (TextView) v.findViewById(R.id.carTransmission);
TextView bookingPrice = (TextView) v.findViewById(R.id.bookingPrice);
TextView carPricePerDay = (TextView) v.findViewById(R.id.carPricePerDay);
TextView moveCarDisclaimer = (TextView) v.findViewById(R.id.moveCarDisclaimer);
TextView carRegistrationNumber = (TextView) v.findViewById(R.id.carRegistrationNumber);
if (carName != null) {
carName.setText(bookingResult.vehicle.name);
}
if (carSeats != null) { | // Path: app/src/main/java/com/vehiclerental/CarRentalApplication.java
// public class CarRentalApplication extends Application {
//
// //Static access to context and ssl parameters
// private static Application application;
// private static SSLContext sslContext;
//
// /**
// * Returns the current application object
// *
// * @return application object
// */
// public static Application getApplication() {
// return application;
// }
//
// /**
// * Returns the current application context
// *
// * @return application context
// */
// public static Context getAppContext() {
// return getApplication().getApplicationContext();
// }
//
// /**
// * Returns the current SSL parameters
// *
// * @return SSL context parameters
// */
// public static SSLContext getSslContext() {
// return sslContext;
// }
//
// @Override
// public void onCreate() {
// //At the beginning of the application, a reference to the app is stored and the SSL parameters are initialized
// super.onCreate();
// application = this;
//
// setupSslTrustStore();
// }
//
// /**
// * Sets up the SSL trust store, containing the encryption keys for encrypted socket communication
// *
// * The keystore was generated with this tool: http://www.keystore-explorer.org/downloads.php
// */
// private void setupSslTrustStore() {
// try {
// char[] password = "carrental".toCharArray();
//
// KeyStore keyStore = KeyStore.getInstance("BKS");
// keyStore.load(this.getResources().openRawResource(R.raw.carrental_keystore), password);
//
// TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// trustManagerFactory.init(keyStore);
//
// KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// keyManagerFactory.init(keyStore, password);
//
// // Create a SSLContext with the certificate
// sslContext = SSLContext.getInstance("TLS");
// sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
// } catch (NoSuchAlgorithmException | KeyStoreException | IOException | KeyManagementException | CertificateException | UnrecoverableKeyException e) {
// e.printStackTrace();
// Log.e("SSL", "Failed to create SSL context");
// }
// }
// }
//
// Path: app/src/main/java/com/vehiclerental/contracts/BookingSearchResultContract.java
// public class BookingSearchResultContract {
// public boolean requireVehicleMove;
// public VehicleContract vehicle;
// public String pickupDate;
// public String returnDate;
// public long daysCount;
// public double price;
// }
// Path: app/src/main/java/com/vehiclerental/adapters/BookingSearchResultListAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.vehiclerental.R;
import com.vehiclerental.CarRentalApplication;
import com.vehiclerental.contracts.BookingSearchResultContract;
import java.text.DecimalFormat;
import java.util.List;
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
v = layoutInflater.inflate(R.layout.booking_search_result_list_item, null);
}
BookingSearchResultContract bookingResult = getItem(position);
if (v != null) {
/* CREATE VIEW */
TextView carName = (TextView) v.findViewById(R.id.carName);
TextView carSeats = (TextView) v.findViewById(R.id.carSeats);
TextView carDoors = (TextView) v.findViewById(R.id.carDoors);
TextView carTransmission = (TextView) v.findViewById(R.id.carTransmission);
TextView bookingPrice = (TextView) v.findViewById(R.id.bookingPrice);
TextView carPricePerDay = (TextView) v.findViewById(R.id.carPricePerDay);
TextView moveCarDisclaimer = (TextView) v.findViewById(R.id.moveCarDisclaimer);
TextView carRegistrationNumber = (TextView) v.findViewById(R.id.carRegistrationNumber);
if (carName != null) {
carName.setText(bookingResult.vehicle.name);
}
if (carSeats != null) { | carSeats.setText(String.format(CarRentalApplication.getAppContext().getString(R.string.seats_number_formatted), bookingResult.vehicle.seats)); |
eladnava/redalert-android | app/src/main/java/com/betomaluje/miband/bluetooth/WriteAction.java | // Path: app/src/main/java/com/betomaluje/miband/ActionCallback.java
// public interface ActionCallback {
// public void onSuccess(Object data);
//
// public void onFail(int errorCode, String msg);
// }
| import com.betomaluje.miband.ActionCallback;
import java.util.UUID; | package com.betomaluje.miband.bluetooth;
/**
* Created by Lewis on 10/01/15.
*/
public class WriteAction implements BLEAction {
private UUID service;
private final UUID characteristic;
private final byte[] payload;
| // Path: app/src/main/java/com/betomaluje/miband/ActionCallback.java
// public interface ActionCallback {
// public void onSuccess(Object data);
//
// public void onFail(int errorCode, String msg);
// }
// Path: app/src/main/java/com/betomaluje/miband/bluetooth/WriteAction.java
import com.betomaluje.miband.ActionCallback;
import java.util.UUID;
package com.betomaluje.miband.bluetooth;
/**
* Created by Lewis on 10/01/15.
*/
public class WriteAction implements BLEAction {
private UUID service;
private final UUID characteristic;
private final byte[] payload;
| private ActionCallback callback; |
eladnava/redalert-android | app/src/main/java/com/red/alert/ui/dialogs/custom/LocationDialogs.java | // Path: app/src/main/java/com/red/alert/logic/settings/AppPreferences.java
// public class AppPreferences {
// public static boolean getNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.enabledPref), true);
// }
//
// public static boolean getLocationAlertsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.locationAlertsPref), false);
// }
//
// public static boolean getSecondaryNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.secondaryEnabledPref), false);
// }
//
// public static boolean getMiBandIntegrationEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.miBandPref), false);
// }
//
// public static boolean getTutorialDisplayed(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.tutorialPref), false);
// }
//
// public static boolean getPopupEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.alertPopupPref), true);
// }
//
// public static void setTutorialDisplayed(Context context) {
// // Update stored value
// Singleton.getSharedPreferences(context).edit().putBoolean(context.getString(R.string.tutorialPref), true).commit();
// }
//
// public static void setCityLastAlertTime(String city, long timestamp, Context context) {
// // Update last alert timestamp for this city
// Singleton.getSharedPreferences(context).edit().putLong(city, timestamp).commit();
// }
//
// public static long getCityLastAlert(String city, Context context) {
// // Get last alert timestamp for this city
// return Singleton.getSharedPreferences(context).getLong(city, 0);
// }
//
// public static float getPrimaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.volumePref), 1.0f);
// }
//
// public static float getSecondaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.secondaryVolumePref), 1.0f);
// }
// }
//
// Path: app/src/main/java/com/red/alert/ui/localization/rtl/RTLSupport.java
// public class RTLSupport {
// @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
// public static void mirrorActionBar(Activity activity) {
// // Hebrew only
// if (!Localization.isHebrewLocale(activity)) {
// return;
// }
//
// // Must be Jellybean or newer
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// // Set RTL layout direction
// activity.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
// }
// }
//
// @SuppressLint("NewApi")
// public static void mirrorDialog(Dialog dialog, Context context) {
// // Hebrew only
// if (!Localization.isHebrewLocale(context)) {
// return;
// }
//
// try {
// // Get message text view
// TextView message = (TextView) dialog.findViewById(android.R.id.message);
//
// // Defy gravity
// if (message != null) {
// message.setGravity(Gravity.RIGHT);
// }
//
// // Get the title of text view
// TextView title = (TextView) dialog.findViewById(context.getResources().getIdentifier("alertTitle", "id", "android"));
//
// // Defy gravity
// title.setGravity(Gravity.RIGHT);
//
// // Get list view (may not exist)
// ListView listView = (ListView) dialog.findViewById(context.getResources().getIdentifier("select_dialog_listview", "id", "android"));
//
// // Check if list & set RTL mode
// if (listView != null) {
// listView.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
// }
//
// // Get title's parent layout
// LinearLayout parent = ((LinearLayout) title.getParent());
//
// // Get layout params
// LinearLayout.LayoutParams originalParams = (LinearLayout.LayoutParams) parent.getLayoutParams();
//
// // Set width to WRAP_CONTENT
// originalParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
//
// // Defy gravity
// originalParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
//
// // Set layout params
// parent.setLayoutParams(originalParams);
// }
// catch (Exception exc) {
// // Log failure to logcat
// Log.d(Logging.TAG, "RTL failed", exc);
// }
// }
// }
| import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.widget.Toast;
import com.red.alert.R;
import com.red.alert.logic.settings.AppPreferences;
import com.red.alert.ui.localization.rtl.RTLSupport;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat; | package com.red.alert.ui.dialogs.custom;
public class LocationDialogs {
private static AlertDialog mLocationServicesDialog;
public static void requestEnableLocationServices(final Activity context) {
// Location alerts disabled? | // Path: app/src/main/java/com/red/alert/logic/settings/AppPreferences.java
// public class AppPreferences {
// public static boolean getNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.enabledPref), true);
// }
//
// public static boolean getLocationAlertsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.locationAlertsPref), false);
// }
//
// public static boolean getSecondaryNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.secondaryEnabledPref), false);
// }
//
// public static boolean getMiBandIntegrationEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.miBandPref), false);
// }
//
// public static boolean getTutorialDisplayed(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.tutorialPref), false);
// }
//
// public static boolean getPopupEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.alertPopupPref), true);
// }
//
// public static void setTutorialDisplayed(Context context) {
// // Update stored value
// Singleton.getSharedPreferences(context).edit().putBoolean(context.getString(R.string.tutorialPref), true).commit();
// }
//
// public static void setCityLastAlertTime(String city, long timestamp, Context context) {
// // Update last alert timestamp for this city
// Singleton.getSharedPreferences(context).edit().putLong(city, timestamp).commit();
// }
//
// public static long getCityLastAlert(String city, Context context) {
// // Get last alert timestamp for this city
// return Singleton.getSharedPreferences(context).getLong(city, 0);
// }
//
// public static float getPrimaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.volumePref), 1.0f);
// }
//
// public static float getSecondaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.secondaryVolumePref), 1.0f);
// }
// }
//
// Path: app/src/main/java/com/red/alert/ui/localization/rtl/RTLSupport.java
// public class RTLSupport {
// @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
// public static void mirrorActionBar(Activity activity) {
// // Hebrew only
// if (!Localization.isHebrewLocale(activity)) {
// return;
// }
//
// // Must be Jellybean or newer
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// // Set RTL layout direction
// activity.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
// }
// }
//
// @SuppressLint("NewApi")
// public static void mirrorDialog(Dialog dialog, Context context) {
// // Hebrew only
// if (!Localization.isHebrewLocale(context)) {
// return;
// }
//
// try {
// // Get message text view
// TextView message = (TextView) dialog.findViewById(android.R.id.message);
//
// // Defy gravity
// if (message != null) {
// message.setGravity(Gravity.RIGHT);
// }
//
// // Get the title of text view
// TextView title = (TextView) dialog.findViewById(context.getResources().getIdentifier("alertTitle", "id", "android"));
//
// // Defy gravity
// title.setGravity(Gravity.RIGHT);
//
// // Get list view (may not exist)
// ListView listView = (ListView) dialog.findViewById(context.getResources().getIdentifier("select_dialog_listview", "id", "android"));
//
// // Check if list & set RTL mode
// if (listView != null) {
// listView.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
// }
//
// // Get title's parent layout
// LinearLayout parent = ((LinearLayout) title.getParent());
//
// // Get layout params
// LinearLayout.LayoutParams originalParams = (LinearLayout.LayoutParams) parent.getLayoutParams();
//
// // Set width to WRAP_CONTENT
// originalParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
//
// // Defy gravity
// originalParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
//
// // Set layout params
// parent.setLayoutParams(originalParams);
// }
// catch (Exception exc) {
// // Log failure to logcat
// Log.d(Logging.TAG, "RTL failed", exc);
// }
// }
// }
// Path: app/src/main/java/com/red/alert/ui/dialogs/custom/LocationDialogs.java
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.widget.Toast;
import com.red.alert.R;
import com.red.alert.logic.settings.AppPreferences;
import com.red.alert.ui.localization.rtl.RTLSupport;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
package com.red.alert.ui.dialogs.custom;
public class LocationDialogs {
private static AlertDialog mLocationServicesDialog;
public static void requestEnableLocationServices(final Activity context) {
// Location alerts disabled? | if (!AppPreferences.getLocationAlertsEnabled(context)) { |
eladnava/redalert-android | app/src/main/java/com/betomaluje/miband/bluetooth/ReadAction.java | // Path: app/src/main/java/com/betomaluje/miband/ActionCallback.java
// public interface ActionCallback {
// public void onSuccess(Object data);
//
// public void onFail(int errorCode, String msg);
// }
| import com.betomaluje.miband.ActionCallback;
import java.util.UUID; | package com.betomaluje.miband.bluetooth;
/**
* Created by betomaluje on 8/3/15.
*/
public class ReadAction implements BLEAction {
private final UUID characteristic;
| // Path: app/src/main/java/com/betomaluje/miband/ActionCallback.java
// public interface ActionCallback {
// public void onSuccess(Object data);
//
// public void onFail(int errorCode, String msg);
// }
// Path: app/src/main/java/com/betomaluje/miband/bluetooth/ReadAction.java
import com.betomaluje.miband.ActionCallback;
import java.util.UUID;
package com.betomaluje.miband.bluetooth;
/**
* Created by betomaluje on 8/3/15.
*/
public class ReadAction implements BLEAction {
private final UUID characteristic;
| private ActionCallback callback; |
eladnava/redalert-android | app/src/main/java/com/red/alert/ui/dialogs/custom/UpdateDialogs.java | // Path: app/src/main/java/com/red/alert/ui/localization/rtl/RTLSupport.java
// public class RTLSupport {
// @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
// public static void mirrorActionBar(Activity activity) {
// // Hebrew only
// if (!Localization.isHebrewLocale(activity)) {
// return;
// }
//
// // Must be Jellybean or newer
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// // Set RTL layout direction
// activity.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
// }
// }
//
// @SuppressLint("NewApi")
// public static void mirrorDialog(Dialog dialog, Context context) {
// // Hebrew only
// if (!Localization.isHebrewLocale(context)) {
// return;
// }
//
// try {
// // Get message text view
// TextView message = (TextView) dialog.findViewById(android.R.id.message);
//
// // Defy gravity
// if (message != null) {
// message.setGravity(Gravity.RIGHT);
// }
//
// // Get the title of text view
// TextView title = (TextView) dialog.findViewById(context.getResources().getIdentifier("alertTitle", "id", "android"));
//
// // Defy gravity
// title.setGravity(Gravity.RIGHT);
//
// // Get list view (may not exist)
// ListView listView = (ListView) dialog.findViewById(context.getResources().getIdentifier("select_dialog_listview", "id", "android"));
//
// // Check if list & set RTL mode
// if (listView != null) {
// listView.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
// }
//
// // Get title's parent layout
// LinearLayout parent = ((LinearLayout) title.getParent());
//
// // Get layout params
// LinearLayout.LayoutParams originalParams = (LinearLayout.LayoutParams) parent.getLayoutParams();
//
// // Set width to WRAP_CONTENT
// originalParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
//
// // Defy gravity
// originalParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
//
// // Set layout params
// parent.setLayoutParams(originalParams);
// }
// catch (Exception exc) {
// // Log failure to logcat
// Log.d(Logging.TAG, "RTL failed", exc);
// }
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/marketing/GooglePlay.java
// public class GooglePlay {
// public static void openAppListingPage(Context context) {
// // Initialize Google Play intent
// Intent rateAppIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.getApplicationContext().getPackageName()));
//
// // Is Google Play installed?
// if (context.getPackageManager().queryIntentActivities(rateAppIntent, 0).size() > 0) {
// try {
// // Try to open Google Play and navigate to app page
// context.startActivity(rateAppIntent);
// }
// catch (Exception exc) {
// // Log it
// Log.e(Logging.TAG, "Rate activity launch failed", exc);
// }
// }
// else {
// // Log it
// Log.e(Logging.TAG, "Can't rate. Google Play app not installed");
// }
// }
// }
| import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.Toast;
import com.red.alert.R;
import com.red.alert.ui.localization.rtl.RTLSupport;
import com.red.alert.utils.marketing.GooglePlay; | package com.red.alert.ui.dialogs.custom;
public class UpdateDialogs {
public static void showUpdateDialog(final Context context, String newVersion) {
// Use builder to create dialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Insert version into message
String message = String.format(context.getString(R.string.updateDesc), newVersion);
// Use builder to create dialog
builder.setTitle(context.getString(R.string.update)).setMessage(message);
// Set positive button
builder.setPositiveButton(R.string.updatePositive, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Open app page | // Path: app/src/main/java/com/red/alert/ui/localization/rtl/RTLSupport.java
// public class RTLSupport {
// @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
// public static void mirrorActionBar(Activity activity) {
// // Hebrew only
// if (!Localization.isHebrewLocale(activity)) {
// return;
// }
//
// // Must be Jellybean or newer
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// // Set RTL layout direction
// activity.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
// }
// }
//
// @SuppressLint("NewApi")
// public static void mirrorDialog(Dialog dialog, Context context) {
// // Hebrew only
// if (!Localization.isHebrewLocale(context)) {
// return;
// }
//
// try {
// // Get message text view
// TextView message = (TextView) dialog.findViewById(android.R.id.message);
//
// // Defy gravity
// if (message != null) {
// message.setGravity(Gravity.RIGHT);
// }
//
// // Get the title of text view
// TextView title = (TextView) dialog.findViewById(context.getResources().getIdentifier("alertTitle", "id", "android"));
//
// // Defy gravity
// title.setGravity(Gravity.RIGHT);
//
// // Get list view (may not exist)
// ListView listView = (ListView) dialog.findViewById(context.getResources().getIdentifier("select_dialog_listview", "id", "android"));
//
// // Check if list & set RTL mode
// if (listView != null) {
// listView.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
// }
//
// // Get title's parent layout
// LinearLayout parent = ((LinearLayout) title.getParent());
//
// // Get layout params
// LinearLayout.LayoutParams originalParams = (LinearLayout.LayoutParams) parent.getLayoutParams();
//
// // Set width to WRAP_CONTENT
// originalParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
//
// // Defy gravity
// originalParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
//
// // Set layout params
// parent.setLayoutParams(originalParams);
// }
// catch (Exception exc) {
// // Log failure to logcat
// Log.d(Logging.TAG, "RTL failed", exc);
// }
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/marketing/GooglePlay.java
// public class GooglePlay {
// public static void openAppListingPage(Context context) {
// // Initialize Google Play intent
// Intent rateAppIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.getApplicationContext().getPackageName()));
//
// // Is Google Play installed?
// if (context.getPackageManager().queryIntentActivities(rateAppIntent, 0).size() > 0) {
// try {
// // Try to open Google Play and navigate to app page
// context.startActivity(rateAppIntent);
// }
// catch (Exception exc) {
// // Log it
// Log.e(Logging.TAG, "Rate activity launch failed", exc);
// }
// }
// else {
// // Log it
// Log.e(Logging.TAG, "Can't rate. Google Play app not installed");
// }
// }
// }
// Path: app/src/main/java/com/red/alert/ui/dialogs/custom/UpdateDialogs.java
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.Toast;
import com.red.alert.R;
import com.red.alert.ui.localization.rtl.RTLSupport;
import com.red.alert.utils.marketing.GooglePlay;
package com.red.alert.ui.dialogs.custom;
public class UpdateDialogs {
public static void showUpdateDialog(final Context context, String newVersion) {
// Use builder to create dialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Insert version into message
String message = String.format(context.getString(R.string.updateDesc), newVersion);
// Use builder to create dialog
builder.setTitle(context.getString(R.string.update)).setMessage(message);
// Set positive button
builder.setPositiveButton(R.string.updatePositive, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Open app page | GooglePlay.openAppListingPage(context); |
eladnava/redalert-android | app/src/main/java/com/red/alert/ui/dialogs/custom/UpdateDialogs.java | // Path: app/src/main/java/com/red/alert/ui/localization/rtl/RTLSupport.java
// public class RTLSupport {
// @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
// public static void mirrorActionBar(Activity activity) {
// // Hebrew only
// if (!Localization.isHebrewLocale(activity)) {
// return;
// }
//
// // Must be Jellybean or newer
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// // Set RTL layout direction
// activity.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
// }
// }
//
// @SuppressLint("NewApi")
// public static void mirrorDialog(Dialog dialog, Context context) {
// // Hebrew only
// if (!Localization.isHebrewLocale(context)) {
// return;
// }
//
// try {
// // Get message text view
// TextView message = (TextView) dialog.findViewById(android.R.id.message);
//
// // Defy gravity
// if (message != null) {
// message.setGravity(Gravity.RIGHT);
// }
//
// // Get the title of text view
// TextView title = (TextView) dialog.findViewById(context.getResources().getIdentifier("alertTitle", "id", "android"));
//
// // Defy gravity
// title.setGravity(Gravity.RIGHT);
//
// // Get list view (may not exist)
// ListView listView = (ListView) dialog.findViewById(context.getResources().getIdentifier("select_dialog_listview", "id", "android"));
//
// // Check if list & set RTL mode
// if (listView != null) {
// listView.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
// }
//
// // Get title's parent layout
// LinearLayout parent = ((LinearLayout) title.getParent());
//
// // Get layout params
// LinearLayout.LayoutParams originalParams = (LinearLayout.LayoutParams) parent.getLayoutParams();
//
// // Set width to WRAP_CONTENT
// originalParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
//
// // Defy gravity
// originalParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
//
// // Set layout params
// parent.setLayoutParams(originalParams);
// }
// catch (Exception exc) {
// // Log failure to logcat
// Log.d(Logging.TAG, "RTL failed", exc);
// }
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/marketing/GooglePlay.java
// public class GooglePlay {
// public static void openAppListingPage(Context context) {
// // Initialize Google Play intent
// Intent rateAppIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.getApplicationContext().getPackageName()));
//
// // Is Google Play installed?
// if (context.getPackageManager().queryIntentActivities(rateAppIntent, 0).size() > 0) {
// try {
// // Try to open Google Play and navigate to app page
// context.startActivity(rateAppIntent);
// }
// catch (Exception exc) {
// // Log it
// Log.e(Logging.TAG, "Rate activity launch failed", exc);
// }
// }
// else {
// // Log it
// Log.e(Logging.TAG, "Can't rate. Google Play app not installed");
// }
// }
// }
| import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.Toast;
import com.red.alert.R;
import com.red.alert.ui.localization.rtl.RTLSupport;
import com.red.alert.utils.marketing.GooglePlay; | package com.red.alert.ui.dialogs.custom;
public class UpdateDialogs {
public static void showUpdateDialog(final Context context, String newVersion) {
// Use builder to create dialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Insert version into message
String message = String.format(context.getString(R.string.updateDesc), newVersion);
// Use builder to create dialog
builder.setTitle(context.getString(R.string.update)).setMessage(message);
// Set positive button
builder.setPositiveButton(R.string.updatePositive, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Open app page
GooglePlay.openAppListingPage(context);
}
});
// Set negative button
builder.setNegativeButton(R.string.notNow, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Close dialog
dialogInterface.dismiss();
}
});
try {
// Create the dialog
AlertDialog dialog = builder.create();
// Show dialog
dialog.show();
// Support for RTL languages | // Path: app/src/main/java/com/red/alert/ui/localization/rtl/RTLSupport.java
// public class RTLSupport {
// @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
// public static void mirrorActionBar(Activity activity) {
// // Hebrew only
// if (!Localization.isHebrewLocale(activity)) {
// return;
// }
//
// // Must be Jellybean or newer
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// // Set RTL layout direction
// activity.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
// }
// }
//
// @SuppressLint("NewApi")
// public static void mirrorDialog(Dialog dialog, Context context) {
// // Hebrew only
// if (!Localization.isHebrewLocale(context)) {
// return;
// }
//
// try {
// // Get message text view
// TextView message = (TextView) dialog.findViewById(android.R.id.message);
//
// // Defy gravity
// if (message != null) {
// message.setGravity(Gravity.RIGHT);
// }
//
// // Get the title of text view
// TextView title = (TextView) dialog.findViewById(context.getResources().getIdentifier("alertTitle", "id", "android"));
//
// // Defy gravity
// title.setGravity(Gravity.RIGHT);
//
// // Get list view (may not exist)
// ListView listView = (ListView) dialog.findViewById(context.getResources().getIdentifier("select_dialog_listview", "id", "android"));
//
// // Check if list & set RTL mode
// if (listView != null) {
// listView.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
// }
//
// // Get title's parent layout
// LinearLayout parent = ((LinearLayout) title.getParent());
//
// // Get layout params
// LinearLayout.LayoutParams originalParams = (LinearLayout.LayoutParams) parent.getLayoutParams();
//
// // Set width to WRAP_CONTENT
// originalParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
//
// // Defy gravity
// originalParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
//
// // Set layout params
// parent.setLayoutParams(originalParams);
// }
// catch (Exception exc) {
// // Log failure to logcat
// Log.d(Logging.TAG, "RTL failed", exc);
// }
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/marketing/GooglePlay.java
// public class GooglePlay {
// public static void openAppListingPage(Context context) {
// // Initialize Google Play intent
// Intent rateAppIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.getApplicationContext().getPackageName()));
//
// // Is Google Play installed?
// if (context.getPackageManager().queryIntentActivities(rateAppIntent, 0).size() > 0) {
// try {
// // Try to open Google Play and navigate to app page
// context.startActivity(rateAppIntent);
// }
// catch (Exception exc) {
// // Log it
// Log.e(Logging.TAG, "Rate activity launch failed", exc);
// }
// }
// else {
// // Log it
// Log.e(Logging.TAG, "Can't rate. Google Play app not installed");
// }
// }
// }
// Path: app/src/main/java/com/red/alert/ui/dialogs/custom/UpdateDialogs.java
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.Toast;
import com.red.alert.R;
import com.red.alert.ui.localization.rtl.RTLSupport;
import com.red.alert.utils.marketing.GooglePlay;
package com.red.alert.ui.dialogs.custom;
public class UpdateDialogs {
public static void showUpdateDialog(final Context context, String newVersion) {
// Use builder to create dialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Insert version into message
String message = String.format(context.getString(R.string.updateDesc), newVersion);
// Use builder to create dialog
builder.setTitle(context.getString(R.string.update)).setMessage(message);
// Set positive button
builder.setPositiveButton(R.string.updatePositive, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Open app page
GooglePlay.openAppListingPage(context);
}
});
// Set negative button
builder.setNegativeButton(R.string.notNow, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Close dialog
dialogInterface.dismiss();
}
});
try {
// Create the dialog
AlertDialog dialog = builder.create();
// Show dialog
dialog.show();
// Support for RTL languages | RTLSupport.mirrorDialog(dialog, context); |
eladnava/redalert-android | app/src/main/java/com/red/alert/receivers/BootReceiver.java | // Path: app/src/main/java/com/red/alert/logic/services/ServiceManager.java
// public class ServiceManager {
// public static void startAppServices(Context context) {
// // Start the Pushy push service
// startPushyService(context);
//
// // Start the location service
// startLocationService(context);
// }
//
// public static void startLocationService(Context context) {
// // Can we request location?
// if (!LocationLogic.shouldRequestLocationUpdates(context)) {
// return;
// }
//
// // Start the location service
// context.startService(new Intent(context, LocationService.class));
// }
//
// public static void startPushyService(Context context) {
// // Set custom heartbeat interval before calling Pushy.listen()
// Pushy.setHeartbeatInterval(PushyGateway.SOCKET_HEARTBEAT_INTERVAL, context);
//
// // Start external service
// Pushy.listen(context);
// }
// }
| import android.content.Context;
import android.content.Intent;
import androidx.legacy.content.WakefulBroadcastReceiver;
import com.red.alert.logic.services.ServiceManager; | package com.red.alert.receivers;
public class BootReceiver extends WakefulBroadcastReceiver {
public void onReceive(Context context, Intent intent) {
// Got boot completed event?
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
// Run all other services | // Path: app/src/main/java/com/red/alert/logic/services/ServiceManager.java
// public class ServiceManager {
// public static void startAppServices(Context context) {
// // Start the Pushy push service
// startPushyService(context);
//
// // Start the location service
// startLocationService(context);
// }
//
// public static void startLocationService(Context context) {
// // Can we request location?
// if (!LocationLogic.shouldRequestLocationUpdates(context)) {
// return;
// }
//
// // Start the location service
// context.startService(new Intent(context, LocationService.class));
// }
//
// public static void startPushyService(Context context) {
// // Set custom heartbeat interval before calling Pushy.listen()
// Pushy.setHeartbeatInterval(PushyGateway.SOCKET_HEARTBEAT_INTERVAL, context);
//
// // Start external service
// Pushy.listen(context);
// }
// }
// Path: app/src/main/java/com/red/alert/receivers/BootReceiver.java
import android.content.Context;
import android.content.Intent;
import androidx.legacy.content.WakefulBroadcastReceiver;
import com.red.alert.logic.services.ServiceManager;
package com.red.alert.receivers;
public class BootReceiver extends WakefulBroadcastReceiver {
public void onReceive(Context context, Intent intent) {
// Got boot completed event?
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
// Run all other services | ServiceManager.startAppServices(context); |
eladnava/redalert-android | app/src/main/java/com/red/alert/ui/localization/rtl/RTLSupport.java | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/utils/localization/Localization.java
// public class Localization {
// public static boolean isEnglishLocale(Context context) {
// // Override locale, if chosen
// overridePhoneLocale(context);
//
// // Get language code
// String languageCode = context.getResources().getConfiguration().locale.getLanguage();
//
// // English locale codes list
// List<String> englishLocales = new ArrayList<>();
//
// // Locale codes that are considered "English"
// englishLocales.add(context.getString(R.string.englishCode));
// englishLocales.add(context.getString(R.string.italianCode));
//
// // Traverse valid locale codes
// for (String code : englishLocales) {
// // Check for string equality
// if (languageCode.equals(code)) {
// return true;
// }
// }
//
// // Not an English locale
// return false;
// }
//
// public static boolean isHebrewLocale(Context context) {
// // Override locale, if chosen
// overridePhoneLocale(context);
//
// // Get language code
// String languageCode = context.getResources().getConfiguration().locale.getLanguage();
//
// // Detect using locale code
// return languageCode.equals(context.getString(R.string.hebrewCode)) || languageCode.equals(context.getString(R.string.hebrewCode2));
// }
//
// public static void overridePhoneLocale(Context context) {
// // Create new configuration
// Configuration configuration = context.getResources().getConfiguration();
//
// // Get new locale code
// String overrideLocale = Singleton.getSharedPreferences(context).getString(context.getString(R.string.langPref), "");
//
// // Chosen a new locale?
// if (!StringUtils.stringIsNullOrEmpty(overrideLocale)) {
// // Set it
// configuration.locale = new Locale(overrideLocale);
// }
// else {
// // Use default locale
// configuration.locale = Locale.getDefault();
// }
//
// // Apply the configuration
// context.getResources().updateConfiguration(configuration, context.getResources().getDisplayMetrics());
// }
// }
| import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.red.alert.config.Logging;
import com.red.alert.utils.localization.Localization; | package com.red.alert.ui.localization.rtl;
public class RTLSupport {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static void mirrorActionBar(Activity activity) {
// Hebrew only | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/utils/localization/Localization.java
// public class Localization {
// public static boolean isEnglishLocale(Context context) {
// // Override locale, if chosen
// overridePhoneLocale(context);
//
// // Get language code
// String languageCode = context.getResources().getConfiguration().locale.getLanguage();
//
// // English locale codes list
// List<String> englishLocales = new ArrayList<>();
//
// // Locale codes that are considered "English"
// englishLocales.add(context.getString(R.string.englishCode));
// englishLocales.add(context.getString(R.string.italianCode));
//
// // Traverse valid locale codes
// for (String code : englishLocales) {
// // Check for string equality
// if (languageCode.equals(code)) {
// return true;
// }
// }
//
// // Not an English locale
// return false;
// }
//
// public static boolean isHebrewLocale(Context context) {
// // Override locale, if chosen
// overridePhoneLocale(context);
//
// // Get language code
// String languageCode = context.getResources().getConfiguration().locale.getLanguage();
//
// // Detect using locale code
// return languageCode.equals(context.getString(R.string.hebrewCode)) || languageCode.equals(context.getString(R.string.hebrewCode2));
// }
//
// public static void overridePhoneLocale(Context context) {
// // Create new configuration
// Configuration configuration = context.getResources().getConfiguration();
//
// // Get new locale code
// String overrideLocale = Singleton.getSharedPreferences(context).getString(context.getString(R.string.langPref), "");
//
// // Chosen a new locale?
// if (!StringUtils.stringIsNullOrEmpty(overrideLocale)) {
// // Set it
// configuration.locale = new Locale(overrideLocale);
// }
// else {
// // Use default locale
// configuration.locale = Locale.getDefault();
// }
//
// // Apply the configuration
// context.getResources().updateConfiguration(configuration, context.getResources().getDisplayMetrics());
// }
// }
// Path: app/src/main/java/com/red/alert/ui/localization/rtl/RTLSupport.java
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.red.alert.config.Logging;
import com.red.alert.utils.localization.Localization;
package com.red.alert.ui.localization.rtl;
public class RTLSupport {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static void mirrorActionBar(Activity activity) {
// Hebrew only | if (!Localization.isHebrewLocale(activity)) { |
eladnava/redalert-android | app/src/main/java/com/red/alert/ui/localization/rtl/RTLSupport.java | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/utils/localization/Localization.java
// public class Localization {
// public static boolean isEnglishLocale(Context context) {
// // Override locale, if chosen
// overridePhoneLocale(context);
//
// // Get language code
// String languageCode = context.getResources().getConfiguration().locale.getLanguage();
//
// // English locale codes list
// List<String> englishLocales = new ArrayList<>();
//
// // Locale codes that are considered "English"
// englishLocales.add(context.getString(R.string.englishCode));
// englishLocales.add(context.getString(R.string.italianCode));
//
// // Traverse valid locale codes
// for (String code : englishLocales) {
// // Check for string equality
// if (languageCode.equals(code)) {
// return true;
// }
// }
//
// // Not an English locale
// return false;
// }
//
// public static boolean isHebrewLocale(Context context) {
// // Override locale, if chosen
// overridePhoneLocale(context);
//
// // Get language code
// String languageCode = context.getResources().getConfiguration().locale.getLanguage();
//
// // Detect using locale code
// return languageCode.equals(context.getString(R.string.hebrewCode)) || languageCode.equals(context.getString(R.string.hebrewCode2));
// }
//
// public static void overridePhoneLocale(Context context) {
// // Create new configuration
// Configuration configuration = context.getResources().getConfiguration();
//
// // Get new locale code
// String overrideLocale = Singleton.getSharedPreferences(context).getString(context.getString(R.string.langPref), "");
//
// // Chosen a new locale?
// if (!StringUtils.stringIsNullOrEmpty(overrideLocale)) {
// // Set it
// configuration.locale = new Locale(overrideLocale);
// }
// else {
// // Use default locale
// configuration.locale = Locale.getDefault();
// }
//
// // Apply the configuration
// context.getResources().updateConfiguration(configuration, context.getResources().getDisplayMetrics());
// }
// }
| import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.red.alert.config.Logging;
import com.red.alert.utils.localization.Localization; | TextView title = (TextView) dialog.findViewById(context.getResources().getIdentifier("alertTitle", "id", "android"));
// Defy gravity
title.setGravity(Gravity.RIGHT);
// Get list view (may not exist)
ListView listView = (ListView) dialog.findViewById(context.getResources().getIdentifier("select_dialog_listview", "id", "android"));
// Check if list & set RTL mode
if (listView != null) {
listView.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
// Get title's parent layout
LinearLayout parent = ((LinearLayout) title.getParent());
// Get layout params
LinearLayout.LayoutParams originalParams = (LinearLayout.LayoutParams) parent.getLayoutParams();
// Set width to WRAP_CONTENT
originalParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
// Defy gravity
originalParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
// Set layout params
parent.setLayoutParams(originalParams);
}
catch (Exception exc) {
// Log failure to logcat | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/utils/localization/Localization.java
// public class Localization {
// public static boolean isEnglishLocale(Context context) {
// // Override locale, if chosen
// overridePhoneLocale(context);
//
// // Get language code
// String languageCode = context.getResources().getConfiguration().locale.getLanguage();
//
// // English locale codes list
// List<String> englishLocales = new ArrayList<>();
//
// // Locale codes that are considered "English"
// englishLocales.add(context.getString(R.string.englishCode));
// englishLocales.add(context.getString(R.string.italianCode));
//
// // Traverse valid locale codes
// for (String code : englishLocales) {
// // Check for string equality
// if (languageCode.equals(code)) {
// return true;
// }
// }
//
// // Not an English locale
// return false;
// }
//
// public static boolean isHebrewLocale(Context context) {
// // Override locale, if chosen
// overridePhoneLocale(context);
//
// // Get language code
// String languageCode = context.getResources().getConfiguration().locale.getLanguage();
//
// // Detect using locale code
// return languageCode.equals(context.getString(R.string.hebrewCode)) || languageCode.equals(context.getString(R.string.hebrewCode2));
// }
//
// public static void overridePhoneLocale(Context context) {
// // Create new configuration
// Configuration configuration = context.getResources().getConfiguration();
//
// // Get new locale code
// String overrideLocale = Singleton.getSharedPreferences(context).getString(context.getString(R.string.langPref), "");
//
// // Chosen a new locale?
// if (!StringUtils.stringIsNullOrEmpty(overrideLocale)) {
// // Set it
// configuration.locale = new Locale(overrideLocale);
// }
// else {
// // Use default locale
// configuration.locale = Locale.getDefault();
// }
//
// // Apply the configuration
// context.getResources().updateConfiguration(configuration, context.getResources().getDisplayMetrics());
// }
// }
// Path: app/src/main/java/com/red/alert/ui/localization/rtl/RTLSupport.java
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.red.alert.config.Logging;
import com.red.alert.utils.localization.Localization;
TextView title = (TextView) dialog.findViewById(context.getResources().getIdentifier("alertTitle", "id", "android"));
// Defy gravity
title.setGravity(Gravity.RIGHT);
// Get list view (may not exist)
ListView listView = (ListView) dialog.findViewById(context.getResources().getIdentifier("select_dialog_listview", "id", "android"));
// Check if list & set RTL mode
if (listView != null) {
listView.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
// Get title's parent layout
LinearLayout parent = ((LinearLayout) title.getParent());
// Get layout params
LinearLayout.LayoutParams originalParams = (LinearLayout.LayoutParams) parent.getLayoutParams();
// Set width to WRAP_CONTENT
originalParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
// Defy gravity
originalParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
// Set layout params
parent.setLayoutParams(originalParams);
}
catch (Exception exc) {
// Log failure to logcat | Log.d(Logging.TAG, "RTL failed", exc); |
eladnava/redalert-android | app/src/main/java/com/red/alert/ui/dialogs/custom/BluetoothDialogs.java | // Path: app/src/main/java/com/red/alert/ui/localization/rtl/RTLSupport.java
// public class RTLSupport {
// @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
// public static void mirrorActionBar(Activity activity) {
// // Hebrew only
// if (!Localization.isHebrewLocale(activity)) {
// return;
// }
//
// // Must be Jellybean or newer
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// // Set RTL layout direction
// activity.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
// }
// }
//
// @SuppressLint("NewApi")
// public static void mirrorDialog(Dialog dialog, Context context) {
// // Hebrew only
// if (!Localization.isHebrewLocale(context)) {
// return;
// }
//
// try {
// // Get message text view
// TextView message = (TextView) dialog.findViewById(android.R.id.message);
//
// // Defy gravity
// if (message != null) {
// message.setGravity(Gravity.RIGHT);
// }
//
// // Get the title of text view
// TextView title = (TextView) dialog.findViewById(context.getResources().getIdentifier("alertTitle", "id", "android"));
//
// // Defy gravity
// title.setGravity(Gravity.RIGHT);
//
// // Get list view (may not exist)
// ListView listView = (ListView) dialog.findViewById(context.getResources().getIdentifier("select_dialog_listview", "id", "android"));
//
// // Check if list & set RTL mode
// if (listView != null) {
// listView.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
// }
//
// // Get title's parent layout
// LinearLayout parent = ((LinearLayout) title.getParent());
//
// // Get layout params
// LinearLayout.LayoutParams originalParams = (LinearLayout.LayoutParams) parent.getLayoutParams();
//
// // Set width to WRAP_CONTENT
// originalParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
//
// // Defy gravity
// originalParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
//
// // Set layout params
// parent.setLayoutParams(originalParams);
// }
// catch (Exception exc) {
// // Log failure to logcat
// Log.d(Logging.TAG, "RTL failed", exc);
// }
// }
// }
| import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.widget.Toast;
import com.red.alert.R;
import com.red.alert.ui.localization.rtl.RTLSupport; | package com.red.alert.ui.dialogs.custom;
public class BluetoothDialogs {
private static AlertDialog mEnableBluetoothDialog;
public static void showEnableBluetoothDialog(final Context context) {
// Already have a historical dialog?
if (mEnableBluetoothDialog != null) {
try {
// Try to dismiss it
mEnableBluetoothDialog.hide();
}
catch (Exception exc) {
// The dialog is probably no longer valid
mEnableBluetoothDialog = null;
}
}
// Use builder to create dialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Use builder to create dialog
builder.setTitle(context.getString(R.string.enableBluetooth)).setMessage(context.getString(R.string.enableBluetoothDesc));
// Set positive button
builder.setPositiveButton(R.string.enable, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Ask user to enable it via built-in Android dialog
context.startActivity(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE));
}
});
// Set negative button
builder.setNegativeButton(R.string.notNow, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
// Hide dialog
dialog.dismiss();
}
});
try {
// Create the dialog
mEnableBluetoothDialog = builder.create();
// Show dialog
mEnableBluetoothDialog.show();
// Support for RTL languages | // Path: app/src/main/java/com/red/alert/ui/localization/rtl/RTLSupport.java
// public class RTLSupport {
// @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
// public static void mirrorActionBar(Activity activity) {
// // Hebrew only
// if (!Localization.isHebrewLocale(activity)) {
// return;
// }
//
// // Must be Jellybean or newer
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// // Set RTL layout direction
// activity.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
// }
// }
//
// @SuppressLint("NewApi")
// public static void mirrorDialog(Dialog dialog, Context context) {
// // Hebrew only
// if (!Localization.isHebrewLocale(context)) {
// return;
// }
//
// try {
// // Get message text view
// TextView message = (TextView) dialog.findViewById(android.R.id.message);
//
// // Defy gravity
// if (message != null) {
// message.setGravity(Gravity.RIGHT);
// }
//
// // Get the title of text view
// TextView title = (TextView) dialog.findViewById(context.getResources().getIdentifier("alertTitle", "id", "android"));
//
// // Defy gravity
// title.setGravity(Gravity.RIGHT);
//
// // Get list view (may not exist)
// ListView listView = (ListView) dialog.findViewById(context.getResources().getIdentifier("select_dialog_listview", "id", "android"));
//
// // Check if list & set RTL mode
// if (listView != null) {
// listView.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
// }
//
// // Get title's parent layout
// LinearLayout parent = ((LinearLayout) title.getParent());
//
// // Get layout params
// LinearLayout.LayoutParams originalParams = (LinearLayout.LayoutParams) parent.getLayoutParams();
//
// // Set width to WRAP_CONTENT
// originalParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
//
// // Defy gravity
// originalParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
//
// // Set layout params
// parent.setLayoutParams(originalParams);
// }
// catch (Exception exc) {
// // Log failure to logcat
// Log.d(Logging.TAG, "RTL failed", exc);
// }
// }
// }
// Path: app/src/main/java/com/red/alert/ui/dialogs/custom/BluetoothDialogs.java
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.widget.Toast;
import com.red.alert.R;
import com.red.alert.ui.localization.rtl.RTLSupport;
package com.red.alert.ui.dialogs.custom;
public class BluetoothDialogs {
private static AlertDialog mEnableBluetoothDialog;
public static void showEnableBluetoothDialog(final Context context) {
// Already have a historical dialog?
if (mEnableBluetoothDialog != null) {
try {
// Try to dismiss it
mEnableBluetoothDialog.hide();
}
catch (Exception exc) {
// The dialog is probably no longer valid
mEnableBluetoothDialog = null;
}
}
// Use builder to create dialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Use builder to create dialog
builder.setTitle(context.getString(R.string.enableBluetooth)).setMessage(context.getString(R.string.enableBluetoothDesc));
// Set positive button
builder.setPositiveButton(R.string.enable, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Ask user to enable it via built-in Android dialog
context.startActivity(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE));
}
});
// Set negative button
builder.setNegativeButton(R.string.notNow, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
// Hide dialog
dialog.dismiss();
}
});
try {
// Create the dialog
mEnableBluetoothDialog = builder.create();
// Show dialog
mEnableBluetoothDialog.show();
// Support for RTL languages | RTLSupport.mirrorDialog(mEnableBluetoothDialog, context); |
eladnava/redalert-android | app/src/main/java/com/red/alert/utils/marketing/GooglePlay.java | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
| import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import com.red.alert.config.Logging; | package com.red.alert.utils.marketing;
public class GooglePlay {
public static void openAppListingPage(Context context) {
// Initialize Google Play intent
Intent rateAppIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.getApplicationContext().getPackageName()));
// Is Google Play installed?
if (context.getPackageManager().queryIntentActivities(rateAppIntent, 0).size() > 0) {
try {
// Try to open Google Play and navigate to app page
context.startActivity(rateAppIntent);
}
catch (Exception exc) {
// Log it | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
// Path: app/src/main/java/com/red/alert/utils/marketing/GooglePlay.java
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import com.red.alert.config.Logging;
package com.red.alert.utils.marketing;
public class GooglePlay {
public static void openAppListingPage(Context context) {
// Initialize Google Play intent
Intent rateAppIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.getApplicationContext().getPackageName()));
// Is Google Play installed?
if (context.getPackageManager().queryIntentActivities(rateAppIntent, 0).size() > 0) {
try {
// Try to open Google Play and navigate to app page
context.startActivity(rateAppIntent);
}
catch (Exception exc) {
// Log it | Log.e(Logging.TAG, "Rate activity launch failed", exc); |
eladnava/redalert-android | app/src/main/java/com/red/alert/utils/feedback/Volume.java | // Path: app/src/main/java/com/red/alert/config/Sound.java
// public class Sound {
// public static final String SCHEME_URI_IDENTIFIER = "://";
// public static final String APP_SOUND_PREFIX = "com.red.alert://";
// // The AudioManager stream that sirens will be played on
// public static int STREAM_TYPE = AudioManager.STREAM_ALARM;
// }
| import android.app.Activity;
import com.red.alert.config.Sound; | package com.red.alert.utils.feedback;
public class Volume {
public static void setVolumeKeysAction(Activity context) {
// Set the appropriate alert stream | // Path: app/src/main/java/com/red/alert/config/Sound.java
// public class Sound {
// public static final String SCHEME_URI_IDENTIFIER = "://";
// public static final String APP_SOUND_PREFIX = "com.red.alert://";
// // The AudioManager stream that sirens will be played on
// public static int STREAM_TYPE = AudioManager.STREAM_ALARM;
// }
// Path: app/src/main/java/com/red/alert/utils/feedback/Volume.java
import android.app.Activity;
import com.red.alert.config.Sound;
package com.red.alert.utils.feedback;
public class Volume {
public static void setVolumeKeysAction(Activity context) {
// Set the appropriate alert stream | context.setVolumeControlStream(Sound.STREAM_TYPE); |
eladnava/redalert-android | app/src/main/java/com/red/alert/utils/integration/WhatsApp.java | // Path: app/src/main/java/com/red/alert/config/Integrations.java
// public class Integrations {
// // WhatsApp package for I'm Safe integration - automatic share via WhatsApp
// public static String WHATSAPP_PACKAGE = "com.whatsapp";
// }
| import android.content.Context;
import android.content.pm.PackageManager;
import com.red.alert.config.Integrations; | package com.red.alert.utils.integration;
public class WhatsApp {
public static boolean isAppInstalled(Context context) {
// Get package manager
PackageManager packageManager = context.getPackageManager();
try {
// Locate package by name | // Path: app/src/main/java/com/red/alert/config/Integrations.java
// public class Integrations {
// // WhatsApp package for I'm Safe integration - automatic share via WhatsApp
// public static String WHATSAPP_PACKAGE = "com.whatsapp";
// }
// Path: app/src/main/java/com/red/alert/utils/integration/WhatsApp.java
import android.content.Context;
import android.content.pm.PackageManager;
import com.red.alert.config.Integrations;
package com.red.alert.utils.integration;
public class WhatsApp {
public static boolean isAppInstalled(Context context) {
// Get package manager
PackageManager packageManager = context.getPackageManager();
try {
// Locate package by name | packageManager.getPackageInfo(Integrations.WHATSAPP_PACKAGE, PackageManager.GET_ACTIVITIES); |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/integration/BluetoothIntegration.java | // Path: app/src/main/java/com/red/alert/logic/alerts/AlertTypes.java
// public class AlertTypes {
// public static final String SYSTEM = "system";
// public static final String PRIMARY = "alert";
// public static final String SECONDARY = "secondary_alert";
//
// public static final String TEST = "test";
// public static final String TEST_SOUND = "test_sound";
// public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
// }
//
// Path: app/src/main/java/com/red/alert/logic/integration/devices/MiBandIntegration.java
// public class MiBandIntegration {
// public static void notifyMiBand(final Context context) {
// // Xiaomi Mi Band integration enabled?
// if (!AppPreferences.getMiBandIntegrationEnabled(context)) {
// // Stop execution
// return;
// }
//
// // Get an instance of the Mi Band SDK
// MiBand miBand = MiBand.getInstance(context);
//
// // Attempt to connect to it
// miBand.connect(new ActionCallback() {
// @Override
// public void onSuccess(Object data) {
// // Log it
// Log.d(Logging.TAG, "Connected to Mi Band");
//
// // Vibration + LED colors
// sendNotificationCommands(context);
// }
//
// @Override
// public void onFail(int errorCode, String msg) {
// // Log fail
// Log.d(Logging.TAG, "Failed to connect to Mi Band: " + msg);
// }
// });
// }
//
// public static void sendNotificationCommands(Context context) {
// // Get an instance of the Mi Band SDK
// MiBand miBand = MiBand.getInstance(context);
//
// // Not connected for some reason?
// if (!miBand.isConnected()) {
// // Log it
// Log.e(Logging.TAG, "Mi Band is no longer connected!");
// }
//
// // Set red LED color (determined via MiBandExample color picker)
// int ledColor = -64746;
//
// // Repeat the vibration + color
// int repeatTimes = 3;
//
// // Sleep in between each notification
// int sleepInterval = 2000;
//
// // Send the notification commands repeatedly
// miBand.notifyBandRepeated(ledColor, repeatTimes, sleepInterval);
// }
// }
//
// Path: app/src/main/java/com/red/alert/logic/settings/AppPreferences.java
// public class AppPreferences {
// public static boolean getNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.enabledPref), true);
// }
//
// public static boolean getLocationAlertsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.locationAlertsPref), false);
// }
//
// public static boolean getSecondaryNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.secondaryEnabledPref), false);
// }
//
// public static boolean getMiBandIntegrationEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.miBandPref), false);
// }
//
// public static boolean getTutorialDisplayed(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.tutorialPref), false);
// }
//
// public static boolean getPopupEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.alertPopupPref), true);
// }
//
// public static void setTutorialDisplayed(Context context) {
// // Update stored value
// Singleton.getSharedPreferences(context).edit().putBoolean(context.getString(R.string.tutorialPref), true).commit();
// }
//
// public static void setCityLastAlertTime(String city, long timestamp, Context context) {
// // Update last alert timestamp for this city
// Singleton.getSharedPreferences(context).edit().putLong(city, timestamp).commit();
// }
//
// public static long getCityLastAlert(String city, Context context) {
// // Get last alert timestamp for this city
// return Singleton.getSharedPreferences(context).getLong(city, 0);
// }
//
// public static float getPrimaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.volumePref), 1.0f);
// }
//
// public static float getSecondaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.secondaryVolumePref), 1.0f);
// }
// }
| import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Looper;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.logic.integration.devices.MiBandIntegration;
import com.red.alert.logic.settings.AppPreferences; | package com.red.alert.logic.integration;
public class BluetoothIntegration {
public static void notifyDevices(String alertType, Context context) {
// Type must be an "alert" or "test" | // Path: app/src/main/java/com/red/alert/logic/alerts/AlertTypes.java
// public class AlertTypes {
// public static final String SYSTEM = "system";
// public static final String PRIMARY = "alert";
// public static final String SECONDARY = "secondary_alert";
//
// public static final String TEST = "test";
// public static final String TEST_SOUND = "test_sound";
// public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
// }
//
// Path: app/src/main/java/com/red/alert/logic/integration/devices/MiBandIntegration.java
// public class MiBandIntegration {
// public static void notifyMiBand(final Context context) {
// // Xiaomi Mi Band integration enabled?
// if (!AppPreferences.getMiBandIntegrationEnabled(context)) {
// // Stop execution
// return;
// }
//
// // Get an instance of the Mi Band SDK
// MiBand miBand = MiBand.getInstance(context);
//
// // Attempt to connect to it
// miBand.connect(new ActionCallback() {
// @Override
// public void onSuccess(Object data) {
// // Log it
// Log.d(Logging.TAG, "Connected to Mi Band");
//
// // Vibration + LED colors
// sendNotificationCommands(context);
// }
//
// @Override
// public void onFail(int errorCode, String msg) {
// // Log fail
// Log.d(Logging.TAG, "Failed to connect to Mi Band: " + msg);
// }
// });
// }
//
// public static void sendNotificationCommands(Context context) {
// // Get an instance of the Mi Band SDK
// MiBand miBand = MiBand.getInstance(context);
//
// // Not connected for some reason?
// if (!miBand.isConnected()) {
// // Log it
// Log.e(Logging.TAG, "Mi Band is no longer connected!");
// }
//
// // Set red LED color (determined via MiBandExample color picker)
// int ledColor = -64746;
//
// // Repeat the vibration + color
// int repeatTimes = 3;
//
// // Sleep in between each notification
// int sleepInterval = 2000;
//
// // Send the notification commands repeatedly
// miBand.notifyBandRepeated(ledColor, repeatTimes, sleepInterval);
// }
// }
//
// Path: app/src/main/java/com/red/alert/logic/settings/AppPreferences.java
// public class AppPreferences {
// public static boolean getNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.enabledPref), true);
// }
//
// public static boolean getLocationAlertsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.locationAlertsPref), false);
// }
//
// public static boolean getSecondaryNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.secondaryEnabledPref), false);
// }
//
// public static boolean getMiBandIntegrationEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.miBandPref), false);
// }
//
// public static boolean getTutorialDisplayed(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.tutorialPref), false);
// }
//
// public static boolean getPopupEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.alertPopupPref), true);
// }
//
// public static void setTutorialDisplayed(Context context) {
// // Update stored value
// Singleton.getSharedPreferences(context).edit().putBoolean(context.getString(R.string.tutorialPref), true).commit();
// }
//
// public static void setCityLastAlertTime(String city, long timestamp, Context context) {
// // Update last alert timestamp for this city
// Singleton.getSharedPreferences(context).edit().putLong(city, timestamp).commit();
// }
//
// public static long getCityLastAlert(String city, Context context) {
// // Get last alert timestamp for this city
// return Singleton.getSharedPreferences(context).getLong(city, 0);
// }
//
// public static float getPrimaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.volumePref), 1.0f);
// }
//
// public static float getSecondaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.secondaryVolumePref), 1.0f);
// }
// }
// Path: app/src/main/java/com/red/alert/logic/integration/BluetoothIntegration.java
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Looper;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.logic.integration.devices.MiBandIntegration;
import com.red.alert.logic.settings.AppPreferences;
package com.red.alert.logic.integration;
public class BluetoothIntegration {
public static void notifyDevices(String alertType, Context context) {
// Type must be an "alert" or "test" | if (alertType.equals(AlertTypes.PRIMARY) || alertType.equals(AlertTypes.TEST)) { |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/integration/BluetoothIntegration.java | // Path: app/src/main/java/com/red/alert/logic/alerts/AlertTypes.java
// public class AlertTypes {
// public static final String SYSTEM = "system";
// public static final String PRIMARY = "alert";
// public static final String SECONDARY = "secondary_alert";
//
// public static final String TEST = "test";
// public static final String TEST_SOUND = "test_sound";
// public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
// }
//
// Path: app/src/main/java/com/red/alert/logic/integration/devices/MiBandIntegration.java
// public class MiBandIntegration {
// public static void notifyMiBand(final Context context) {
// // Xiaomi Mi Band integration enabled?
// if (!AppPreferences.getMiBandIntegrationEnabled(context)) {
// // Stop execution
// return;
// }
//
// // Get an instance of the Mi Band SDK
// MiBand miBand = MiBand.getInstance(context);
//
// // Attempt to connect to it
// miBand.connect(new ActionCallback() {
// @Override
// public void onSuccess(Object data) {
// // Log it
// Log.d(Logging.TAG, "Connected to Mi Band");
//
// // Vibration + LED colors
// sendNotificationCommands(context);
// }
//
// @Override
// public void onFail(int errorCode, String msg) {
// // Log fail
// Log.d(Logging.TAG, "Failed to connect to Mi Band: " + msg);
// }
// });
// }
//
// public static void sendNotificationCommands(Context context) {
// // Get an instance of the Mi Band SDK
// MiBand miBand = MiBand.getInstance(context);
//
// // Not connected for some reason?
// if (!miBand.isConnected()) {
// // Log it
// Log.e(Logging.TAG, "Mi Band is no longer connected!");
// }
//
// // Set red LED color (determined via MiBandExample color picker)
// int ledColor = -64746;
//
// // Repeat the vibration + color
// int repeatTimes = 3;
//
// // Sleep in between each notification
// int sleepInterval = 2000;
//
// // Send the notification commands repeatedly
// miBand.notifyBandRepeated(ledColor, repeatTimes, sleepInterval);
// }
// }
//
// Path: app/src/main/java/com/red/alert/logic/settings/AppPreferences.java
// public class AppPreferences {
// public static boolean getNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.enabledPref), true);
// }
//
// public static boolean getLocationAlertsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.locationAlertsPref), false);
// }
//
// public static boolean getSecondaryNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.secondaryEnabledPref), false);
// }
//
// public static boolean getMiBandIntegrationEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.miBandPref), false);
// }
//
// public static boolean getTutorialDisplayed(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.tutorialPref), false);
// }
//
// public static boolean getPopupEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.alertPopupPref), true);
// }
//
// public static void setTutorialDisplayed(Context context) {
// // Update stored value
// Singleton.getSharedPreferences(context).edit().putBoolean(context.getString(R.string.tutorialPref), true).commit();
// }
//
// public static void setCityLastAlertTime(String city, long timestamp, Context context) {
// // Update last alert timestamp for this city
// Singleton.getSharedPreferences(context).edit().putLong(city, timestamp).commit();
// }
//
// public static long getCityLastAlert(String city, Context context) {
// // Get last alert timestamp for this city
// return Singleton.getSharedPreferences(context).getLong(city, 0);
// }
//
// public static float getPrimaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.volumePref), 1.0f);
// }
//
// public static float getSecondaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.secondaryVolumePref), 1.0f);
// }
// }
| import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Looper;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.logic.integration.devices.MiBandIntegration;
import com.red.alert.logic.settings.AppPreferences; | package com.red.alert.logic.integration;
public class BluetoothIntegration {
public static void notifyDevices(String alertType, Context context) {
// Type must be an "alert" or "test"
if (alertType.equals(AlertTypes.PRIMARY) || alertType.equals(AlertTypes.TEST)) {
// Check for BLE support + enabled Bluetooth controller
if (!isBLESupported(context) || !isBluetoothEnabled()) {
// Stop execution
return;
}
// Vibrate + LED for Mi Band (if enabled) | // Path: app/src/main/java/com/red/alert/logic/alerts/AlertTypes.java
// public class AlertTypes {
// public static final String SYSTEM = "system";
// public static final String PRIMARY = "alert";
// public static final String SECONDARY = "secondary_alert";
//
// public static final String TEST = "test";
// public static final String TEST_SOUND = "test_sound";
// public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
// }
//
// Path: app/src/main/java/com/red/alert/logic/integration/devices/MiBandIntegration.java
// public class MiBandIntegration {
// public static void notifyMiBand(final Context context) {
// // Xiaomi Mi Band integration enabled?
// if (!AppPreferences.getMiBandIntegrationEnabled(context)) {
// // Stop execution
// return;
// }
//
// // Get an instance of the Mi Band SDK
// MiBand miBand = MiBand.getInstance(context);
//
// // Attempt to connect to it
// miBand.connect(new ActionCallback() {
// @Override
// public void onSuccess(Object data) {
// // Log it
// Log.d(Logging.TAG, "Connected to Mi Band");
//
// // Vibration + LED colors
// sendNotificationCommands(context);
// }
//
// @Override
// public void onFail(int errorCode, String msg) {
// // Log fail
// Log.d(Logging.TAG, "Failed to connect to Mi Band: " + msg);
// }
// });
// }
//
// public static void sendNotificationCommands(Context context) {
// // Get an instance of the Mi Band SDK
// MiBand miBand = MiBand.getInstance(context);
//
// // Not connected for some reason?
// if (!miBand.isConnected()) {
// // Log it
// Log.e(Logging.TAG, "Mi Band is no longer connected!");
// }
//
// // Set red LED color (determined via MiBandExample color picker)
// int ledColor = -64746;
//
// // Repeat the vibration + color
// int repeatTimes = 3;
//
// // Sleep in between each notification
// int sleepInterval = 2000;
//
// // Send the notification commands repeatedly
// miBand.notifyBandRepeated(ledColor, repeatTimes, sleepInterval);
// }
// }
//
// Path: app/src/main/java/com/red/alert/logic/settings/AppPreferences.java
// public class AppPreferences {
// public static boolean getNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.enabledPref), true);
// }
//
// public static boolean getLocationAlertsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.locationAlertsPref), false);
// }
//
// public static boolean getSecondaryNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.secondaryEnabledPref), false);
// }
//
// public static boolean getMiBandIntegrationEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.miBandPref), false);
// }
//
// public static boolean getTutorialDisplayed(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.tutorialPref), false);
// }
//
// public static boolean getPopupEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.alertPopupPref), true);
// }
//
// public static void setTutorialDisplayed(Context context) {
// // Update stored value
// Singleton.getSharedPreferences(context).edit().putBoolean(context.getString(R.string.tutorialPref), true).commit();
// }
//
// public static void setCityLastAlertTime(String city, long timestamp, Context context) {
// // Update last alert timestamp for this city
// Singleton.getSharedPreferences(context).edit().putLong(city, timestamp).commit();
// }
//
// public static long getCityLastAlert(String city, Context context) {
// // Get last alert timestamp for this city
// return Singleton.getSharedPreferences(context).getLong(city, 0);
// }
//
// public static float getPrimaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.volumePref), 1.0f);
// }
//
// public static float getSecondaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.secondaryVolumePref), 1.0f);
// }
// }
// Path: app/src/main/java/com/red/alert/logic/integration/BluetoothIntegration.java
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Looper;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.logic.integration.devices.MiBandIntegration;
import com.red.alert.logic.settings.AppPreferences;
package com.red.alert.logic.integration;
public class BluetoothIntegration {
public static void notifyDevices(String alertType, Context context) {
// Type must be an "alert" or "test"
if (alertType.equals(AlertTypes.PRIMARY) || alertType.equals(AlertTypes.TEST)) {
// Check for BLE support + enabled Bluetooth controller
if (!isBLESupported(context) || !isBluetoothEnabled()) {
// Stop execution
return;
}
// Vibrate + LED for Mi Band (if enabled) | MiBandIntegration.notifyMiBand(context); |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/integration/BluetoothIntegration.java | // Path: app/src/main/java/com/red/alert/logic/alerts/AlertTypes.java
// public class AlertTypes {
// public static final String SYSTEM = "system";
// public static final String PRIMARY = "alert";
// public static final String SECONDARY = "secondary_alert";
//
// public static final String TEST = "test";
// public static final String TEST_SOUND = "test_sound";
// public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
// }
//
// Path: app/src/main/java/com/red/alert/logic/integration/devices/MiBandIntegration.java
// public class MiBandIntegration {
// public static void notifyMiBand(final Context context) {
// // Xiaomi Mi Band integration enabled?
// if (!AppPreferences.getMiBandIntegrationEnabled(context)) {
// // Stop execution
// return;
// }
//
// // Get an instance of the Mi Band SDK
// MiBand miBand = MiBand.getInstance(context);
//
// // Attempt to connect to it
// miBand.connect(new ActionCallback() {
// @Override
// public void onSuccess(Object data) {
// // Log it
// Log.d(Logging.TAG, "Connected to Mi Band");
//
// // Vibration + LED colors
// sendNotificationCommands(context);
// }
//
// @Override
// public void onFail(int errorCode, String msg) {
// // Log fail
// Log.d(Logging.TAG, "Failed to connect to Mi Band: " + msg);
// }
// });
// }
//
// public static void sendNotificationCommands(Context context) {
// // Get an instance of the Mi Band SDK
// MiBand miBand = MiBand.getInstance(context);
//
// // Not connected for some reason?
// if (!miBand.isConnected()) {
// // Log it
// Log.e(Logging.TAG, "Mi Band is no longer connected!");
// }
//
// // Set red LED color (determined via MiBandExample color picker)
// int ledColor = -64746;
//
// // Repeat the vibration + color
// int repeatTimes = 3;
//
// // Sleep in between each notification
// int sleepInterval = 2000;
//
// // Send the notification commands repeatedly
// miBand.notifyBandRepeated(ledColor, repeatTimes, sleepInterval);
// }
// }
//
// Path: app/src/main/java/com/red/alert/logic/settings/AppPreferences.java
// public class AppPreferences {
// public static boolean getNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.enabledPref), true);
// }
//
// public static boolean getLocationAlertsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.locationAlertsPref), false);
// }
//
// public static boolean getSecondaryNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.secondaryEnabledPref), false);
// }
//
// public static boolean getMiBandIntegrationEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.miBandPref), false);
// }
//
// public static boolean getTutorialDisplayed(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.tutorialPref), false);
// }
//
// public static boolean getPopupEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.alertPopupPref), true);
// }
//
// public static void setTutorialDisplayed(Context context) {
// // Update stored value
// Singleton.getSharedPreferences(context).edit().putBoolean(context.getString(R.string.tutorialPref), true).commit();
// }
//
// public static void setCityLastAlertTime(String city, long timestamp, Context context) {
// // Update last alert timestamp for this city
// Singleton.getSharedPreferences(context).edit().putLong(city, timestamp).commit();
// }
//
// public static long getCityLastAlert(String city, Context context) {
// // Get last alert timestamp for this city
// return Singleton.getSharedPreferences(context).getLong(city, 0);
// }
//
// public static float getPrimaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.volumePref), 1.0f);
// }
//
// public static float getSecondaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.secondaryVolumePref), 1.0f);
// }
// }
| import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Looper;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.logic.integration.devices.MiBandIntegration;
import com.red.alert.logic.settings.AppPreferences; | package com.red.alert.logic.integration;
public class BluetoothIntegration {
public static void notifyDevices(String alertType, Context context) {
// Type must be an "alert" or "test"
if (alertType.equals(AlertTypes.PRIMARY) || alertType.equals(AlertTypes.TEST)) {
// Check for BLE support + enabled Bluetooth controller
if (!isBLESupported(context) || !isBluetoothEnabled()) {
// Stop execution
return;
}
// Vibrate + LED for Mi Band (if enabled)
MiBandIntegration.notifyMiBand(context);
}
}
public static boolean isIntegrationEnabled(Context context) {
// Check if Mi Band integration is enabled (and add more devices in the future) | // Path: app/src/main/java/com/red/alert/logic/alerts/AlertTypes.java
// public class AlertTypes {
// public static final String SYSTEM = "system";
// public static final String PRIMARY = "alert";
// public static final String SECONDARY = "secondary_alert";
//
// public static final String TEST = "test";
// public static final String TEST_SOUND = "test_sound";
// public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
// }
//
// Path: app/src/main/java/com/red/alert/logic/integration/devices/MiBandIntegration.java
// public class MiBandIntegration {
// public static void notifyMiBand(final Context context) {
// // Xiaomi Mi Band integration enabled?
// if (!AppPreferences.getMiBandIntegrationEnabled(context)) {
// // Stop execution
// return;
// }
//
// // Get an instance of the Mi Band SDK
// MiBand miBand = MiBand.getInstance(context);
//
// // Attempt to connect to it
// miBand.connect(new ActionCallback() {
// @Override
// public void onSuccess(Object data) {
// // Log it
// Log.d(Logging.TAG, "Connected to Mi Band");
//
// // Vibration + LED colors
// sendNotificationCommands(context);
// }
//
// @Override
// public void onFail(int errorCode, String msg) {
// // Log fail
// Log.d(Logging.TAG, "Failed to connect to Mi Band: " + msg);
// }
// });
// }
//
// public static void sendNotificationCommands(Context context) {
// // Get an instance of the Mi Band SDK
// MiBand miBand = MiBand.getInstance(context);
//
// // Not connected for some reason?
// if (!miBand.isConnected()) {
// // Log it
// Log.e(Logging.TAG, "Mi Band is no longer connected!");
// }
//
// // Set red LED color (determined via MiBandExample color picker)
// int ledColor = -64746;
//
// // Repeat the vibration + color
// int repeatTimes = 3;
//
// // Sleep in between each notification
// int sleepInterval = 2000;
//
// // Send the notification commands repeatedly
// miBand.notifyBandRepeated(ledColor, repeatTimes, sleepInterval);
// }
// }
//
// Path: app/src/main/java/com/red/alert/logic/settings/AppPreferences.java
// public class AppPreferences {
// public static boolean getNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.enabledPref), true);
// }
//
// public static boolean getLocationAlertsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.locationAlertsPref), false);
// }
//
// public static boolean getSecondaryNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.secondaryEnabledPref), false);
// }
//
// public static boolean getMiBandIntegrationEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.miBandPref), false);
// }
//
// public static boolean getTutorialDisplayed(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.tutorialPref), false);
// }
//
// public static boolean getPopupEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.alertPopupPref), true);
// }
//
// public static void setTutorialDisplayed(Context context) {
// // Update stored value
// Singleton.getSharedPreferences(context).edit().putBoolean(context.getString(R.string.tutorialPref), true).commit();
// }
//
// public static void setCityLastAlertTime(String city, long timestamp, Context context) {
// // Update last alert timestamp for this city
// Singleton.getSharedPreferences(context).edit().putLong(city, timestamp).commit();
// }
//
// public static long getCityLastAlert(String city, Context context) {
// // Get last alert timestamp for this city
// return Singleton.getSharedPreferences(context).getLong(city, 0);
// }
//
// public static float getPrimaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.volumePref), 1.0f);
// }
//
// public static float getSecondaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.secondaryVolumePref), 1.0f);
// }
// }
// Path: app/src/main/java/com/red/alert/logic/integration/BluetoothIntegration.java
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Looper;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.logic.integration.devices.MiBandIntegration;
import com.red.alert.logic.settings.AppPreferences;
package com.red.alert.logic.integration;
public class BluetoothIntegration {
public static void notifyDevices(String alertType, Context context) {
// Type must be an "alert" or "test"
if (alertType.equals(AlertTypes.PRIMARY) || alertType.equals(AlertTypes.TEST)) {
// Check for BLE support + enabled Bluetooth controller
if (!isBLESupported(context) || !isBluetoothEnabled()) {
// Stop execution
return;
}
// Vibrate + LED for Mi Band (if enabled)
MiBandIntegration.notifyMiBand(context);
}
}
public static boolean isIntegrationEnabled(Context context) {
// Check if Mi Band integration is enabled (and add more devices in the future) | return AppPreferences.getMiBandIntegrationEnabled(context); |
eladnava/redalert-android | app/src/main/java/com/betomaluje/miband/sqlite/MasterSQLiteHelper.java | // Path: app/src/main/java/com/betomaluje/miband/AppUtils.java
// public class AppUtils {
//
// public static boolean supportsBluetoothLE(Context context) {
// return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
// }
//
// public static boolean isRunningLollipopOrLater() {
// return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
// }
//
// }
| import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.betomaluje.miband.AppUtils; | package com.betomaluje.miband.sqlite;
/**
* Created by betomaluje on 7/6/15.
*/
public class MasterSQLiteHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "miband.db";
private static final int DATABASE_VERSION = 1;
/**
* WITHOUT ROWID is only available with sqlite 3.8.2, which is available
* with Lollipop and later.
*
* @return the "WITHOUT ROWID" string or an empty string for pre-Lollipop devices
*/
private String getWithoutRowId() { | // Path: app/src/main/java/com/betomaluje/miband/AppUtils.java
// public class AppUtils {
//
// public static boolean supportsBluetoothLE(Context context) {
// return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
// }
//
// public static boolean isRunningLollipopOrLater() {
// return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
// }
//
// }
// Path: app/src/main/java/com/betomaluje/miband/sqlite/MasterSQLiteHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.betomaluje.miband.AppUtils;
package com.betomaluje.miband.sqlite;
/**
* Created by betomaluje on 7/6/15.
*/
public class MasterSQLiteHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "miband.db";
private static final int DATABASE_VERSION = 1;
/**
* WITHOUT ROWID is only available with sqlite 3.8.2, which is available
* with Lollipop and later.
*
* @return the "WITHOUT ROWID" string or an empty string for pre-Lollipop devices
*/
private String getWithoutRowId() { | if (AppUtils.isRunningLollipopOrLater()) { |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/push/FCMRegistration.java | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/push/FCMGateway.java
// public class FCMGateway {
// // FCM Sender ID
// public static String SENDER_ID = "23150228579";
//
// // FCM Scope
// public static String SCOPE = "*";
//
// // FCM Topic Name for PubSub push notifications
// public static String ALERTS_TOPIC = "alerts";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/integration/GooglePlayServices.java
// public class GooglePlayServices {
// public static boolean isAvailable(Context context) {
// // Get availability checker
// GoogleApiAvailability playServices = GoogleApiAvailability.getInstance();
//
// // Check whether services are available
// int result = playServices.isGooglePlayServicesAvailable(context);
//
// // Are we good?
// return result == ConnectionResult.SUCCESS;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.push.FCMGateway;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.integration.GooglePlayServices;
import androidx.annotation.NonNull; | package com.red.alert.logic.push;
public class FCMRegistration {
public static String registerForPushNotifications(final Context context) throws Exception {
// Make sure we have Google Play Services | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/push/FCMGateway.java
// public class FCMGateway {
// // FCM Sender ID
// public static String SENDER_ID = "23150228579";
//
// // FCM Scope
// public static String SCOPE = "*";
//
// // FCM Topic Name for PubSub push notifications
// public static String ALERTS_TOPIC = "alerts";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/integration/GooglePlayServices.java
// public class GooglePlayServices {
// public static boolean isAvailable(Context context) {
// // Get availability checker
// GoogleApiAvailability playServices = GoogleApiAvailability.getInstance();
//
// // Check whether services are available
// int result = playServices.isGooglePlayServicesAvailable(context);
//
// // Are we good?
// return result == ConnectionResult.SUCCESS;
// }
// }
// Path: app/src/main/java/com/red/alert/logic/push/FCMRegistration.java
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.push.FCMGateway;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.integration.GooglePlayServices;
import androidx.annotation.NonNull;
package com.red.alert.logic.push;
public class FCMRegistration {
public static String registerForPushNotifications(final Context context) throws Exception {
// Make sure we have Google Play Services | if (!GooglePlayServices.isAvailable(context)) { |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/push/FCMRegistration.java | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/push/FCMGateway.java
// public class FCMGateway {
// // FCM Sender ID
// public static String SENDER_ID = "23150228579";
//
// // FCM Scope
// public static String SCOPE = "*";
//
// // FCM Topic Name for PubSub push notifications
// public static String ALERTS_TOPIC = "alerts";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/integration/GooglePlayServices.java
// public class GooglePlayServices {
// public static boolean isAvailable(Context context) {
// // Get availability checker
// GoogleApiAvailability playServices = GoogleApiAvailability.getInstance();
//
// // Check whether services are available
// int result = playServices.isGooglePlayServicesAvailable(context);
//
// // Are we good?
// return result == ConnectionResult.SUCCESS;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.push.FCMGateway;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.integration.GooglePlayServices;
import androidx.annotation.NonNull; | package com.red.alert.logic.push;
public class FCMRegistration {
public static String registerForPushNotifications(final Context context) throws Exception {
// Make sure we have Google Play Services
if (!GooglePlayServices.isAvailable(context)) {
// Throw exception
throw new Exception(context.getString(R.string.noGooglePlayServices));
}
// Get an FCM registration token | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/push/FCMGateway.java
// public class FCMGateway {
// // FCM Sender ID
// public static String SENDER_ID = "23150228579";
//
// // FCM Scope
// public static String SCOPE = "*";
//
// // FCM Topic Name for PubSub push notifications
// public static String ALERTS_TOPIC = "alerts";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/integration/GooglePlayServices.java
// public class GooglePlayServices {
// public static boolean isAvailable(Context context) {
// // Get availability checker
// GoogleApiAvailability playServices = GoogleApiAvailability.getInstance();
//
// // Check whether services are available
// int result = playServices.isGooglePlayServicesAvailable(context);
//
// // Are we good?
// return result == ConnectionResult.SUCCESS;
// }
// }
// Path: app/src/main/java/com/red/alert/logic/push/FCMRegistration.java
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.push.FCMGateway;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.integration.GooglePlayServices;
import androidx.annotation.NonNull;
package com.red.alert.logic.push;
public class FCMRegistration {
public static String registerForPushNotifications(final Context context) throws Exception {
// Make sure we have Google Play Services
if (!GooglePlayServices.isAvailable(context)) {
// Throw exception
throw new Exception(context.getString(R.string.noGooglePlayServices));
}
// Get an FCM registration token | final String token = FirebaseInstanceId.getInstance().getToken(FCMGateway.SENDER_ID, FCMGateway.SCOPE); |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/push/FCMRegistration.java | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/push/FCMGateway.java
// public class FCMGateway {
// // FCM Sender ID
// public static String SENDER_ID = "23150228579";
//
// // FCM Scope
// public static String SCOPE = "*";
//
// // FCM Topic Name for PubSub push notifications
// public static String ALERTS_TOPIC = "alerts";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/integration/GooglePlayServices.java
// public class GooglePlayServices {
// public static boolean isAvailable(Context context) {
// // Get availability checker
// GoogleApiAvailability playServices = GoogleApiAvailability.getInstance();
//
// // Check whether services are available
// int result = playServices.isGooglePlayServicesAvailable(context);
//
// // Are we good?
// return result == ConnectionResult.SUCCESS;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.push.FCMGateway;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.integration.GooglePlayServices;
import androidx.annotation.NonNull; | package com.red.alert.logic.push;
public class FCMRegistration {
public static String registerForPushNotifications(final Context context) throws Exception {
// Make sure we have Google Play Services
if (!GooglePlayServices.isAvailable(context)) {
// Throw exception
throw new Exception(context.getString(R.string.noGooglePlayServices));
}
// Get an FCM registration token
final String token = FirebaseInstanceId.getInstance().getToken(FCMGateway.SENDER_ID, FCMGateway.SCOPE);
// Log to logcat | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/push/FCMGateway.java
// public class FCMGateway {
// // FCM Sender ID
// public static String SENDER_ID = "23150228579";
//
// // FCM Scope
// public static String SCOPE = "*";
//
// // FCM Topic Name for PubSub push notifications
// public static String ALERTS_TOPIC = "alerts";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/integration/GooglePlayServices.java
// public class GooglePlayServices {
// public static boolean isAvailable(Context context) {
// // Get availability checker
// GoogleApiAvailability playServices = GoogleApiAvailability.getInstance();
//
// // Check whether services are available
// int result = playServices.isGooglePlayServicesAvailable(context);
//
// // Are we good?
// return result == ConnectionResult.SUCCESS;
// }
// }
// Path: app/src/main/java/com/red/alert/logic/push/FCMRegistration.java
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.push.FCMGateway;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.integration.GooglePlayServices;
import androidx.annotation.NonNull;
package com.red.alert.logic.push;
public class FCMRegistration {
public static String registerForPushNotifications(final Context context) throws Exception {
// Make sure we have Google Play Services
if (!GooglePlayServices.isAvailable(context)) {
// Throw exception
throw new Exception(context.getString(R.string.noGooglePlayServices));
}
// Get an FCM registration token
final String token = FirebaseInstanceId.getInstance().getToken(FCMGateway.SENDER_ID, FCMGateway.SCOPE);
// Log to logcat | Log.d(Logging.TAG, "FCM registration success: " + token); |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/push/FCMRegistration.java | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/push/FCMGateway.java
// public class FCMGateway {
// // FCM Sender ID
// public static String SENDER_ID = "23150228579";
//
// // FCM Scope
// public static String SCOPE = "*";
//
// // FCM Topic Name for PubSub push notifications
// public static String ALERTS_TOPIC = "alerts";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/integration/GooglePlayServices.java
// public class GooglePlayServices {
// public static boolean isAvailable(Context context) {
// // Get availability checker
// GoogleApiAvailability playServices = GoogleApiAvailability.getInstance();
//
// // Check whether services are available
// int result = playServices.isGooglePlayServicesAvailable(context);
//
// // Are we good?
// return result == ConnectionResult.SUCCESS;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.push.FCMGateway;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.integration.GooglePlayServices;
import androidx.annotation.NonNull; | package com.red.alert.logic.push;
public class FCMRegistration {
public static String registerForPushNotifications(final Context context) throws Exception {
// Make sure we have Google Play Services
if (!GooglePlayServices.isAvailable(context)) {
// Throw exception
throw new Exception(context.getString(R.string.noGooglePlayServices));
}
// Get an FCM registration token
final String token = FirebaseInstanceId.getInstance().getToken(FCMGateway.SENDER_ID, FCMGateway.SCOPE);
// Log to logcat
Log.d(Logging.TAG, "FCM registration success: " + token);
// Unsubscribe from alerts topic (FCM Pub/Sub is unreliable for mission-critical alerts)
FirebaseMessaging.getInstance().unsubscribeFromTopic(FCMGateway.ALERTS_TOPIC)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (!task.isSuccessful()) {
Log.e(Logging.TAG, "FCM unsubscribe failed: ", task.getException());
return;
}
// Log it
Log.d(Logging.TAG, "FCM unsubscribe success: " + FCMGateway.ALERTS_TOPIC);
}
});
// Return token for saving and processing
return token;
}
public static String getRegistrationToken(Context context) {
// Get it from SharedPreferences (may be null) | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/push/FCMGateway.java
// public class FCMGateway {
// // FCM Sender ID
// public static String SENDER_ID = "23150228579";
//
// // FCM Scope
// public static String SCOPE = "*";
//
// // FCM Topic Name for PubSub push notifications
// public static String ALERTS_TOPIC = "alerts";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/integration/GooglePlayServices.java
// public class GooglePlayServices {
// public static boolean isAvailable(Context context) {
// // Get availability checker
// GoogleApiAvailability playServices = GoogleApiAvailability.getInstance();
//
// // Check whether services are available
// int result = playServices.isGooglePlayServicesAvailable(context);
//
// // Are we good?
// return result == ConnectionResult.SUCCESS;
// }
// }
// Path: app/src/main/java/com/red/alert/logic/push/FCMRegistration.java
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.push.FCMGateway;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.integration.GooglePlayServices;
import androidx.annotation.NonNull;
package com.red.alert.logic.push;
public class FCMRegistration {
public static String registerForPushNotifications(final Context context) throws Exception {
// Make sure we have Google Play Services
if (!GooglePlayServices.isAvailable(context)) {
// Throw exception
throw new Exception(context.getString(R.string.noGooglePlayServices));
}
// Get an FCM registration token
final String token = FirebaseInstanceId.getInstance().getToken(FCMGateway.SENDER_ID, FCMGateway.SCOPE);
// Log to logcat
Log.d(Logging.TAG, "FCM registration success: " + token);
// Unsubscribe from alerts topic (FCM Pub/Sub is unreliable for mission-critical alerts)
FirebaseMessaging.getInstance().unsubscribeFromTopic(FCMGateway.ALERTS_TOPIC)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (!task.isSuccessful()) {
Log.e(Logging.TAG, "FCM unsubscribe failed: ", task.getException());
return;
}
// Log it
Log.d(Logging.TAG, "FCM unsubscribe success: " + FCMGateway.ALERTS_TOPIC);
}
});
// Return token for saving and processing
return token;
}
public static String getRegistrationToken(Context context) {
// Get it from SharedPreferences (may be null) | return Singleton.getSharedPreferences(context).getString(context.getString(R.string.fcmTokenPref), null); |
eladnava/redalert-android | app/src/main/java/com/red/alert/utils/communication/Broadcasts.java | // Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import com.red.alert.utils.caching.Singleton; | package com.red.alert.utils.communication;
public class Broadcasts {
public static void subscribe(Context context, SharedPreferences.OnSharedPreferenceChangeListener listener) {
// Listen for preference changes | // Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
// Path: app/src/main/java/com/red/alert/utils/communication/Broadcasts.java
import android.content.Context;
import android.content.SharedPreferences;
import com.red.alert.utils.caching.Singleton;
package com.red.alert.utils.communication;
public class Broadcasts {
public static void subscribe(Context context, SharedPreferences.OnSharedPreferenceChangeListener listener) {
// Listen for preference changes | Singleton.getSharedPreferences(context).registerOnSharedPreferenceChangeListener(listener); |
eladnava/redalert-android | app/src/main/java/com/red/alert/ui/dialogs/AlertDialogBuilder.java | // Path: app/src/main/java/com/red/alert/ui/localization/rtl/RTLSupport.java
// public class RTLSupport {
// @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
// public static void mirrorActionBar(Activity activity) {
// // Hebrew only
// if (!Localization.isHebrewLocale(activity)) {
// return;
// }
//
// // Must be Jellybean or newer
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// // Set RTL layout direction
// activity.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
// }
// }
//
// @SuppressLint("NewApi")
// public static void mirrorDialog(Dialog dialog, Context context) {
// // Hebrew only
// if (!Localization.isHebrewLocale(context)) {
// return;
// }
//
// try {
// // Get message text view
// TextView message = (TextView) dialog.findViewById(android.R.id.message);
//
// // Defy gravity
// if (message != null) {
// message.setGravity(Gravity.RIGHT);
// }
//
// // Get the title of text view
// TextView title = (TextView) dialog.findViewById(context.getResources().getIdentifier("alertTitle", "id", "android"));
//
// // Defy gravity
// title.setGravity(Gravity.RIGHT);
//
// // Get list view (may not exist)
// ListView listView = (ListView) dialog.findViewById(context.getResources().getIdentifier("select_dialog_listview", "id", "android"));
//
// // Check if list & set RTL mode
// if (listView != null) {
// listView.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
// }
//
// // Get title's parent layout
// LinearLayout parent = ((LinearLayout) title.getParent());
//
// // Get layout params
// LinearLayout.LayoutParams originalParams = (LinearLayout.LayoutParams) parent.getLayoutParams();
//
// // Set width to WRAP_CONTENT
// originalParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
//
// // Defy gravity
// originalParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
//
// // Set layout params
// parent.setLayoutParams(originalParams);
// }
// catch (Exception exc) {
// // Log failure to logcat
// Log.d(Logging.TAG, "RTL failed", exc);
// }
// }
// }
| import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.Toast;
import com.red.alert.R;
import com.red.alert.ui.localization.rtl.RTLSupport; | package com.red.alert.ui.dialogs;
public class AlertDialogBuilder {
public static final void showGenericDialog(String title, String message, Context context, DialogInterface.OnClickListener clickListener) {
// Use builder to create dialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Use builder to create dialog
builder.setTitle(title).setMessage(message).setCancelable(false).setPositiveButton(R.string.okay, clickListener);
// Prevent cancellation
builder.setCancelable(false);
try {
// Build it
AlertDialog dialog = builder.create();
// Show it
dialog.show();
// Support for RTL languages | // Path: app/src/main/java/com/red/alert/ui/localization/rtl/RTLSupport.java
// public class RTLSupport {
// @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
// public static void mirrorActionBar(Activity activity) {
// // Hebrew only
// if (!Localization.isHebrewLocale(activity)) {
// return;
// }
//
// // Must be Jellybean or newer
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// // Set RTL layout direction
// activity.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
// }
// }
//
// @SuppressLint("NewApi")
// public static void mirrorDialog(Dialog dialog, Context context) {
// // Hebrew only
// if (!Localization.isHebrewLocale(context)) {
// return;
// }
//
// try {
// // Get message text view
// TextView message = (TextView) dialog.findViewById(android.R.id.message);
//
// // Defy gravity
// if (message != null) {
// message.setGravity(Gravity.RIGHT);
// }
//
// // Get the title of text view
// TextView title = (TextView) dialog.findViewById(context.getResources().getIdentifier("alertTitle", "id", "android"));
//
// // Defy gravity
// title.setGravity(Gravity.RIGHT);
//
// // Get list view (may not exist)
// ListView listView = (ListView) dialog.findViewById(context.getResources().getIdentifier("select_dialog_listview", "id", "android"));
//
// // Check if list & set RTL mode
// if (listView != null) {
// listView.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
// }
//
// // Get title's parent layout
// LinearLayout parent = ((LinearLayout) title.getParent());
//
// // Get layout params
// LinearLayout.LayoutParams originalParams = (LinearLayout.LayoutParams) parent.getLayoutParams();
//
// // Set width to WRAP_CONTENT
// originalParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
//
// // Defy gravity
// originalParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
//
// // Set layout params
// parent.setLayoutParams(originalParams);
// }
// catch (Exception exc) {
// // Log failure to logcat
// Log.d(Logging.TAG, "RTL failed", exc);
// }
// }
// }
// Path: app/src/main/java/com/red/alert/ui/dialogs/AlertDialogBuilder.java
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.Toast;
import com.red.alert.R;
import com.red.alert.ui.localization.rtl.RTLSupport;
package com.red.alert.ui.dialogs;
public class AlertDialogBuilder {
public static final void showGenericDialog(String title, String message, Context context, DialogInterface.OnClickListener clickListener) {
// Use builder to create dialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Use builder to create dialog
builder.setTitle(title).setMessage(message).setCancelable(false).setPositiveButton(R.string.okay, clickListener);
// Prevent cancellation
builder.setCancelable(false);
try {
// Build it
AlertDialog dialog = builder.create();
// Show it
dialog.show();
// Support for RTL languages | RTLSupport.mirrorDialog(dialog, context); |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/location/LocationLogic.java | // Path: app/src/main/java/com/red/alert/config/LocationAlerts.java
// public class LocationAlerts {
// // Max distance that can be selected for location-based alerts
// public static int MAX_DISTANCE_KM = 50;
//
// // Max location polling frequency for location-based alerts (higher value is less reliable)
// public static int MAX_FREQUENCY_MIN = 60;
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/integration/GooglePlayServices.java
// public class GooglePlayServices {
// public static boolean isAvailable(Context context) {
// // Get availability checker
// GoogleApiAvailability playServices = GoogleApiAvailability.getInstance();
//
// // Check whether services are available
// int result = playServices.isGooglePlayServicesAvailable(context);
//
// // Are we good?
// return result == ConnectionResult.SUCCESS;
// }
// }
| import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import com.red.alert.R;
import com.red.alert.config.LocationAlerts;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.integration.GooglePlayServices;
import androidx.core.app.ActivityCompat; | package com.red.alert.logic.location;
public class LocationLogic {
public static int getUpdateIntervalMinutes(Context context, float overrideSetting) {
// Get stored value | // Path: app/src/main/java/com/red/alert/config/LocationAlerts.java
// public class LocationAlerts {
// // Max distance that can be selected for location-based alerts
// public static int MAX_DISTANCE_KM = 50;
//
// // Max location polling frequency for location-based alerts (higher value is less reliable)
// public static int MAX_FREQUENCY_MIN = 60;
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/integration/GooglePlayServices.java
// public class GooglePlayServices {
// public static boolean isAvailable(Context context) {
// // Get availability checker
// GoogleApiAvailability playServices = GoogleApiAvailability.getInstance();
//
// // Check whether services are available
// int result = playServices.isGooglePlayServicesAvailable(context);
//
// // Are we good?
// return result == ConnectionResult.SUCCESS;
// }
// }
// Path: app/src/main/java/com/red/alert/logic/location/LocationLogic.java
import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import com.red.alert.R;
import com.red.alert.config.LocationAlerts;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.integration.GooglePlayServices;
import androidx.core.app.ActivityCompat;
package com.red.alert.logic.location;
public class LocationLogic {
public static int getUpdateIntervalMinutes(Context context, float overrideSetting) {
// Get stored value | float sliderValue = Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.gpsFrequencyPref), 0.02f); |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/location/LocationLogic.java | // Path: app/src/main/java/com/red/alert/config/LocationAlerts.java
// public class LocationAlerts {
// // Max distance that can be selected for location-based alerts
// public static int MAX_DISTANCE_KM = 50;
//
// // Max location polling frequency for location-based alerts (higher value is less reliable)
// public static int MAX_FREQUENCY_MIN = 60;
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/integration/GooglePlayServices.java
// public class GooglePlayServices {
// public static boolean isAvailable(Context context) {
// // Get availability checker
// GoogleApiAvailability playServices = GoogleApiAvailability.getInstance();
//
// // Check whether services are available
// int result = playServices.isGooglePlayServicesAvailable(context);
//
// // Are we good?
// return result == ConnectionResult.SUCCESS;
// }
// }
| import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import com.red.alert.R;
import com.red.alert.config.LocationAlerts;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.integration.GooglePlayServices;
import androidx.core.app.ActivityCompat; | package com.red.alert.logic.location;
public class LocationLogic {
public static int getUpdateIntervalMinutes(Context context, float overrideSetting) {
// Get stored value
float sliderValue = Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.gpsFrequencyPref), 0.02f);
// Override it?
if (overrideSetting != -1) {
sliderValue = overrideSetting;
}
// Calculate frequency in minutes | // Path: app/src/main/java/com/red/alert/config/LocationAlerts.java
// public class LocationAlerts {
// // Max distance that can be selected for location-based alerts
// public static int MAX_DISTANCE_KM = 50;
//
// // Max location polling frequency for location-based alerts (higher value is less reliable)
// public static int MAX_FREQUENCY_MIN = 60;
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/integration/GooglePlayServices.java
// public class GooglePlayServices {
// public static boolean isAvailable(Context context) {
// // Get availability checker
// GoogleApiAvailability playServices = GoogleApiAvailability.getInstance();
//
// // Check whether services are available
// int result = playServices.isGooglePlayServicesAvailable(context);
//
// // Are we good?
// return result == ConnectionResult.SUCCESS;
// }
// }
// Path: app/src/main/java/com/red/alert/logic/location/LocationLogic.java
import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import com.red.alert.R;
import com.red.alert.config.LocationAlerts;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.integration.GooglePlayServices;
import androidx.core.app.ActivityCompat;
package com.red.alert.logic.location;
public class LocationLogic {
public static int getUpdateIntervalMinutes(Context context, float overrideSetting) {
// Get stored value
float sliderValue = Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.gpsFrequencyPref), 0.02f);
// Override it?
if (overrideSetting != -1) {
sliderValue = overrideSetting;
}
// Calculate frequency in minutes | int frequencyMin = (int) (LocationAlerts.MAX_FREQUENCY_MIN * sliderValue); |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/location/LocationLogic.java | // Path: app/src/main/java/com/red/alert/config/LocationAlerts.java
// public class LocationAlerts {
// // Max distance that can be selected for location-based alerts
// public static int MAX_DISTANCE_KM = 50;
//
// // Max location polling frequency for location-based alerts (higher value is less reliable)
// public static int MAX_FREQUENCY_MIN = 60;
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/integration/GooglePlayServices.java
// public class GooglePlayServices {
// public static boolean isAvailable(Context context) {
// // Get availability checker
// GoogleApiAvailability playServices = GoogleApiAvailability.getInstance();
//
// // Check whether services are available
// int result = playServices.isGooglePlayServicesAvailable(context);
//
// // Are we good?
// return result == ConnectionResult.SUCCESS;
// }
// }
| import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import com.red.alert.R;
import com.red.alert.config.LocationAlerts;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.integration.GooglePlayServices;
import androidx.core.app.ActivityCompat; | package com.red.alert.logic.location;
public class LocationLogic {
public static int getUpdateIntervalMinutes(Context context, float overrideSetting) {
// Get stored value
float sliderValue = Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.gpsFrequencyPref), 0.02f);
// Override it?
if (overrideSetting != -1) {
sliderValue = overrideSetting;
}
// Calculate frequency in minutes
int frequencyMin = (int) (LocationAlerts.MAX_FREQUENCY_MIN * sliderValue);
// Return it
return frequencyMin;
}
public static int getMaxDistanceKilometers(Context context, float overrideSetting) {
// Get stored value
float sliderValue = Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.maxDistancePref), 0.04f);
// Override it?
if (overrideSetting != -1) {
sliderValue = overrideSetting;
}
// Calculate frequency in minutes
int maxDistance = (int) (LocationAlerts.MAX_DISTANCE_KM * sliderValue);
// Return it
return maxDistance;
}
public static long getUpdateIntervalMilliseconds(Context context) {
// Convert to milliseconds
return getUpdateIntervalMinutes(context, -1) * 60 * 1000;
}
public static boolean shouldRequestLocationUpdates(Context context) {
// Must have Google Play Services | // Path: app/src/main/java/com/red/alert/config/LocationAlerts.java
// public class LocationAlerts {
// // Max distance that can be selected for location-based alerts
// public static int MAX_DISTANCE_KM = 50;
//
// // Max location polling frequency for location-based alerts (higher value is less reliable)
// public static int MAX_FREQUENCY_MIN = 60;
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/integration/GooglePlayServices.java
// public class GooglePlayServices {
// public static boolean isAvailable(Context context) {
// // Get availability checker
// GoogleApiAvailability playServices = GoogleApiAvailability.getInstance();
//
// // Check whether services are available
// int result = playServices.isGooglePlayServicesAvailable(context);
//
// // Are we good?
// return result == ConnectionResult.SUCCESS;
// }
// }
// Path: app/src/main/java/com/red/alert/logic/location/LocationLogic.java
import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import com.red.alert.R;
import com.red.alert.config.LocationAlerts;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.integration.GooglePlayServices;
import androidx.core.app.ActivityCompat;
package com.red.alert.logic.location;
public class LocationLogic {
public static int getUpdateIntervalMinutes(Context context, float overrideSetting) {
// Get stored value
float sliderValue = Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.gpsFrequencyPref), 0.02f);
// Override it?
if (overrideSetting != -1) {
sliderValue = overrideSetting;
}
// Calculate frequency in minutes
int frequencyMin = (int) (LocationAlerts.MAX_FREQUENCY_MIN * sliderValue);
// Return it
return frequencyMin;
}
public static int getMaxDistanceKilometers(Context context, float overrideSetting) {
// Get stored value
float sliderValue = Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.maxDistancePref), 0.04f);
// Override it?
if (overrideSetting != -1) {
sliderValue = overrideSetting;
}
// Calculate frequency in minutes
int maxDistance = (int) (LocationAlerts.MAX_DISTANCE_KM * sliderValue);
// Return it
return maxDistance;
}
public static long getUpdateIntervalMilliseconds(Context context) {
// Convert to milliseconds
return getUpdateIntervalMinutes(context, -1) * 60 * 1000;
}
public static boolean shouldRequestLocationUpdates(Context context) {
// Must have Google Play Services | if (!GooglePlayServices.isAvailable(context)) { |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/feedback/sound/SoundLogic.java | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/Sound.java
// public class Sound {
// public static final String SCHEME_URI_IDENTIFIER = "://";
// public static final String APP_SOUND_PREFIX = "com.red.alert://";
// // The AudioManager stream that sirens will be played on
// public static int STREAM_TYPE = AudioManager.STREAM_ALARM;
// }
//
// Path: app/src/main/java/com/red/alert/logic/alerts/AlertTypes.java
// public class AlertTypes {
// public static final String SYSTEM = "system";
// public static final String PRIMARY = "alert";
// public static final String SECONDARY = "secondary_alert";
//
// public static final String TEST = "test";
// public static final String TEST_SOUND = "test_sound";
// public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/feedback/Vibration.java
// public class Vibration {
// public static void stopVibration(Context context) {
// // Get vibration service
// Vibrator vibratorService = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
//
// // Cancel any current vibrations
// vibratorService.cancel();
// }
//
// public static void issueVibration(String alertType, Context context) {
// // Enable vibration?
// if (!VibrationLogic.isVibrationEnabled(alertType, context)) {
// return;
// }
//
// // Should we vibrate?
// if (!VibrationLogic.shouldVibrate(alertType, context)) {
// return;
// }
//
// // Get vibration service
// Vibrator vibratorService = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
//
// // Play only once
// vibratorService.vibrate(com.red.alert.config.Vibration.VIBRATION_PATTERN, -1);
// }
//
// }
//
// Path: app/src/main/java/com/red/alert/utils/formatting/StringUtils.java
// public class StringUtils {
// public static boolean stringIsNullOrEmpty(String inputString) {
// // String is null? return true
// if (inputString == null) {
// return true;
// }
//
// // String is empty? true
// if (inputString.trim().equals("")) {
// return true;
// }
//
// // String is not empty
// return false;
// }
//
// public static String implode(String separator, List<String> data) {
// // No data?
// if (data.size() == 0) {
// return "";
// }
//
// // Create temp StringBuilder
// StringBuilder builder = new StringBuilder();
//
// // Loop over list except last item
// for (int i = 0; i < data.size() - 1; i++) {
// // Append current item
// builder.append(data.get(i));
//
// // Append separator
// builder.append(separator);
// }
//
// // Add last item without separator
// builder.append(data.get(data.size() - 1));
//
// // Return string
// return builder.toString();
// }
//
// public static String regexMatch(String source, String compilePattern) {
// // Compile regex
// Pattern compiledPattern = Pattern.compile(compilePattern);
//
// // Match against source input
// Matcher matcher = compiledPattern.matcher(source);
//
// // Prepare match object
// String match = "";
//
// // Did we find anything?
// if (matcher.find()) {
// // Get first group
// match = matcher.group(1);
// }
//
// // Return match
// return match;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.Sound;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.feedback.Vibration;
import com.red.alert.utils.formatting.StringUtils; | package com.red.alert.logic.feedback.sound;
public class SoundLogic {
static MediaPlayer mPlayer;
static final int ALARM_CUTOFF_SECONDS = 5;
public static boolean shouldPlayAlertSound(String alertType, Context context) {
// No type? | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/Sound.java
// public class Sound {
// public static final String SCHEME_URI_IDENTIFIER = "://";
// public static final String APP_SOUND_PREFIX = "com.red.alert://";
// // The AudioManager stream that sirens will be played on
// public static int STREAM_TYPE = AudioManager.STREAM_ALARM;
// }
//
// Path: app/src/main/java/com/red/alert/logic/alerts/AlertTypes.java
// public class AlertTypes {
// public static final String SYSTEM = "system";
// public static final String PRIMARY = "alert";
// public static final String SECONDARY = "secondary_alert";
//
// public static final String TEST = "test";
// public static final String TEST_SOUND = "test_sound";
// public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/feedback/Vibration.java
// public class Vibration {
// public static void stopVibration(Context context) {
// // Get vibration service
// Vibrator vibratorService = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
//
// // Cancel any current vibrations
// vibratorService.cancel();
// }
//
// public static void issueVibration(String alertType, Context context) {
// // Enable vibration?
// if (!VibrationLogic.isVibrationEnabled(alertType, context)) {
// return;
// }
//
// // Should we vibrate?
// if (!VibrationLogic.shouldVibrate(alertType, context)) {
// return;
// }
//
// // Get vibration service
// Vibrator vibratorService = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
//
// // Play only once
// vibratorService.vibrate(com.red.alert.config.Vibration.VIBRATION_PATTERN, -1);
// }
//
// }
//
// Path: app/src/main/java/com/red/alert/utils/formatting/StringUtils.java
// public class StringUtils {
// public static boolean stringIsNullOrEmpty(String inputString) {
// // String is null? return true
// if (inputString == null) {
// return true;
// }
//
// // String is empty? true
// if (inputString.trim().equals("")) {
// return true;
// }
//
// // String is not empty
// return false;
// }
//
// public static String implode(String separator, List<String> data) {
// // No data?
// if (data.size() == 0) {
// return "";
// }
//
// // Create temp StringBuilder
// StringBuilder builder = new StringBuilder();
//
// // Loop over list except last item
// for (int i = 0; i < data.size() - 1; i++) {
// // Append current item
// builder.append(data.get(i));
//
// // Append separator
// builder.append(separator);
// }
//
// // Add last item without separator
// builder.append(data.get(data.size() - 1));
//
// // Return string
// return builder.toString();
// }
//
// public static String regexMatch(String source, String compilePattern) {
// // Compile regex
// Pattern compiledPattern = Pattern.compile(compilePattern);
//
// // Match against source input
// Matcher matcher = compiledPattern.matcher(source);
//
// // Prepare match object
// String match = "";
//
// // Did we find anything?
// if (matcher.find()) {
// // Get first group
// match = matcher.group(1);
// }
//
// // Return match
// return match;
// }
// }
// Path: app/src/main/java/com/red/alert/logic/feedback/sound/SoundLogic.java
import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.Sound;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.feedback.Vibration;
import com.red.alert.utils.formatting.StringUtils;
package com.red.alert.logic.feedback.sound;
public class SoundLogic {
static MediaPlayer mPlayer;
static final int ALARM_CUTOFF_SECONDS = 5;
public static boolean shouldPlayAlertSound(String alertType, Context context) {
// No type? | if (StringUtils.stringIsNullOrEmpty(alertType)) { |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/feedback/sound/SoundLogic.java | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/Sound.java
// public class Sound {
// public static final String SCHEME_URI_IDENTIFIER = "://";
// public static final String APP_SOUND_PREFIX = "com.red.alert://";
// // The AudioManager stream that sirens will be played on
// public static int STREAM_TYPE = AudioManager.STREAM_ALARM;
// }
//
// Path: app/src/main/java/com/red/alert/logic/alerts/AlertTypes.java
// public class AlertTypes {
// public static final String SYSTEM = "system";
// public static final String PRIMARY = "alert";
// public static final String SECONDARY = "secondary_alert";
//
// public static final String TEST = "test";
// public static final String TEST_SOUND = "test_sound";
// public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/feedback/Vibration.java
// public class Vibration {
// public static void stopVibration(Context context) {
// // Get vibration service
// Vibrator vibratorService = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
//
// // Cancel any current vibrations
// vibratorService.cancel();
// }
//
// public static void issueVibration(String alertType, Context context) {
// // Enable vibration?
// if (!VibrationLogic.isVibrationEnabled(alertType, context)) {
// return;
// }
//
// // Should we vibrate?
// if (!VibrationLogic.shouldVibrate(alertType, context)) {
// return;
// }
//
// // Get vibration service
// Vibrator vibratorService = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
//
// // Play only once
// vibratorService.vibrate(com.red.alert.config.Vibration.VIBRATION_PATTERN, -1);
// }
//
// }
//
// Path: app/src/main/java/com/red/alert/utils/formatting/StringUtils.java
// public class StringUtils {
// public static boolean stringIsNullOrEmpty(String inputString) {
// // String is null? return true
// if (inputString == null) {
// return true;
// }
//
// // String is empty? true
// if (inputString.trim().equals("")) {
// return true;
// }
//
// // String is not empty
// return false;
// }
//
// public static String implode(String separator, List<String> data) {
// // No data?
// if (data.size() == 0) {
// return "";
// }
//
// // Create temp StringBuilder
// StringBuilder builder = new StringBuilder();
//
// // Loop over list except last item
// for (int i = 0; i < data.size() - 1; i++) {
// // Append current item
// builder.append(data.get(i));
//
// // Append separator
// builder.append(separator);
// }
//
// // Add last item without separator
// builder.append(data.get(data.size() - 1));
//
// // Return string
// return builder.toString();
// }
//
// public static String regexMatch(String source, String compilePattern) {
// // Compile regex
// Pattern compiledPattern = Pattern.compile(compilePattern);
//
// // Match against source input
// Matcher matcher = compiledPattern.matcher(source);
//
// // Prepare match object
// String match = "";
//
// // Did we find anything?
// if (matcher.find()) {
// // Get first group
// match = matcher.group(1);
// }
//
// // Return match
// return match;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.Sound;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.feedback.Vibration;
import com.red.alert.utils.formatting.StringUtils; | package com.red.alert.logic.feedback.sound;
public class SoundLogic {
static MediaPlayer mPlayer;
static final int ALARM_CUTOFF_SECONDS = 5;
public static boolean shouldPlayAlertSound(String alertType, Context context) {
// No type?
if (StringUtils.stringIsNullOrEmpty(alertType)) {
return false;
}
// No sound for system message | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/Sound.java
// public class Sound {
// public static final String SCHEME_URI_IDENTIFIER = "://";
// public static final String APP_SOUND_PREFIX = "com.red.alert://";
// // The AudioManager stream that sirens will be played on
// public static int STREAM_TYPE = AudioManager.STREAM_ALARM;
// }
//
// Path: app/src/main/java/com/red/alert/logic/alerts/AlertTypes.java
// public class AlertTypes {
// public static final String SYSTEM = "system";
// public static final String PRIMARY = "alert";
// public static final String SECONDARY = "secondary_alert";
//
// public static final String TEST = "test";
// public static final String TEST_SOUND = "test_sound";
// public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/feedback/Vibration.java
// public class Vibration {
// public static void stopVibration(Context context) {
// // Get vibration service
// Vibrator vibratorService = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
//
// // Cancel any current vibrations
// vibratorService.cancel();
// }
//
// public static void issueVibration(String alertType, Context context) {
// // Enable vibration?
// if (!VibrationLogic.isVibrationEnabled(alertType, context)) {
// return;
// }
//
// // Should we vibrate?
// if (!VibrationLogic.shouldVibrate(alertType, context)) {
// return;
// }
//
// // Get vibration service
// Vibrator vibratorService = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
//
// // Play only once
// vibratorService.vibrate(com.red.alert.config.Vibration.VIBRATION_PATTERN, -1);
// }
//
// }
//
// Path: app/src/main/java/com/red/alert/utils/formatting/StringUtils.java
// public class StringUtils {
// public static boolean stringIsNullOrEmpty(String inputString) {
// // String is null? return true
// if (inputString == null) {
// return true;
// }
//
// // String is empty? true
// if (inputString.trim().equals("")) {
// return true;
// }
//
// // String is not empty
// return false;
// }
//
// public static String implode(String separator, List<String> data) {
// // No data?
// if (data.size() == 0) {
// return "";
// }
//
// // Create temp StringBuilder
// StringBuilder builder = new StringBuilder();
//
// // Loop over list except last item
// for (int i = 0; i < data.size() - 1; i++) {
// // Append current item
// builder.append(data.get(i));
//
// // Append separator
// builder.append(separator);
// }
//
// // Add last item without separator
// builder.append(data.get(data.size() - 1));
//
// // Return string
// return builder.toString();
// }
//
// public static String regexMatch(String source, String compilePattern) {
// // Compile regex
// Pattern compiledPattern = Pattern.compile(compilePattern);
//
// // Match against source input
// Matcher matcher = compiledPattern.matcher(source);
//
// // Prepare match object
// String match = "";
//
// // Did we find anything?
// if (matcher.find()) {
// // Get first group
// match = matcher.group(1);
// }
//
// // Return match
// return match;
// }
// }
// Path: app/src/main/java/com/red/alert/logic/feedback/sound/SoundLogic.java
import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.Sound;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.feedback.Vibration;
import com.red.alert.utils.formatting.StringUtils;
package com.red.alert.logic.feedback.sound;
public class SoundLogic {
static MediaPlayer mPlayer;
static final int ALARM_CUTOFF_SECONDS = 5;
public static boolean shouldPlayAlertSound(String alertType, Context context) {
// No type?
if (StringUtils.stringIsNullOrEmpty(alertType)) {
return false;
}
// No sound for system message | if (alertType.equals(AlertTypes.SYSTEM)) { |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/feedback/sound/SoundLogic.java | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/Sound.java
// public class Sound {
// public static final String SCHEME_URI_IDENTIFIER = "://";
// public static final String APP_SOUND_PREFIX = "com.red.alert://";
// // The AudioManager stream that sirens will be played on
// public static int STREAM_TYPE = AudioManager.STREAM_ALARM;
// }
//
// Path: app/src/main/java/com/red/alert/logic/alerts/AlertTypes.java
// public class AlertTypes {
// public static final String SYSTEM = "system";
// public static final String PRIMARY = "alert";
// public static final String SECONDARY = "secondary_alert";
//
// public static final String TEST = "test";
// public static final String TEST_SOUND = "test_sound";
// public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/feedback/Vibration.java
// public class Vibration {
// public static void stopVibration(Context context) {
// // Get vibration service
// Vibrator vibratorService = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
//
// // Cancel any current vibrations
// vibratorService.cancel();
// }
//
// public static void issueVibration(String alertType, Context context) {
// // Enable vibration?
// if (!VibrationLogic.isVibrationEnabled(alertType, context)) {
// return;
// }
//
// // Should we vibrate?
// if (!VibrationLogic.shouldVibrate(alertType, context)) {
// return;
// }
//
// // Get vibration service
// Vibrator vibratorService = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
//
// // Play only once
// vibratorService.vibrate(com.red.alert.config.Vibration.VIBRATION_PATTERN, -1);
// }
//
// }
//
// Path: app/src/main/java/com/red/alert/utils/formatting/StringUtils.java
// public class StringUtils {
// public static boolean stringIsNullOrEmpty(String inputString) {
// // String is null? return true
// if (inputString == null) {
// return true;
// }
//
// // String is empty? true
// if (inputString.trim().equals("")) {
// return true;
// }
//
// // String is not empty
// return false;
// }
//
// public static String implode(String separator, List<String> data) {
// // No data?
// if (data.size() == 0) {
// return "";
// }
//
// // Create temp StringBuilder
// StringBuilder builder = new StringBuilder();
//
// // Loop over list except last item
// for (int i = 0; i < data.size() - 1; i++) {
// // Append current item
// builder.append(data.get(i));
//
// // Append separator
// builder.append(separator);
// }
//
// // Add last item without separator
// builder.append(data.get(data.size() - 1));
//
// // Return string
// return builder.toString();
// }
//
// public static String regexMatch(String source, String compilePattern) {
// // Compile regex
// Pattern compiledPattern = Pattern.compile(compilePattern);
//
// // Match against source input
// Matcher matcher = compiledPattern.matcher(source);
//
// // Prepare match object
// String match = "";
//
// // Did we find anything?
// if (matcher.find()) {
// // Get first group
// match = matcher.group(1);
// }
//
// // Return match
// return match;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.Sound;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.feedback.Vibration;
import com.red.alert.utils.formatting.StringUtils; | // Alarm played in past X seconds?
return System.currentTimeMillis() - (1000 * ALARM_CUTOFF_SECONDS);
}
public static void playSound(String alertType, String alertSound, Context context) {
// Should we play it?
if (!shouldPlayAlertSound(alertType, context)) {
return;
}
// Avoid secondary override
if (isSoundCurrentlyPlaying(alertType, context)) {
return;
}
// Get path to resource
Uri alarmSoundURI = getAlertSound(alertType, alertSound, context);
// Invalid sound URI?
if (alarmSoundURI == null) {
return;
}
// Override volume (Also to set the user's chosen volume)
VolumeLogic.setStreamVolume(alertType, context);
// Play sound
playSoundURI(alarmSoundURI, context);
// Vibrate depending on type | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/Sound.java
// public class Sound {
// public static final String SCHEME_URI_IDENTIFIER = "://";
// public static final String APP_SOUND_PREFIX = "com.red.alert://";
// // The AudioManager stream that sirens will be played on
// public static int STREAM_TYPE = AudioManager.STREAM_ALARM;
// }
//
// Path: app/src/main/java/com/red/alert/logic/alerts/AlertTypes.java
// public class AlertTypes {
// public static final String SYSTEM = "system";
// public static final String PRIMARY = "alert";
// public static final String SECONDARY = "secondary_alert";
//
// public static final String TEST = "test";
// public static final String TEST_SOUND = "test_sound";
// public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/feedback/Vibration.java
// public class Vibration {
// public static void stopVibration(Context context) {
// // Get vibration service
// Vibrator vibratorService = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
//
// // Cancel any current vibrations
// vibratorService.cancel();
// }
//
// public static void issueVibration(String alertType, Context context) {
// // Enable vibration?
// if (!VibrationLogic.isVibrationEnabled(alertType, context)) {
// return;
// }
//
// // Should we vibrate?
// if (!VibrationLogic.shouldVibrate(alertType, context)) {
// return;
// }
//
// // Get vibration service
// Vibrator vibratorService = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
//
// // Play only once
// vibratorService.vibrate(com.red.alert.config.Vibration.VIBRATION_PATTERN, -1);
// }
//
// }
//
// Path: app/src/main/java/com/red/alert/utils/formatting/StringUtils.java
// public class StringUtils {
// public static boolean stringIsNullOrEmpty(String inputString) {
// // String is null? return true
// if (inputString == null) {
// return true;
// }
//
// // String is empty? true
// if (inputString.trim().equals("")) {
// return true;
// }
//
// // String is not empty
// return false;
// }
//
// public static String implode(String separator, List<String> data) {
// // No data?
// if (data.size() == 0) {
// return "";
// }
//
// // Create temp StringBuilder
// StringBuilder builder = new StringBuilder();
//
// // Loop over list except last item
// for (int i = 0; i < data.size() - 1; i++) {
// // Append current item
// builder.append(data.get(i));
//
// // Append separator
// builder.append(separator);
// }
//
// // Add last item without separator
// builder.append(data.get(data.size() - 1));
//
// // Return string
// return builder.toString();
// }
//
// public static String regexMatch(String source, String compilePattern) {
// // Compile regex
// Pattern compiledPattern = Pattern.compile(compilePattern);
//
// // Match against source input
// Matcher matcher = compiledPattern.matcher(source);
//
// // Prepare match object
// String match = "";
//
// // Did we find anything?
// if (matcher.find()) {
// // Get first group
// match = matcher.group(1);
// }
//
// // Return match
// return match;
// }
// }
// Path: app/src/main/java/com/red/alert/logic/feedback/sound/SoundLogic.java
import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.Sound;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.feedback.Vibration;
import com.red.alert.utils.formatting.StringUtils;
// Alarm played in past X seconds?
return System.currentTimeMillis() - (1000 * ALARM_CUTOFF_SECONDS);
}
public static void playSound(String alertType, String alertSound, Context context) {
// Should we play it?
if (!shouldPlayAlertSound(alertType, context)) {
return;
}
// Avoid secondary override
if (isSoundCurrentlyPlaying(alertType, context)) {
return;
}
// Get path to resource
Uri alarmSoundURI = getAlertSound(alertType, alertSound, context);
// Invalid sound URI?
if (alarmSoundURI == null) {
return;
}
// Override volume (Also to set the user's chosen volume)
VolumeLogic.setStreamVolume(alertType, context);
// Play sound
playSoundURI(alarmSoundURI, context);
// Vibrate depending on type | Vibration.issueVibration(alertType, context); |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/feedback/sound/SoundLogic.java | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/Sound.java
// public class Sound {
// public static final String SCHEME_URI_IDENTIFIER = "://";
// public static final String APP_SOUND_PREFIX = "com.red.alert://";
// // The AudioManager stream that sirens will be played on
// public static int STREAM_TYPE = AudioManager.STREAM_ALARM;
// }
//
// Path: app/src/main/java/com/red/alert/logic/alerts/AlertTypes.java
// public class AlertTypes {
// public static final String SYSTEM = "system";
// public static final String PRIMARY = "alert";
// public static final String SECONDARY = "secondary_alert";
//
// public static final String TEST = "test";
// public static final String TEST_SOUND = "test_sound";
// public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/feedback/Vibration.java
// public class Vibration {
// public static void stopVibration(Context context) {
// // Get vibration service
// Vibrator vibratorService = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
//
// // Cancel any current vibrations
// vibratorService.cancel();
// }
//
// public static void issueVibration(String alertType, Context context) {
// // Enable vibration?
// if (!VibrationLogic.isVibrationEnabled(alertType, context)) {
// return;
// }
//
// // Should we vibrate?
// if (!VibrationLogic.shouldVibrate(alertType, context)) {
// return;
// }
//
// // Get vibration service
// Vibrator vibratorService = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
//
// // Play only once
// vibratorService.vibrate(com.red.alert.config.Vibration.VIBRATION_PATTERN, -1);
// }
//
// }
//
// Path: app/src/main/java/com/red/alert/utils/formatting/StringUtils.java
// public class StringUtils {
// public static boolean stringIsNullOrEmpty(String inputString) {
// // String is null? return true
// if (inputString == null) {
// return true;
// }
//
// // String is empty? true
// if (inputString.trim().equals("")) {
// return true;
// }
//
// // String is not empty
// return false;
// }
//
// public static String implode(String separator, List<String> data) {
// // No data?
// if (data.size() == 0) {
// return "";
// }
//
// // Create temp StringBuilder
// StringBuilder builder = new StringBuilder();
//
// // Loop over list except last item
// for (int i = 0; i < data.size() - 1; i++) {
// // Append current item
// builder.append(data.get(i));
//
// // Append separator
// builder.append(separator);
// }
//
// // Add last item without separator
// builder.append(data.get(data.size() - 1));
//
// // Return string
// return builder.toString();
// }
//
// public static String regexMatch(String source, String compilePattern) {
// // Compile regex
// Pattern compiledPattern = Pattern.compile(compilePattern);
//
// // Match against source input
// Matcher matcher = compiledPattern.matcher(source);
//
// // Prepare match object
// String match = "";
//
// // Did we find anything?
// if (matcher.find()) {
// // Get first group
// match = matcher.group(1);
// }
//
// // Return match
// return match;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.Sound;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.feedback.Vibration;
import com.red.alert.utils.formatting.StringUtils; | Vibration.stopVibration(context);
}
static void playSoundURI(Uri alarmSoundUi, Context context) {
// No URI?
if (alarmSoundUi == null) {
return;
}
// Already initialized or currently playing?
stopSound(context);
// Create new MediaPlayer
mPlayer = new MediaPlayer();
// Wake up processor
mPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK);
// Set stream type
mPlayer.setAudioStreamType(getSoundStreamType(context));
try {
// Set URI data source
mPlayer.setDataSource(context, alarmSoundUi);
// Prepare media player
mPlayer.prepare();
}
catch (Exception exc) {
// Log it | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/Sound.java
// public class Sound {
// public static final String SCHEME_URI_IDENTIFIER = "://";
// public static final String APP_SOUND_PREFIX = "com.red.alert://";
// // The AudioManager stream that sirens will be played on
// public static int STREAM_TYPE = AudioManager.STREAM_ALARM;
// }
//
// Path: app/src/main/java/com/red/alert/logic/alerts/AlertTypes.java
// public class AlertTypes {
// public static final String SYSTEM = "system";
// public static final String PRIMARY = "alert";
// public static final String SECONDARY = "secondary_alert";
//
// public static final String TEST = "test";
// public static final String TEST_SOUND = "test_sound";
// public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/feedback/Vibration.java
// public class Vibration {
// public static void stopVibration(Context context) {
// // Get vibration service
// Vibrator vibratorService = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
//
// // Cancel any current vibrations
// vibratorService.cancel();
// }
//
// public static void issueVibration(String alertType, Context context) {
// // Enable vibration?
// if (!VibrationLogic.isVibrationEnabled(alertType, context)) {
// return;
// }
//
// // Should we vibrate?
// if (!VibrationLogic.shouldVibrate(alertType, context)) {
// return;
// }
//
// // Get vibration service
// Vibrator vibratorService = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
//
// // Play only once
// vibratorService.vibrate(com.red.alert.config.Vibration.VIBRATION_PATTERN, -1);
// }
//
// }
//
// Path: app/src/main/java/com/red/alert/utils/formatting/StringUtils.java
// public class StringUtils {
// public static boolean stringIsNullOrEmpty(String inputString) {
// // String is null? return true
// if (inputString == null) {
// return true;
// }
//
// // String is empty? true
// if (inputString.trim().equals("")) {
// return true;
// }
//
// // String is not empty
// return false;
// }
//
// public static String implode(String separator, List<String> data) {
// // No data?
// if (data.size() == 0) {
// return "";
// }
//
// // Create temp StringBuilder
// StringBuilder builder = new StringBuilder();
//
// // Loop over list except last item
// for (int i = 0; i < data.size() - 1; i++) {
// // Append current item
// builder.append(data.get(i));
//
// // Append separator
// builder.append(separator);
// }
//
// // Add last item without separator
// builder.append(data.get(data.size() - 1));
//
// // Return string
// return builder.toString();
// }
//
// public static String regexMatch(String source, String compilePattern) {
// // Compile regex
// Pattern compiledPattern = Pattern.compile(compilePattern);
//
// // Match against source input
// Matcher matcher = compiledPattern.matcher(source);
//
// // Prepare match object
// String match = "";
//
// // Did we find anything?
// if (matcher.find()) {
// // Get first group
// match = matcher.group(1);
// }
//
// // Return match
// return match;
// }
// }
// Path: app/src/main/java/com/red/alert/logic/feedback/sound/SoundLogic.java
import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.Sound;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.feedback.Vibration;
import com.red.alert.utils.formatting.StringUtils;
Vibration.stopVibration(context);
}
static void playSoundURI(Uri alarmSoundUi, Context context) {
// No URI?
if (alarmSoundUi == null) {
return;
}
// Already initialized or currently playing?
stopSound(context);
// Create new MediaPlayer
mPlayer = new MediaPlayer();
// Wake up processor
mPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK);
// Set stream type
mPlayer.setAudioStreamType(getSoundStreamType(context));
try {
// Set URI data source
mPlayer.setDataSource(context, alarmSoundUi);
// Prepare media player
mPlayer.prepare();
}
catch (Exception exc) {
// Log it | Log.e(Logging.TAG, "Media player preparation failed", exc); |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/push/PushyRegistration.java | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/push/PushyGateway.java
// public class PushyGateway {
// // Set custom heartbeat interval (in ms) for the underlying MQTT socket
// public static int SOCKET_HEARTBEAT_INTERVAL = 60 * 3;
//
// // Pushy Topic ID for PubSub push notifications
// public static String ALERTS_TOPIC = "alerts";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.push.PushyGateway;
import com.red.alert.utils.caching.Singleton;
import me.pushy.sdk.Pushy; | package com.red.alert.logic.push;
public class PushyRegistration {
public static void registerForPushNotifications(Context context) throws Exception {
// Acquire a unique registration ID for this device
String token = Pushy.register(context);
// Log to logcat | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/push/PushyGateway.java
// public class PushyGateway {
// // Set custom heartbeat interval (in ms) for the underlying MQTT socket
// public static int SOCKET_HEARTBEAT_INTERVAL = 60 * 3;
//
// // Pushy Topic ID for PubSub push notifications
// public static String ALERTS_TOPIC = "alerts";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
// Path: app/src/main/java/com/red/alert/logic/push/PushyRegistration.java
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.push.PushyGateway;
import com.red.alert.utils.caching.Singleton;
import me.pushy.sdk.Pushy;
package com.red.alert.logic.push;
public class PushyRegistration {
public static void registerForPushNotifications(Context context) throws Exception {
// Acquire a unique registration ID for this device
String token = Pushy.register(context);
// Log to logcat | Log.d(Logging.TAG, "Pushy registration success: " + token); |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/push/PushyRegistration.java | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/push/PushyGateway.java
// public class PushyGateway {
// // Set custom heartbeat interval (in ms) for the underlying MQTT socket
// public static int SOCKET_HEARTBEAT_INTERVAL = 60 * 3;
//
// // Pushy Topic ID for PubSub push notifications
// public static String ALERTS_TOPIC = "alerts";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.push.PushyGateway;
import com.red.alert.utils.caching.Singleton;
import me.pushy.sdk.Pushy; | package com.red.alert.logic.push;
public class PushyRegistration {
public static void registerForPushNotifications(Context context) throws Exception {
// Acquire a unique registration ID for this device
String token = Pushy.register(context);
// Log to logcat
Log.d(Logging.TAG, "Pushy registration success: " + token);
// Subscribe to global alerts topic (we need this for location alerts to work) | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/push/PushyGateway.java
// public class PushyGateway {
// // Set custom heartbeat interval (in ms) for the underlying MQTT socket
// public static int SOCKET_HEARTBEAT_INTERVAL = 60 * 3;
//
// // Pushy Topic ID for PubSub push notifications
// public static String ALERTS_TOPIC = "alerts";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
// Path: app/src/main/java/com/red/alert/logic/push/PushyRegistration.java
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.push.PushyGateway;
import com.red.alert.utils.caching.Singleton;
import me.pushy.sdk.Pushy;
package com.red.alert.logic.push;
public class PushyRegistration {
public static void registerForPushNotifications(Context context) throws Exception {
// Acquire a unique registration ID for this device
String token = Pushy.register(context);
// Log to logcat
Log.d(Logging.TAG, "Pushy registration success: " + token);
// Subscribe to global alerts topic (we need this for location alerts to work) | Pushy.subscribe(PushyGateway.ALERTS_TOPIC, context); |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/push/PushyRegistration.java | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/push/PushyGateway.java
// public class PushyGateway {
// // Set custom heartbeat interval (in ms) for the underlying MQTT socket
// public static int SOCKET_HEARTBEAT_INTERVAL = 60 * 3;
//
// // Pushy Topic ID for PubSub push notifications
// public static String ALERTS_TOPIC = "alerts";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.push.PushyGateway;
import com.red.alert.utils.caching.Singleton;
import me.pushy.sdk.Pushy; | package com.red.alert.logic.push;
public class PushyRegistration {
public static void registerForPushNotifications(Context context) throws Exception {
// Acquire a unique registration ID for this device
String token = Pushy.register(context);
// Log to logcat
Log.d(Logging.TAG, "Pushy registration success: " + token);
// Subscribe to global alerts topic (we need this for location alerts to work)
Pushy.subscribe(PushyGateway.ALERTS_TOPIC, context);
// Log it
Log.d(Logging.TAG, "Pushy subscribe success: " + PushyGateway.ALERTS_TOPIC);
// Persist it locally (no need to send it to our API)
saveRegistrationToken(context, token);
}
public static String getRegistrationToken(Context context) {
// Get it from SharedPreferences (may be null) | // Path: app/src/main/java/com/red/alert/config/Logging.java
// public class Logging {
// // Tag for all logcat logs
// public static String TAG = "RedAlert";
// }
//
// Path: app/src/main/java/com/red/alert/config/push/PushyGateway.java
// public class PushyGateway {
// // Set custom heartbeat interval (in ms) for the underlying MQTT socket
// public static int SOCKET_HEARTBEAT_INTERVAL = 60 * 3;
//
// // Pushy Topic ID for PubSub push notifications
// public static String ALERTS_TOPIC = "alerts";
// }
//
// Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
// Path: app/src/main/java/com/red/alert/logic/push/PushyRegistration.java
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.red.alert.R;
import com.red.alert.config.Logging;
import com.red.alert.config.push.PushyGateway;
import com.red.alert.utils.caching.Singleton;
import me.pushy.sdk.Pushy;
package com.red.alert.logic.push;
public class PushyRegistration {
public static void registerForPushNotifications(Context context) throws Exception {
// Acquire a unique registration ID for this device
String token = Pushy.register(context);
// Log to logcat
Log.d(Logging.TAG, "Pushy registration success: " + token);
// Subscribe to global alerts topic (we need this for location alerts to work)
Pushy.subscribe(PushyGateway.ALERTS_TOPIC, context);
// Log it
Log.d(Logging.TAG, "Pushy subscribe success: " + PushyGateway.ALERTS_TOPIC);
// Persist it locally (no need to send it to our API)
saveRegistrationToken(context, token);
}
public static String getRegistrationToken(Context context) {
// Get it from SharedPreferences (may be null) | return Singleton.getSharedPreferences(context).getString(context.getString(R.string.pushyTokenPref), null); |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/feedback/sound/VolumeLogic.java | // Path: app/src/main/java/com/red/alert/config/Sound.java
// public class Sound {
// public static final String SCHEME_URI_IDENTIFIER = "://";
// public static final String APP_SOUND_PREFIX = "com.red.alert://";
// // The AudioManager stream that sirens will be played on
// public static int STREAM_TYPE = AudioManager.STREAM_ALARM;
// }
//
// Path: app/src/main/java/com/red/alert/logic/alerts/AlertTypes.java
// public class AlertTypes {
// public static final String SYSTEM = "system";
// public static final String PRIMARY = "alert";
// public static final String SECONDARY = "secondary_alert";
//
// public static final String TEST = "test";
// public static final String TEST_SOUND = "test_sound";
// public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
// }
//
// Path: app/src/main/java/com/red/alert/logic/settings/AppPreferences.java
// public class AppPreferences {
// public static boolean getNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.enabledPref), true);
// }
//
// public static boolean getLocationAlertsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.locationAlertsPref), false);
// }
//
// public static boolean getSecondaryNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.secondaryEnabledPref), false);
// }
//
// public static boolean getMiBandIntegrationEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.miBandPref), false);
// }
//
// public static boolean getTutorialDisplayed(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.tutorialPref), false);
// }
//
// public static boolean getPopupEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.alertPopupPref), true);
// }
//
// public static void setTutorialDisplayed(Context context) {
// // Update stored value
// Singleton.getSharedPreferences(context).edit().putBoolean(context.getString(R.string.tutorialPref), true).commit();
// }
//
// public static void setCityLastAlertTime(String city, long timestamp, Context context) {
// // Update last alert timestamp for this city
// Singleton.getSharedPreferences(context).edit().putLong(city, timestamp).commit();
// }
//
// public static long getCityLastAlert(String city, Context context) {
// // Get last alert timestamp for this city
// return Singleton.getSharedPreferences(context).getLong(city, 0);
// }
//
// public static float getPrimaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.volumePref), 1.0f);
// }
//
// public static float getSecondaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.secondaryVolumePref), 1.0f);
// }
// }
| import android.content.Context;
import android.media.AudioManager;
import com.red.alert.config.Sound;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.logic.settings.AppPreferences; | package com.red.alert.logic.feedback.sound;
public class VolumeLogic {
public static void setStreamVolume(String alertType, Context context) {
// Get the audio manager
AudioManager audioManager = (AudioManager) context.getSystemService(context.AUDIO_SERVICE);
// Get max possible volume
int requestedVolume = VolumeLogic.getNotificationVolume(alertType, context);
// Set volume to desired level | // Path: app/src/main/java/com/red/alert/config/Sound.java
// public class Sound {
// public static final String SCHEME_URI_IDENTIFIER = "://";
// public static final String APP_SOUND_PREFIX = "com.red.alert://";
// // The AudioManager stream that sirens will be played on
// public static int STREAM_TYPE = AudioManager.STREAM_ALARM;
// }
//
// Path: app/src/main/java/com/red/alert/logic/alerts/AlertTypes.java
// public class AlertTypes {
// public static final String SYSTEM = "system";
// public static final String PRIMARY = "alert";
// public static final String SECONDARY = "secondary_alert";
//
// public static final String TEST = "test";
// public static final String TEST_SOUND = "test_sound";
// public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
// }
//
// Path: app/src/main/java/com/red/alert/logic/settings/AppPreferences.java
// public class AppPreferences {
// public static boolean getNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.enabledPref), true);
// }
//
// public static boolean getLocationAlertsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.locationAlertsPref), false);
// }
//
// public static boolean getSecondaryNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.secondaryEnabledPref), false);
// }
//
// public static boolean getMiBandIntegrationEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.miBandPref), false);
// }
//
// public static boolean getTutorialDisplayed(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.tutorialPref), false);
// }
//
// public static boolean getPopupEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.alertPopupPref), true);
// }
//
// public static void setTutorialDisplayed(Context context) {
// // Update stored value
// Singleton.getSharedPreferences(context).edit().putBoolean(context.getString(R.string.tutorialPref), true).commit();
// }
//
// public static void setCityLastAlertTime(String city, long timestamp, Context context) {
// // Update last alert timestamp for this city
// Singleton.getSharedPreferences(context).edit().putLong(city, timestamp).commit();
// }
//
// public static long getCityLastAlert(String city, Context context) {
// // Get last alert timestamp for this city
// return Singleton.getSharedPreferences(context).getLong(city, 0);
// }
//
// public static float getPrimaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.volumePref), 1.0f);
// }
//
// public static float getSecondaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.secondaryVolumePref), 1.0f);
// }
// }
// Path: app/src/main/java/com/red/alert/logic/feedback/sound/VolumeLogic.java
import android.content.Context;
import android.media.AudioManager;
import com.red.alert.config.Sound;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.logic.settings.AppPreferences;
package com.red.alert.logic.feedback.sound;
public class VolumeLogic {
public static void setStreamVolume(String alertType, Context context) {
// Get the audio manager
AudioManager audioManager = (AudioManager) context.getSystemService(context.AUDIO_SERVICE);
// Get max possible volume
int requestedVolume = VolumeLogic.getNotificationVolume(alertType, context);
// Set volume to desired level | audioManager.setStreamVolume(Sound.STREAM_TYPE, requestedVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE); |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/feedback/sound/VolumeLogic.java | // Path: app/src/main/java/com/red/alert/config/Sound.java
// public class Sound {
// public static final String SCHEME_URI_IDENTIFIER = "://";
// public static final String APP_SOUND_PREFIX = "com.red.alert://";
// // The AudioManager stream that sirens will be played on
// public static int STREAM_TYPE = AudioManager.STREAM_ALARM;
// }
//
// Path: app/src/main/java/com/red/alert/logic/alerts/AlertTypes.java
// public class AlertTypes {
// public static final String SYSTEM = "system";
// public static final String PRIMARY = "alert";
// public static final String SECONDARY = "secondary_alert";
//
// public static final String TEST = "test";
// public static final String TEST_SOUND = "test_sound";
// public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
// }
//
// Path: app/src/main/java/com/red/alert/logic/settings/AppPreferences.java
// public class AppPreferences {
// public static boolean getNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.enabledPref), true);
// }
//
// public static boolean getLocationAlertsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.locationAlertsPref), false);
// }
//
// public static boolean getSecondaryNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.secondaryEnabledPref), false);
// }
//
// public static boolean getMiBandIntegrationEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.miBandPref), false);
// }
//
// public static boolean getTutorialDisplayed(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.tutorialPref), false);
// }
//
// public static boolean getPopupEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.alertPopupPref), true);
// }
//
// public static void setTutorialDisplayed(Context context) {
// // Update stored value
// Singleton.getSharedPreferences(context).edit().putBoolean(context.getString(R.string.tutorialPref), true).commit();
// }
//
// public static void setCityLastAlertTime(String city, long timestamp, Context context) {
// // Update last alert timestamp for this city
// Singleton.getSharedPreferences(context).edit().putLong(city, timestamp).commit();
// }
//
// public static long getCityLastAlert(String city, Context context) {
// // Get last alert timestamp for this city
// return Singleton.getSharedPreferences(context).getLong(city, 0);
// }
//
// public static float getPrimaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.volumePref), 1.0f);
// }
//
// public static float getSecondaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.secondaryVolumePref), 1.0f);
// }
// }
| import android.content.Context;
import android.media.AudioManager;
import com.red.alert.config.Sound;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.logic.settings.AppPreferences; | package com.red.alert.logic.feedback.sound;
public class VolumeLogic {
public static void setStreamVolume(String alertType, Context context) {
// Get the audio manager
AudioManager audioManager = (AudioManager) context.getSystemService(context.AUDIO_SERVICE);
// Get max possible volume
int requestedVolume = VolumeLogic.getNotificationVolume(alertType, context);
// Set volume to desired level
audioManager.setStreamVolume(Sound.STREAM_TYPE, requestedVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
public static int getNotificationVolume(String alertType, Context context) {
// Get default volume multiplier | // Path: app/src/main/java/com/red/alert/config/Sound.java
// public class Sound {
// public static final String SCHEME_URI_IDENTIFIER = "://";
// public static final String APP_SOUND_PREFIX = "com.red.alert://";
// // The AudioManager stream that sirens will be played on
// public static int STREAM_TYPE = AudioManager.STREAM_ALARM;
// }
//
// Path: app/src/main/java/com/red/alert/logic/alerts/AlertTypes.java
// public class AlertTypes {
// public static final String SYSTEM = "system";
// public static final String PRIMARY = "alert";
// public static final String SECONDARY = "secondary_alert";
//
// public static final String TEST = "test";
// public static final String TEST_SOUND = "test_sound";
// public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
// }
//
// Path: app/src/main/java/com/red/alert/logic/settings/AppPreferences.java
// public class AppPreferences {
// public static boolean getNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.enabledPref), true);
// }
//
// public static boolean getLocationAlertsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.locationAlertsPref), false);
// }
//
// public static boolean getSecondaryNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.secondaryEnabledPref), false);
// }
//
// public static boolean getMiBandIntegrationEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.miBandPref), false);
// }
//
// public static boolean getTutorialDisplayed(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.tutorialPref), false);
// }
//
// public static boolean getPopupEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.alertPopupPref), true);
// }
//
// public static void setTutorialDisplayed(Context context) {
// // Update stored value
// Singleton.getSharedPreferences(context).edit().putBoolean(context.getString(R.string.tutorialPref), true).commit();
// }
//
// public static void setCityLastAlertTime(String city, long timestamp, Context context) {
// // Update last alert timestamp for this city
// Singleton.getSharedPreferences(context).edit().putLong(city, timestamp).commit();
// }
//
// public static long getCityLastAlert(String city, Context context) {
// // Get last alert timestamp for this city
// return Singleton.getSharedPreferences(context).getLong(city, 0);
// }
//
// public static float getPrimaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.volumePref), 1.0f);
// }
//
// public static float getSecondaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.secondaryVolumePref), 1.0f);
// }
// }
// Path: app/src/main/java/com/red/alert/logic/feedback/sound/VolumeLogic.java
import android.content.Context;
import android.media.AudioManager;
import com.red.alert.config.Sound;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.logic.settings.AppPreferences;
package com.red.alert.logic.feedback.sound;
public class VolumeLogic {
public static void setStreamVolume(String alertType, Context context) {
// Get the audio manager
AudioManager audioManager = (AudioManager) context.getSystemService(context.AUDIO_SERVICE);
// Get max possible volume
int requestedVolume = VolumeLogic.getNotificationVolume(alertType, context);
// Set volume to desired level
audioManager.setStreamVolume(Sound.STREAM_TYPE, requestedVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
public static int getNotificationVolume(String alertType, Context context) {
// Get default volume multiplier | float volumePercent = AppPreferences.getPrimaryAlertVolume(context, -1); |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/feedback/sound/VolumeLogic.java | // Path: app/src/main/java/com/red/alert/config/Sound.java
// public class Sound {
// public static final String SCHEME_URI_IDENTIFIER = "://";
// public static final String APP_SOUND_PREFIX = "com.red.alert://";
// // The AudioManager stream that sirens will be played on
// public static int STREAM_TYPE = AudioManager.STREAM_ALARM;
// }
//
// Path: app/src/main/java/com/red/alert/logic/alerts/AlertTypes.java
// public class AlertTypes {
// public static final String SYSTEM = "system";
// public static final String PRIMARY = "alert";
// public static final String SECONDARY = "secondary_alert";
//
// public static final String TEST = "test";
// public static final String TEST_SOUND = "test_sound";
// public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
// }
//
// Path: app/src/main/java/com/red/alert/logic/settings/AppPreferences.java
// public class AppPreferences {
// public static boolean getNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.enabledPref), true);
// }
//
// public static boolean getLocationAlertsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.locationAlertsPref), false);
// }
//
// public static boolean getSecondaryNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.secondaryEnabledPref), false);
// }
//
// public static boolean getMiBandIntegrationEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.miBandPref), false);
// }
//
// public static boolean getTutorialDisplayed(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.tutorialPref), false);
// }
//
// public static boolean getPopupEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.alertPopupPref), true);
// }
//
// public static void setTutorialDisplayed(Context context) {
// // Update stored value
// Singleton.getSharedPreferences(context).edit().putBoolean(context.getString(R.string.tutorialPref), true).commit();
// }
//
// public static void setCityLastAlertTime(String city, long timestamp, Context context) {
// // Update last alert timestamp for this city
// Singleton.getSharedPreferences(context).edit().putLong(city, timestamp).commit();
// }
//
// public static long getCityLastAlert(String city, Context context) {
// // Get last alert timestamp for this city
// return Singleton.getSharedPreferences(context).getLong(city, 0);
// }
//
// public static float getPrimaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.volumePref), 1.0f);
// }
//
// public static float getSecondaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.secondaryVolumePref), 1.0f);
// }
// }
| import android.content.Context;
import android.media.AudioManager;
import com.red.alert.config.Sound;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.logic.settings.AppPreferences; | package com.red.alert.logic.feedback.sound;
public class VolumeLogic {
public static void setStreamVolume(String alertType, Context context) {
// Get the audio manager
AudioManager audioManager = (AudioManager) context.getSystemService(context.AUDIO_SERVICE);
// Get max possible volume
int requestedVolume = VolumeLogic.getNotificationVolume(alertType, context);
// Set volume to desired level
audioManager.setStreamVolume(Sound.STREAM_TYPE, requestedVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
public static int getNotificationVolume(String alertType, Context context) {
// Get default volume multiplier
float volumePercent = AppPreferences.getPrimaryAlertVolume(context, -1);
// Secondary alert? | // Path: app/src/main/java/com/red/alert/config/Sound.java
// public class Sound {
// public static final String SCHEME_URI_IDENTIFIER = "://";
// public static final String APP_SOUND_PREFIX = "com.red.alert://";
// // The AudioManager stream that sirens will be played on
// public static int STREAM_TYPE = AudioManager.STREAM_ALARM;
// }
//
// Path: app/src/main/java/com/red/alert/logic/alerts/AlertTypes.java
// public class AlertTypes {
// public static final String SYSTEM = "system";
// public static final String PRIMARY = "alert";
// public static final String SECONDARY = "secondary_alert";
//
// public static final String TEST = "test";
// public static final String TEST_SOUND = "test_sound";
// public static final String TEST_SECONDARY_SOUND = "test_secondary_sound";
// }
//
// Path: app/src/main/java/com/red/alert/logic/settings/AppPreferences.java
// public class AppPreferences {
// public static boolean getNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.enabledPref), true);
// }
//
// public static boolean getLocationAlertsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.locationAlertsPref), false);
// }
//
// public static boolean getSecondaryNotificationsEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.secondaryEnabledPref), false);
// }
//
// public static boolean getMiBandIntegrationEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.miBandPref), false);
// }
//
// public static boolean getTutorialDisplayed(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.tutorialPref), false);
// }
//
// public static boolean getPopupEnabled(Context context) {
// // Get saved preference
// return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.alertPopupPref), true);
// }
//
// public static void setTutorialDisplayed(Context context) {
// // Update stored value
// Singleton.getSharedPreferences(context).edit().putBoolean(context.getString(R.string.tutorialPref), true).commit();
// }
//
// public static void setCityLastAlertTime(String city, long timestamp, Context context) {
// // Update last alert timestamp for this city
// Singleton.getSharedPreferences(context).edit().putLong(city, timestamp).commit();
// }
//
// public static long getCityLastAlert(String city, Context context) {
// // Get last alert timestamp for this city
// return Singleton.getSharedPreferences(context).getLong(city, 0);
// }
//
// public static float getPrimaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.volumePref), 1.0f);
// }
//
// public static float getSecondaryAlertVolume(Context context, float overrideValue) {
// // Override?
// if (overrideValue != -1) {
// return overrideValue;
// }
//
// // Get stored value
// return Singleton.getSharedPreferences(context).getFloat(context.getString(R.string.secondaryVolumePref), 1.0f);
// }
// }
// Path: app/src/main/java/com/red/alert/logic/feedback/sound/VolumeLogic.java
import android.content.Context;
import android.media.AudioManager;
import com.red.alert.config.Sound;
import com.red.alert.logic.alerts.AlertTypes;
import com.red.alert.logic.settings.AppPreferences;
package com.red.alert.logic.feedback.sound;
public class VolumeLogic {
public static void setStreamVolume(String alertType, Context context) {
// Get the audio manager
AudioManager audioManager = (AudioManager) context.getSystemService(context.AUDIO_SERVICE);
// Get max possible volume
int requestedVolume = VolumeLogic.getNotificationVolume(alertType, context);
// Set volume to desired level
audioManager.setStreamVolume(Sound.STREAM_TYPE, requestedVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
public static int getNotificationVolume(String alertType, Context context) {
// Get default volume multiplier
float volumePercent = AppPreferences.getPrimaryAlertVolume(context, -1);
// Secondary alert? | if (alertType.equals(AlertTypes.SECONDARY) || alertType.equals(AlertTypes.TEST_SECONDARY_SOUND)) { |
eladnava/redalert-android | app/src/main/java/com/betomaluje/miband/sqlite/ActivitySQLite.java | // Path: app/src/main/java/com/betomaluje/miband/DateUtils.java
// public class DateUtils {
//
// private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
//
// public static String convertString(Calendar cal) {
// return sdf.format(cal.getTime());
// }
//
// public static String convertString(long timeInMillis) {
// Calendar date = Calendar.getInstance();
// date.setTimeInMillis(timeInMillis);
// return convertString(date);
// }
//
// }
//
// Path: app/src/main/java/com/betomaluje/miband/models/ActivityData.java
// public class ActivityData {
//
// public static final float Y_VALUE_DEEP_SLEEP = 0.01f;
// public static final float Y_VALUE_LIGHT_SLEEP = 0.016f;
//
// public static final byte PROVIDER_MIBAND = 0;
//
// // public static final byte TYPE_CHARGING = 6;
// // public static final byte TYPE_NONWEAR = 3;
// // public static final byte TYPE_NREM = 5; // DEEP SLEEP
// // public static final byte TYPE_ONBED = 7;
// // public static final byte TYPE_REM = 4; // LIGHT SLEEP
// // public static final byte TYPE_RUNNING = 2;
// // public static final byte TYPE_SLIENT = 0;
// // public static final byte TYPE_USER = 100;
// // public static final byte TYPE_WALKING = 1;
//
// public static final byte TYPE_DEEP_SLEEP = 5;
// public static final byte TYPE_LIGHT_SLEEP = 4;
// public static final byte TYPE_ACTIVITY = -1;
// public static final byte TYPE_UNKNOWN = -1;
// // add more here
//
// private final int timestamp;
// private final byte provider;
// private final short intensity;
// private final byte steps;
// private final byte type;
//
// public ActivityData(int timestamp, byte provider, short intensity, byte steps, byte type) {
// this.timestamp = timestamp;
// this.provider = provider;
// this.intensity = intensity;
// this.steps = steps;
// this.type = type;
// }
//
// public int getTimestamp() {
// return timestamp;
// }
//
// public byte getProvider() {
// return provider;
// }
//
// public short getIntensity() {
// return intensity;
// }
//
// public byte getSteps() {
// return steps;
// }
//
// public byte getType() {
// return type;
// }
// }
//
// Path: app/src/main/java/com/betomaluje/miband/models/ActivityKind.java
// public class ActivityKind {
// public static final int TYPE_UNKNOWN = 0;
// public static final int TYPE_ACTIVITY = 1;
// public static final int TYPE_LIGHT_SLEEP = 2;
// public static final int TYPE_DEEP_SLEEP = 4;
// public static final int TYPE_SLEEP = TYPE_LIGHT_SLEEP | TYPE_DEEP_SLEEP;
// public static final int TYPE_ALL = TYPE_ACTIVITY | TYPE_SLEEP;
//
// public static byte[] mapToDBActivityTypes(int types) {
// byte[] result = new byte[3];
// int i = 0;
// if ((types & ActivityKind.TYPE_ACTIVITY) != 0) {
// result[i++] = ActivityData.TYPE_ACTIVITY;
// }
// if ((types & ActivityKind.TYPE_DEEP_SLEEP) != 0) {
// result[i++] = ActivityData.TYPE_DEEP_SLEEP;
// }
// if ((types & ActivityKind.TYPE_LIGHT_SLEEP) != 0) {
// result[i++] = ActivityData.TYPE_LIGHT_SLEEP;
// }
// return Arrays.copyOf(result, i);
// }
//
// }
| import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.betomaluje.miband.DateUtils;
import com.betomaluje.miband.models.ActivityData;
import com.betomaluje.miband.models.ActivityKind;
import java.util.ArrayList;
import java.util.Calendar; | package com.betomaluje.miband.sqlite;
/**
* Created by betomaluje on 7/9/15.
*/
public class ActivitySQLite {
private final String TAG = getClass().getSimpleName();
public static final String TABLE_NAME = "Activities";
private Context context;
private static ActivitySQLite instance;
public static ActivitySQLite getInstance(Context context) {
if (instance == null)
instance = new ActivitySQLite(context);
return instance;
}
public ActivitySQLite(Context context) {
this.context = context;
}
public boolean saveActivity(int timestamp, byte provider, short intensity, byte steps, byte type) {
MasterSQLiteHelper helperDB = new MasterSQLiteHelper(context);
SQLiteDatabase db = helperDB.getWritableDatabase();
//Log.e(TAG, "saving Activity " + timestamp);
ContentValues cv = new ContentValues();
cv.put("timestamp", timestamp);
cv.put("provider", provider);
cv.put("intensity", intensity);
cv.put("steps", steps);
cv.put("type", type);
if (db.insert(TABLE_NAME, null, cv) != -1) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp); | // Path: app/src/main/java/com/betomaluje/miband/DateUtils.java
// public class DateUtils {
//
// private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
//
// public static String convertString(Calendar cal) {
// return sdf.format(cal.getTime());
// }
//
// public static String convertString(long timeInMillis) {
// Calendar date = Calendar.getInstance();
// date.setTimeInMillis(timeInMillis);
// return convertString(date);
// }
//
// }
//
// Path: app/src/main/java/com/betomaluje/miband/models/ActivityData.java
// public class ActivityData {
//
// public static final float Y_VALUE_DEEP_SLEEP = 0.01f;
// public static final float Y_VALUE_LIGHT_SLEEP = 0.016f;
//
// public static final byte PROVIDER_MIBAND = 0;
//
// // public static final byte TYPE_CHARGING = 6;
// // public static final byte TYPE_NONWEAR = 3;
// // public static final byte TYPE_NREM = 5; // DEEP SLEEP
// // public static final byte TYPE_ONBED = 7;
// // public static final byte TYPE_REM = 4; // LIGHT SLEEP
// // public static final byte TYPE_RUNNING = 2;
// // public static final byte TYPE_SLIENT = 0;
// // public static final byte TYPE_USER = 100;
// // public static final byte TYPE_WALKING = 1;
//
// public static final byte TYPE_DEEP_SLEEP = 5;
// public static final byte TYPE_LIGHT_SLEEP = 4;
// public static final byte TYPE_ACTIVITY = -1;
// public static final byte TYPE_UNKNOWN = -1;
// // add more here
//
// private final int timestamp;
// private final byte provider;
// private final short intensity;
// private final byte steps;
// private final byte type;
//
// public ActivityData(int timestamp, byte provider, short intensity, byte steps, byte type) {
// this.timestamp = timestamp;
// this.provider = provider;
// this.intensity = intensity;
// this.steps = steps;
// this.type = type;
// }
//
// public int getTimestamp() {
// return timestamp;
// }
//
// public byte getProvider() {
// return provider;
// }
//
// public short getIntensity() {
// return intensity;
// }
//
// public byte getSteps() {
// return steps;
// }
//
// public byte getType() {
// return type;
// }
// }
//
// Path: app/src/main/java/com/betomaluje/miband/models/ActivityKind.java
// public class ActivityKind {
// public static final int TYPE_UNKNOWN = 0;
// public static final int TYPE_ACTIVITY = 1;
// public static final int TYPE_LIGHT_SLEEP = 2;
// public static final int TYPE_DEEP_SLEEP = 4;
// public static final int TYPE_SLEEP = TYPE_LIGHT_SLEEP | TYPE_DEEP_SLEEP;
// public static final int TYPE_ALL = TYPE_ACTIVITY | TYPE_SLEEP;
//
// public static byte[] mapToDBActivityTypes(int types) {
// byte[] result = new byte[3];
// int i = 0;
// if ((types & ActivityKind.TYPE_ACTIVITY) != 0) {
// result[i++] = ActivityData.TYPE_ACTIVITY;
// }
// if ((types & ActivityKind.TYPE_DEEP_SLEEP) != 0) {
// result[i++] = ActivityData.TYPE_DEEP_SLEEP;
// }
// if ((types & ActivityKind.TYPE_LIGHT_SLEEP) != 0) {
// result[i++] = ActivityData.TYPE_LIGHT_SLEEP;
// }
// return Arrays.copyOf(result, i);
// }
//
// }
// Path: app/src/main/java/com/betomaluje/miband/sqlite/ActivitySQLite.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.betomaluje.miband.DateUtils;
import com.betomaluje.miband.models.ActivityData;
import com.betomaluje.miband.models.ActivityKind;
import java.util.ArrayList;
import java.util.Calendar;
package com.betomaluje.miband.sqlite;
/**
* Created by betomaluje on 7/9/15.
*/
public class ActivitySQLite {
private final String TAG = getClass().getSimpleName();
public static final String TABLE_NAME = "Activities";
private Context context;
private static ActivitySQLite instance;
public static ActivitySQLite getInstance(Context context) {
if (instance == null)
instance = new ActivitySQLite(context);
return instance;
}
public ActivitySQLite(Context context) {
this.context = context;
}
public boolean saveActivity(int timestamp, byte provider, short intensity, byte steps, byte type) {
MasterSQLiteHelper helperDB = new MasterSQLiteHelper(context);
SQLiteDatabase db = helperDB.getWritableDatabase();
//Log.e(TAG, "saving Activity " + timestamp);
ContentValues cv = new ContentValues();
cv.put("timestamp", timestamp);
cv.put("provider", provider);
cv.put("intensity", intensity);
cv.put("steps", steps);
cv.put("type", type);
if (db.insert(TABLE_NAME, null, cv) != -1) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp); | Log.e(TAG, "Activity " + DateUtils.convertString(cal) + " insertada con éxito!"); |
eladnava/redalert-android | app/src/main/java/com/betomaluje/miband/sqlite/ActivitySQLite.java | // Path: app/src/main/java/com/betomaluje/miband/DateUtils.java
// public class DateUtils {
//
// private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
//
// public static String convertString(Calendar cal) {
// return sdf.format(cal.getTime());
// }
//
// public static String convertString(long timeInMillis) {
// Calendar date = Calendar.getInstance();
// date.setTimeInMillis(timeInMillis);
// return convertString(date);
// }
//
// }
//
// Path: app/src/main/java/com/betomaluje/miband/models/ActivityData.java
// public class ActivityData {
//
// public static final float Y_VALUE_DEEP_SLEEP = 0.01f;
// public static final float Y_VALUE_LIGHT_SLEEP = 0.016f;
//
// public static final byte PROVIDER_MIBAND = 0;
//
// // public static final byte TYPE_CHARGING = 6;
// // public static final byte TYPE_NONWEAR = 3;
// // public static final byte TYPE_NREM = 5; // DEEP SLEEP
// // public static final byte TYPE_ONBED = 7;
// // public static final byte TYPE_REM = 4; // LIGHT SLEEP
// // public static final byte TYPE_RUNNING = 2;
// // public static final byte TYPE_SLIENT = 0;
// // public static final byte TYPE_USER = 100;
// // public static final byte TYPE_WALKING = 1;
//
// public static final byte TYPE_DEEP_SLEEP = 5;
// public static final byte TYPE_LIGHT_SLEEP = 4;
// public static final byte TYPE_ACTIVITY = -1;
// public static final byte TYPE_UNKNOWN = -1;
// // add more here
//
// private final int timestamp;
// private final byte provider;
// private final short intensity;
// private final byte steps;
// private final byte type;
//
// public ActivityData(int timestamp, byte provider, short intensity, byte steps, byte type) {
// this.timestamp = timestamp;
// this.provider = provider;
// this.intensity = intensity;
// this.steps = steps;
// this.type = type;
// }
//
// public int getTimestamp() {
// return timestamp;
// }
//
// public byte getProvider() {
// return provider;
// }
//
// public short getIntensity() {
// return intensity;
// }
//
// public byte getSteps() {
// return steps;
// }
//
// public byte getType() {
// return type;
// }
// }
//
// Path: app/src/main/java/com/betomaluje/miband/models/ActivityKind.java
// public class ActivityKind {
// public static final int TYPE_UNKNOWN = 0;
// public static final int TYPE_ACTIVITY = 1;
// public static final int TYPE_LIGHT_SLEEP = 2;
// public static final int TYPE_DEEP_SLEEP = 4;
// public static final int TYPE_SLEEP = TYPE_LIGHT_SLEEP | TYPE_DEEP_SLEEP;
// public static final int TYPE_ALL = TYPE_ACTIVITY | TYPE_SLEEP;
//
// public static byte[] mapToDBActivityTypes(int types) {
// byte[] result = new byte[3];
// int i = 0;
// if ((types & ActivityKind.TYPE_ACTIVITY) != 0) {
// result[i++] = ActivityData.TYPE_ACTIVITY;
// }
// if ((types & ActivityKind.TYPE_DEEP_SLEEP) != 0) {
// result[i++] = ActivityData.TYPE_DEEP_SLEEP;
// }
// if ((types & ActivityKind.TYPE_LIGHT_SLEEP) != 0) {
// result[i++] = ActivityData.TYPE_LIGHT_SLEEP;
// }
// return Arrays.copyOf(result, i);
// }
//
// }
| import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.betomaluje.miband.DateUtils;
import com.betomaluje.miband.models.ActivityData;
import com.betomaluje.miband.models.ActivityKind;
import java.util.ArrayList;
import java.util.Calendar; |
public ActivitySQLite(Context context) {
this.context = context;
}
public boolean saveActivity(int timestamp, byte provider, short intensity, byte steps, byte type) {
MasterSQLiteHelper helperDB = new MasterSQLiteHelper(context);
SQLiteDatabase db = helperDB.getWritableDatabase();
//Log.e(TAG, "saving Activity " + timestamp);
ContentValues cv = new ContentValues();
cv.put("timestamp", timestamp);
cv.put("provider", provider);
cv.put("intensity", intensity);
cv.put("steps", steps);
cv.put("type", type);
if (db.insert(TABLE_NAME, null, cv) != -1) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
Log.e(TAG, "Activity " + DateUtils.convertString(cal) + " insertada con éxito!");
db.close();
return true;
} else {
db.close();
return false;
}
}
| // Path: app/src/main/java/com/betomaluje/miband/DateUtils.java
// public class DateUtils {
//
// private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
//
// public static String convertString(Calendar cal) {
// return sdf.format(cal.getTime());
// }
//
// public static String convertString(long timeInMillis) {
// Calendar date = Calendar.getInstance();
// date.setTimeInMillis(timeInMillis);
// return convertString(date);
// }
//
// }
//
// Path: app/src/main/java/com/betomaluje/miband/models/ActivityData.java
// public class ActivityData {
//
// public static final float Y_VALUE_DEEP_SLEEP = 0.01f;
// public static final float Y_VALUE_LIGHT_SLEEP = 0.016f;
//
// public static final byte PROVIDER_MIBAND = 0;
//
// // public static final byte TYPE_CHARGING = 6;
// // public static final byte TYPE_NONWEAR = 3;
// // public static final byte TYPE_NREM = 5; // DEEP SLEEP
// // public static final byte TYPE_ONBED = 7;
// // public static final byte TYPE_REM = 4; // LIGHT SLEEP
// // public static final byte TYPE_RUNNING = 2;
// // public static final byte TYPE_SLIENT = 0;
// // public static final byte TYPE_USER = 100;
// // public static final byte TYPE_WALKING = 1;
//
// public static final byte TYPE_DEEP_SLEEP = 5;
// public static final byte TYPE_LIGHT_SLEEP = 4;
// public static final byte TYPE_ACTIVITY = -1;
// public static final byte TYPE_UNKNOWN = -1;
// // add more here
//
// private final int timestamp;
// private final byte provider;
// private final short intensity;
// private final byte steps;
// private final byte type;
//
// public ActivityData(int timestamp, byte provider, short intensity, byte steps, byte type) {
// this.timestamp = timestamp;
// this.provider = provider;
// this.intensity = intensity;
// this.steps = steps;
// this.type = type;
// }
//
// public int getTimestamp() {
// return timestamp;
// }
//
// public byte getProvider() {
// return provider;
// }
//
// public short getIntensity() {
// return intensity;
// }
//
// public byte getSteps() {
// return steps;
// }
//
// public byte getType() {
// return type;
// }
// }
//
// Path: app/src/main/java/com/betomaluje/miband/models/ActivityKind.java
// public class ActivityKind {
// public static final int TYPE_UNKNOWN = 0;
// public static final int TYPE_ACTIVITY = 1;
// public static final int TYPE_LIGHT_SLEEP = 2;
// public static final int TYPE_DEEP_SLEEP = 4;
// public static final int TYPE_SLEEP = TYPE_LIGHT_SLEEP | TYPE_DEEP_SLEEP;
// public static final int TYPE_ALL = TYPE_ACTIVITY | TYPE_SLEEP;
//
// public static byte[] mapToDBActivityTypes(int types) {
// byte[] result = new byte[3];
// int i = 0;
// if ((types & ActivityKind.TYPE_ACTIVITY) != 0) {
// result[i++] = ActivityData.TYPE_ACTIVITY;
// }
// if ((types & ActivityKind.TYPE_DEEP_SLEEP) != 0) {
// result[i++] = ActivityData.TYPE_DEEP_SLEEP;
// }
// if ((types & ActivityKind.TYPE_LIGHT_SLEEP) != 0) {
// result[i++] = ActivityData.TYPE_LIGHT_SLEEP;
// }
// return Arrays.copyOf(result, i);
// }
//
// }
// Path: app/src/main/java/com/betomaluje/miband/sqlite/ActivitySQLite.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.betomaluje.miband.DateUtils;
import com.betomaluje.miband.models.ActivityData;
import com.betomaluje.miband.models.ActivityKind;
import java.util.ArrayList;
import java.util.Calendar;
public ActivitySQLite(Context context) {
this.context = context;
}
public boolean saveActivity(int timestamp, byte provider, short intensity, byte steps, byte type) {
MasterSQLiteHelper helperDB = new MasterSQLiteHelper(context);
SQLiteDatabase db = helperDB.getWritableDatabase();
//Log.e(TAG, "saving Activity " + timestamp);
ContentValues cv = new ContentValues();
cv.put("timestamp", timestamp);
cv.put("provider", provider);
cv.put("intensity", intensity);
cv.put("steps", steps);
cv.put("type", type);
if (db.insert(TABLE_NAME, null, cv) != -1) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
Log.e(TAG, "Activity " + DateUtils.convertString(cal) + " insertada con éxito!");
db.close();
return true;
} else {
db.close();
return false;
}
}
| public ArrayList<ActivityData> getSleepSamples(long timestamp_from, long timestamp_to) { |
eladnava/redalert-android | app/src/main/java/com/betomaluje/miband/sqlite/ActivitySQLite.java | // Path: app/src/main/java/com/betomaluje/miband/DateUtils.java
// public class DateUtils {
//
// private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
//
// public static String convertString(Calendar cal) {
// return sdf.format(cal.getTime());
// }
//
// public static String convertString(long timeInMillis) {
// Calendar date = Calendar.getInstance();
// date.setTimeInMillis(timeInMillis);
// return convertString(date);
// }
//
// }
//
// Path: app/src/main/java/com/betomaluje/miband/models/ActivityData.java
// public class ActivityData {
//
// public static final float Y_VALUE_DEEP_SLEEP = 0.01f;
// public static final float Y_VALUE_LIGHT_SLEEP = 0.016f;
//
// public static final byte PROVIDER_MIBAND = 0;
//
// // public static final byte TYPE_CHARGING = 6;
// // public static final byte TYPE_NONWEAR = 3;
// // public static final byte TYPE_NREM = 5; // DEEP SLEEP
// // public static final byte TYPE_ONBED = 7;
// // public static final byte TYPE_REM = 4; // LIGHT SLEEP
// // public static final byte TYPE_RUNNING = 2;
// // public static final byte TYPE_SLIENT = 0;
// // public static final byte TYPE_USER = 100;
// // public static final byte TYPE_WALKING = 1;
//
// public static final byte TYPE_DEEP_SLEEP = 5;
// public static final byte TYPE_LIGHT_SLEEP = 4;
// public static final byte TYPE_ACTIVITY = -1;
// public static final byte TYPE_UNKNOWN = -1;
// // add more here
//
// private final int timestamp;
// private final byte provider;
// private final short intensity;
// private final byte steps;
// private final byte type;
//
// public ActivityData(int timestamp, byte provider, short intensity, byte steps, byte type) {
// this.timestamp = timestamp;
// this.provider = provider;
// this.intensity = intensity;
// this.steps = steps;
// this.type = type;
// }
//
// public int getTimestamp() {
// return timestamp;
// }
//
// public byte getProvider() {
// return provider;
// }
//
// public short getIntensity() {
// return intensity;
// }
//
// public byte getSteps() {
// return steps;
// }
//
// public byte getType() {
// return type;
// }
// }
//
// Path: app/src/main/java/com/betomaluje/miband/models/ActivityKind.java
// public class ActivityKind {
// public static final int TYPE_UNKNOWN = 0;
// public static final int TYPE_ACTIVITY = 1;
// public static final int TYPE_LIGHT_SLEEP = 2;
// public static final int TYPE_DEEP_SLEEP = 4;
// public static final int TYPE_SLEEP = TYPE_LIGHT_SLEEP | TYPE_DEEP_SLEEP;
// public static final int TYPE_ALL = TYPE_ACTIVITY | TYPE_SLEEP;
//
// public static byte[] mapToDBActivityTypes(int types) {
// byte[] result = new byte[3];
// int i = 0;
// if ((types & ActivityKind.TYPE_ACTIVITY) != 0) {
// result[i++] = ActivityData.TYPE_ACTIVITY;
// }
// if ((types & ActivityKind.TYPE_DEEP_SLEEP) != 0) {
// result[i++] = ActivityData.TYPE_DEEP_SLEEP;
// }
// if ((types & ActivityKind.TYPE_LIGHT_SLEEP) != 0) {
// result[i++] = ActivityData.TYPE_LIGHT_SLEEP;
// }
// return Arrays.copyOf(result, i);
// }
//
// }
| import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.betomaluje.miband.DateUtils;
import com.betomaluje.miband.models.ActivityData;
import com.betomaluje.miband.models.ActivityKind;
import java.util.ArrayList;
import java.util.Calendar; | public ActivitySQLite(Context context) {
this.context = context;
}
public boolean saveActivity(int timestamp, byte provider, short intensity, byte steps, byte type) {
MasterSQLiteHelper helperDB = new MasterSQLiteHelper(context);
SQLiteDatabase db = helperDB.getWritableDatabase();
//Log.e(TAG, "saving Activity " + timestamp);
ContentValues cv = new ContentValues();
cv.put("timestamp", timestamp);
cv.put("provider", provider);
cv.put("intensity", intensity);
cv.put("steps", steps);
cv.put("type", type);
if (db.insert(TABLE_NAME, null, cv) != -1) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
Log.e(TAG, "Activity " + DateUtils.convertString(cal) + " insertada con éxito!");
db.close();
return true;
} else {
db.close();
return false;
}
}
public ArrayList<ActivityData> getSleepSamples(long timestamp_from, long timestamp_to) { | // Path: app/src/main/java/com/betomaluje/miband/DateUtils.java
// public class DateUtils {
//
// private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
//
// public static String convertString(Calendar cal) {
// return sdf.format(cal.getTime());
// }
//
// public static String convertString(long timeInMillis) {
// Calendar date = Calendar.getInstance();
// date.setTimeInMillis(timeInMillis);
// return convertString(date);
// }
//
// }
//
// Path: app/src/main/java/com/betomaluje/miband/models/ActivityData.java
// public class ActivityData {
//
// public static final float Y_VALUE_DEEP_SLEEP = 0.01f;
// public static final float Y_VALUE_LIGHT_SLEEP = 0.016f;
//
// public static final byte PROVIDER_MIBAND = 0;
//
// // public static final byte TYPE_CHARGING = 6;
// // public static final byte TYPE_NONWEAR = 3;
// // public static final byte TYPE_NREM = 5; // DEEP SLEEP
// // public static final byte TYPE_ONBED = 7;
// // public static final byte TYPE_REM = 4; // LIGHT SLEEP
// // public static final byte TYPE_RUNNING = 2;
// // public static final byte TYPE_SLIENT = 0;
// // public static final byte TYPE_USER = 100;
// // public static final byte TYPE_WALKING = 1;
//
// public static final byte TYPE_DEEP_SLEEP = 5;
// public static final byte TYPE_LIGHT_SLEEP = 4;
// public static final byte TYPE_ACTIVITY = -1;
// public static final byte TYPE_UNKNOWN = -1;
// // add more here
//
// private final int timestamp;
// private final byte provider;
// private final short intensity;
// private final byte steps;
// private final byte type;
//
// public ActivityData(int timestamp, byte provider, short intensity, byte steps, byte type) {
// this.timestamp = timestamp;
// this.provider = provider;
// this.intensity = intensity;
// this.steps = steps;
// this.type = type;
// }
//
// public int getTimestamp() {
// return timestamp;
// }
//
// public byte getProvider() {
// return provider;
// }
//
// public short getIntensity() {
// return intensity;
// }
//
// public byte getSteps() {
// return steps;
// }
//
// public byte getType() {
// return type;
// }
// }
//
// Path: app/src/main/java/com/betomaluje/miband/models/ActivityKind.java
// public class ActivityKind {
// public static final int TYPE_UNKNOWN = 0;
// public static final int TYPE_ACTIVITY = 1;
// public static final int TYPE_LIGHT_SLEEP = 2;
// public static final int TYPE_DEEP_SLEEP = 4;
// public static final int TYPE_SLEEP = TYPE_LIGHT_SLEEP | TYPE_DEEP_SLEEP;
// public static final int TYPE_ALL = TYPE_ACTIVITY | TYPE_SLEEP;
//
// public static byte[] mapToDBActivityTypes(int types) {
// byte[] result = new byte[3];
// int i = 0;
// if ((types & ActivityKind.TYPE_ACTIVITY) != 0) {
// result[i++] = ActivityData.TYPE_ACTIVITY;
// }
// if ((types & ActivityKind.TYPE_DEEP_SLEEP) != 0) {
// result[i++] = ActivityData.TYPE_DEEP_SLEEP;
// }
// if ((types & ActivityKind.TYPE_LIGHT_SLEEP) != 0) {
// result[i++] = ActivityData.TYPE_LIGHT_SLEEP;
// }
// return Arrays.copyOf(result, i);
// }
//
// }
// Path: app/src/main/java/com/betomaluje/miband/sqlite/ActivitySQLite.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.betomaluje.miband.DateUtils;
import com.betomaluje.miband.models.ActivityData;
import com.betomaluje.miband.models.ActivityKind;
import java.util.ArrayList;
import java.util.Calendar;
public ActivitySQLite(Context context) {
this.context = context;
}
public boolean saveActivity(int timestamp, byte provider, short intensity, byte steps, byte type) {
MasterSQLiteHelper helperDB = new MasterSQLiteHelper(context);
SQLiteDatabase db = helperDB.getWritableDatabase();
//Log.e(TAG, "saving Activity " + timestamp);
ContentValues cv = new ContentValues();
cv.put("timestamp", timestamp);
cv.put("provider", provider);
cv.put("intensity", intensity);
cv.put("steps", steps);
cv.put("type", type);
if (db.insert(TABLE_NAME, null, cv) != -1) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
Log.e(TAG, "Activity " + DateUtils.convertString(cal) + " insertada con éxito!");
db.close();
return true;
} else {
db.close();
return false;
}
}
public ArrayList<ActivityData> getSleepSamples(long timestamp_from, long timestamp_to) { | return getActivitiesSample(timestamp_from, timestamp_to, ActivityKind.TYPE_SLEEP); |
eladnava/redalert-android | app/src/main/java/com/red/alert/utils/localization/Localization.java | // Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/formatting/StringUtils.java
// public class StringUtils {
// public static boolean stringIsNullOrEmpty(String inputString) {
// // String is null? return true
// if (inputString == null) {
// return true;
// }
//
// // String is empty? true
// if (inputString.trim().equals("")) {
// return true;
// }
//
// // String is not empty
// return false;
// }
//
// public static String implode(String separator, List<String> data) {
// // No data?
// if (data.size() == 0) {
// return "";
// }
//
// // Create temp StringBuilder
// StringBuilder builder = new StringBuilder();
//
// // Loop over list except last item
// for (int i = 0; i < data.size() - 1; i++) {
// // Append current item
// builder.append(data.get(i));
//
// // Append separator
// builder.append(separator);
// }
//
// // Add last item without separator
// builder.append(data.get(data.size() - 1));
//
// // Return string
// return builder.toString();
// }
//
// public static String regexMatch(String source, String compilePattern) {
// // Compile regex
// Pattern compiledPattern = Pattern.compile(compilePattern);
//
// // Match against source input
// Matcher matcher = compiledPattern.matcher(source);
//
// // Prepare match object
// String match = "";
//
// // Did we find anything?
// if (matcher.find()) {
// // Get first group
// match = matcher.group(1);
// }
//
// // Return match
// return match;
// }
// }
| import android.content.Context;
import android.content.res.Configuration;
import com.red.alert.R;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.formatting.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale; | package com.red.alert.utils.localization;
public class Localization {
public static boolean isEnglishLocale(Context context) {
// Override locale, if chosen
overridePhoneLocale(context);
// Get language code
String languageCode = context.getResources().getConfiguration().locale.getLanguage();
// English locale codes list
List<String> englishLocales = new ArrayList<>();
// Locale codes that are considered "English"
englishLocales.add(context.getString(R.string.englishCode));
englishLocales.add(context.getString(R.string.italianCode));
// Traverse valid locale codes
for (String code : englishLocales) {
// Check for string equality
if (languageCode.equals(code)) {
return true;
}
}
// Not an English locale
return false;
}
public static boolean isHebrewLocale(Context context) {
// Override locale, if chosen
overridePhoneLocale(context);
// Get language code
String languageCode = context.getResources().getConfiguration().locale.getLanguage();
// Detect using locale code
return languageCode.equals(context.getString(R.string.hebrewCode)) || languageCode.equals(context.getString(R.string.hebrewCode2));
}
public static void overridePhoneLocale(Context context) {
// Create new configuration
Configuration configuration = context.getResources().getConfiguration();
// Get new locale code | // Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/formatting/StringUtils.java
// public class StringUtils {
// public static boolean stringIsNullOrEmpty(String inputString) {
// // String is null? return true
// if (inputString == null) {
// return true;
// }
//
// // String is empty? true
// if (inputString.trim().equals("")) {
// return true;
// }
//
// // String is not empty
// return false;
// }
//
// public static String implode(String separator, List<String> data) {
// // No data?
// if (data.size() == 0) {
// return "";
// }
//
// // Create temp StringBuilder
// StringBuilder builder = new StringBuilder();
//
// // Loop over list except last item
// for (int i = 0; i < data.size() - 1; i++) {
// // Append current item
// builder.append(data.get(i));
//
// // Append separator
// builder.append(separator);
// }
//
// // Add last item without separator
// builder.append(data.get(data.size() - 1));
//
// // Return string
// return builder.toString();
// }
//
// public static String regexMatch(String source, String compilePattern) {
// // Compile regex
// Pattern compiledPattern = Pattern.compile(compilePattern);
//
// // Match against source input
// Matcher matcher = compiledPattern.matcher(source);
//
// // Prepare match object
// String match = "";
//
// // Did we find anything?
// if (matcher.find()) {
// // Get first group
// match = matcher.group(1);
// }
//
// // Return match
// return match;
// }
// }
// Path: app/src/main/java/com/red/alert/utils/localization/Localization.java
import android.content.Context;
import android.content.res.Configuration;
import com.red.alert.R;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.formatting.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
package com.red.alert.utils.localization;
public class Localization {
public static boolean isEnglishLocale(Context context) {
// Override locale, if chosen
overridePhoneLocale(context);
// Get language code
String languageCode = context.getResources().getConfiguration().locale.getLanguage();
// English locale codes list
List<String> englishLocales = new ArrayList<>();
// Locale codes that are considered "English"
englishLocales.add(context.getString(R.string.englishCode));
englishLocales.add(context.getString(R.string.italianCode));
// Traverse valid locale codes
for (String code : englishLocales) {
// Check for string equality
if (languageCode.equals(code)) {
return true;
}
}
// Not an English locale
return false;
}
public static boolean isHebrewLocale(Context context) {
// Override locale, if chosen
overridePhoneLocale(context);
// Get language code
String languageCode = context.getResources().getConfiguration().locale.getLanguage();
// Detect using locale code
return languageCode.equals(context.getString(R.string.hebrewCode)) || languageCode.equals(context.getString(R.string.hebrewCode2));
}
public static void overridePhoneLocale(Context context) {
// Create new configuration
Configuration configuration = context.getResources().getConfiguration();
// Get new locale code | String overrideLocale = Singleton.getSharedPreferences(context).getString(context.getString(R.string.langPref), ""); |
eladnava/redalert-android | app/src/main/java/com/red/alert/utils/localization/Localization.java | // Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/formatting/StringUtils.java
// public class StringUtils {
// public static boolean stringIsNullOrEmpty(String inputString) {
// // String is null? return true
// if (inputString == null) {
// return true;
// }
//
// // String is empty? true
// if (inputString.trim().equals("")) {
// return true;
// }
//
// // String is not empty
// return false;
// }
//
// public static String implode(String separator, List<String> data) {
// // No data?
// if (data.size() == 0) {
// return "";
// }
//
// // Create temp StringBuilder
// StringBuilder builder = new StringBuilder();
//
// // Loop over list except last item
// for (int i = 0; i < data.size() - 1; i++) {
// // Append current item
// builder.append(data.get(i));
//
// // Append separator
// builder.append(separator);
// }
//
// // Add last item without separator
// builder.append(data.get(data.size() - 1));
//
// // Return string
// return builder.toString();
// }
//
// public static String regexMatch(String source, String compilePattern) {
// // Compile regex
// Pattern compiledPattern = Pattern.compile(compilePattern);
//
// // Match against source input
// Matcher matcher = compiledPattern.matcher(source);
//
// // Prepare match object
// String match = "";
//
// // Did we find anything?
// if (matcher.find()) {
// // Get first group
// match = matcher.group(1);
// }
//
// // Return match
// return match;
// }
// }
| import android.content.Context;
import android.content.res.Configuration;
import com.red.alert.R;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.formatting.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale; | package com.red.alert.utils.localization;
public class Localization {
public static boolean isEnglishLocale(Context context) {
// Override locale, if chosen
overridePhoneLocale(context);
// Get language code
String languageCode = context.getResources().getConfiguration().locale.getLanguage();
// English locale codes list
List<String> englishLocales = new ArrayList<>();
// Locale codes that are considered "English"
englishLocales.add(context.getString(R.string.englishCode));
englishLocales.add(context.getString(R.string.italianCode));
// Traverse valid locale codes
for (String code : englishLocales) {
// Check for string equality
if (languageCode.equals(code)) {
return true;
}
}
// Not an English locale
return false;
}
public static boolean isHebrewLocale(Context context) {
// Override locale, if chosen
overridePhoneLocale(context);
// Get language code
String languageCode = context.getResources().getConfiguration().locale.getLanguage();
// Detect using locale code
return languageCode.equals(context.getString(R.string.hebrewCode)) || languageCode.equals(context.getString(R.string.hebrewCode2));
}
public static void overridePhoneLocale(Context context) {
// Create new configuration
Configuration configuration = context.getResources().getConfiguration();
// Get new locale code
String overrideLocale = Singleton.getSharedPreferences(context).getString(context.getString(R.string.langPref), "");
// Chosen a new locale? | // Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
//
// Path: app/src/main/java/com/red/alert/utils/formatting/StringUtils.java
// public class StringUtils {
// public static boolean stringIsNullOrEmpty(String inputString) {
// // String is null? return true
// if (inputString == null) {
// return true;
// }
//
// // String is empty? true
// if (inputString.trim().equals("")) {
// return true;
// }
//
// // String is not empty
// return false;
// }
//
// public static String implode(String separator, List<String> data) {
// // No data?
// if (data.size() == 0) {
// return "";
// }
//
// // Create temp StringBuilder
// StringBuilder builder = new StringBuilder();
//
// // Loop over list except last item
// for (int i = 0; i < data.size() - 1; i++) {
// // Append current item
// builder.append(data.get(i));
//
// // Append separator
// builder.append(separator);
// }
//
// // Add last item without separator
// builder.append(data.get(data.size() - 1));
//
// // Return string
// return builder.toString();
// }
//
// public static String regexMatch(String source, String compilePattern) {
// // Compile regex
// Pattern compiledPattern = Pattern.compile(compilePattern);
//
// // Match against source input
// Matcher matcher = compiledPattern.matcher(source);
//
// // Prepare match object
// String match = "";
//
// // Did we find anything?
// if (matcher.find()) {
// // Get first group
// match = matcher.group(1);
// }
//
// // Return match
// return match;
// }
// }
// Path: app/src/main/java/com/red/alert/utils/localization/Localization.java
import android.content.Context;
import android.content.res.Configuration;
import com.red.alert.R;
import com.red.alert.utils.caching.Singleton;
import com.red.alert.utils.formatting.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
package com.red.alert.utils.localization;
public class Localization {
public static boolean isEnglishLocale(Context context) {
// Override locale, if chosen
overridePhoneLocale(context);
// Get language code
String languageCode = context.getResources().getConfiguration().locale.getLanguage();
// English locale codes list
List<String> englishLocales = new ArrayList<>();
// Locale codes that are considered "English"
englishLocales.add(context.getString(R.string.englishCode));
englishLocales.add(context.getString(R.string.italianCode));
// Traverse valid locale codes
for (String code : englishLocales) {
// Check for string equality
if (languageCode.equals(code)) {
return true;
}
}
// Not an English locale
return false;
}
public static boolean isHebrewLocale(Context context) {
// Override locale, if chosen
overridePhoneLocale(context);
// Get language code
String languageCode = context.getResources().getConfiguration().locale.getLanguage();
// Detect using locale code
return languageCode.equals(context.getString(R.string.hebrewCode)) || languageCode.equals(context.getString(R.string.hebrewCode2));
}
public static void overridePhoneLocale(Context context) {
// Create new configuration
Configuration configuration = context.getResources().getConfiguration();
// Get new locale code
String overrideLocale = Singleton.getSharedPreferences(context).getString(context.getString(R.string.langPref), "");
// Chosen a new locale? | if (!StringUtils.stringIsNullOrEmpty(overrideLocale)) { |
eladnava/redalert-android | app/src/main/java/com/red/alert/utils/feedback/Vibration.java | // Path: app/src/main/java/com/red/alert/logic/feedback/VibrationLogic.java
// public class VibrationLogic {
// public static boolean shouldVibrate(String alertType, Context context) {
// // Testing sounds?
// if (alertType.equals(AlertTypes.TEST_SOUND) || alertType.equals(AlertTypes.TEST_SECONDARY_SOUND)) {
// return false;
// }
//
// // Get the audio manager
// AudioManager audioManager = (AudioManager) context.getSystemService(context.AUDIO_SERVICE);
//
// // Phone is on silent?
// if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
// // Can't override silent mode?
// if (!SoundLogic.shouldOverrideSilentMode(alertType, context)) {
// return false;
// }
// }
//
// // All good
// return true;
// }
//
// public static boolean isVibrationEnabled(String alertType, Context context) {
// // Get enabled / disabled setting
// boolean isVibrationEnabled = Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.vibratePref), true);
//
// // Secondary alert?
// if (alertType.equals(AlertTypes.SECONDARY)) {
// isVibrationEnabled = Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.secondaryVibratePref), true);
// }
//
// // Return value
// return isVibrationEnabled;
// }
// }
| import android.content.Context;
import android.os.Vibrator;
import com.red.alert.logic.feedback.VibrationLogic; | package com.red.alert.utils.feedback;
public class Vibration {
public static void stopVibration(Context context) {
// Get vibration service
Vibrator vibratorService = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
// Cancel any current vibrations
vibratorService.cancel();
}
public static void issueVibration(String alertType, Context context) {
// Enable vibration? | // Path: app/src/main/java/com/red/alert/logic/feedback/VibrationLogic.java
// public class VibrationLogic {
// public static boolean shouldVibrate(String alertType, Context context) {
// // Testing sounds?
// if (alertType.equals(AlertTypes.TEST_SOUND) || alertType.equals(AlertTypes.TEST_SECONDARY_SOUND)) {
// return false;
// }
//
// // Get the audio manager
// AudioManager audioManager = (AudioManager) context.getSystemService(context.AUDIO_SERVICE);
//
// // Phone is on silent?
// if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
// // Can't override silent mode?
// if (!SoundLogic.shouldOverrideSilentMode(alertType, context)) {
// return false;
// }
// }
//
// // All good
// return true;
// }
//
// public static boolean isVibrationEnabled(String alertType, Context context) {
// // Get enabled / disabled setting
// boolean isVibrationEnabled = Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.vibratePref), true);
//
// // Secondary alert?
// if (alertType.equals(AlertTypes.SECONDARY)) {
// isVibrationEnabled = Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.secondaryVibratePref), true);
// }
//
// // Return value
// return isVibrationEnabled;
// }
// }
// Path: app/src/main/java/com/red/alert/utils/feedback/Vibration.java
import android.content.Context;
import android.os.Vibrator;
import com.red.alert.logic.feedback.VibrationLogic;
package com.red.alert.utils.feedback;
public class Vibration {
public static void stopVibration(Context context) {
// Get vibration service
Vibrator vibratorService = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
// Cancel any current vibrations
vibratorService.cancel();
}
public static void issueVibration(String alertType, Context context) {
// Enable vibration? | if (!VibrationLogic.isVibrationEnabled(alertType, context)) { |
eladnava/redalert-android | app/src/main/java/com/red/alert/logic/settings/AppPreferences.java | // Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
| import android.content.Context;
import com.red.alert.R;
import com.red.alert.utils.caching.Singleton; | package com.red.alert.logic.settings;
public class AppPreferences {
public static boolean getNotificationsEnabled(Context context) {
// Get saved preference | // Path: app/src/main/java/com/red/alert/utils/caching/Singleton.java
// public class Singleton {
// static ObjectMapper mMapper;
// static SharedPreferences mSettings;
//
// public static SharedPreferences getSharedPreferences(Context context) {
// // First time?
// if (mSettings == null) {
// // Open shared preferences
// mSettings = PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// // Return cached object
// return mSettings;
// }
//
// public static ObjectMapper getJackson() {
// // First time?
// if (mMapper == null) {
// // Get Jackson instance
// mMapper = new ObjectMapper();
//
// // Ignore unknown properties
// mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// }
//
// // Return cached object
// return mMapper;
// }
// }
// Path: app/src/main/java/com/red/alert/logic/settings/AppPreferences.java
import android.content.Context;
import com.red.alert.R;
import com.red.alert.utils.caching.Singleton;
package com.red.alert.logic.settings;
public class AppPreferences {
public static boolean getNotificationsEnabled(Context context) {
// Get saved preference | return Singleton.getSharedPreferences(context).getBoolean(context.getString(R.string.enabledPref), true); |
javaBin/AndroiditoJZ12 | android/src/main/java/com/google/android/apps/iosched/sync/ScheduleUpdaterService.java | // Path: android/src/main/java/com/google/android/apps/iosched/io/HandlerException.java
// public class HandlerException extends IOException {
//
// public HandlerException() {
// super();
// }
//
// public HandlerException(String message) {
// super(message);
// }
//
// public HandlerException(String message, Throwable cause) {
// super(message);
// initCause(cause);
// }
//
// @Override
// public String toString() {
// if (getCause() != null) {
// return getLocalizedMessage() + ": " + getCause();
// } else {
// return getLocalizedMessage();
// }
// }
//
// public static class UnauthorizedException extends HandlerException {
// public UnauthorizedException() {
// }
//
// public UnauthorizedException(String message) {
// super(message);
// }
//
// public UnauthorizedException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// public static class NoDevsiteProfileException extends HandlerException {
// public NoDevsiteProfileException() {
// }
//
// public NoDevsiteProfileException(String message) {
// super(message);
// }
//
// public NoDevsiteProfileException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGI(final String tag, String message) {
// Log.i(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGW(final String tag, String message) {
// Log.w(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
| import java.util.LinkedList;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import com.google.android.apps.iosched.io.HandlerException;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator; | synchronized (mScheduleUpdates) {
mScheduleUpdates.add(intent);
}
return START_REDELIVER_INTENT;
}
@Override
public void onDestroy() {
mServiceLooper.quit();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void processPendingScheduleUpdates() {
try {
// Operate on a local copy of the schedule update list so as not to block
// the main thread adding to this list
List<Intent> scheduleUpdates = new ArrayList<Intent>();
synchronized (mScheduleUpdates) {
scheduleUpdates.addAll(mScheduleUpdates);
mScheduleUpdates.clear();
}
SyncHelper syncHelper = new SyncHelper(this);
for (Intent updateIntent : scheduleUpdates) {
String sessionId = updateIntent.getStringExtra(EXTRA_SESSION_ID);
boolean inSchedule = updateIntent.getBooleanExtra(EXTRA_IN_SCHEDULE, false); | // Path: android/src/main/java/com/google/android/apps/iosched/io/HandlerException.java
// public class HandlerException extends IOException {
//
// public HandlerException() {
// super();
// }
//
// public HandlerException(String message) {
// super(message);
// }
//
// public HandlerException(String message, Throwable cause) {
// super(message);
// initCause(cause);
// }
//
// @Override
// public String toString() {
// if (getCause() != null) {
// return getLocalizedMessage() + ": " + getCause();
// } else {
// return getLocalizedMessage();
// }
// }
//
// public static class UnauthorizedException extends HandlerException {
// public UnauthorizedException() {
// }
//
// public UnauthorizedException(String message) {
// super(message);
// }
//
// public UnauthorizedException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// public static class NoDevsiteProfileException extends HandlerException {
// public NoDevsiteProfileException() {
// }
//
// public NoDevsiteProfileException(String message) {
// super(message);
// }
//
// public NoDevsiteProfileException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGI(final String tag, String message) {
// Log.i(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGW(final String tag, String message) {
// Log.w(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
// Path: android/src/main/java/com/google/android/apps/iosched/sync/ScheduleUpdaterService.java
import java.util.LinkedList;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import com.google.android.apps.iosched.io.HandlerException;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
synchronized (mScheduleUpdates) {
mScheduleUpdates.add(intent);
}
return START_REDELIVER_INTENT;
}
@Override
public void onDestroy() {
mServiceLooper.quit();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void processPendingScheduleUpdates() {
try {
// Operate on a local copy of the schedule update list so as not to block
// the main thread adding to this list
List<Intent> scheduleUpdates = new ArrayList<Intent>();
synchronized (mScheduleUpdates) {
scheduleUpdates.addAll(mScheduleUpdates);
mScheduleUpdates.clear();
}
SyncHelper syncHelper = new SyncHelper(this);
for (Intent updateIntent : scheduleUpdates) {
String sessionId = updateIntent.getStringExtra(EXTRA_SESSION_ID);
boolean inSchedule = updateIntent.getBooleanExtra(EXTRA_IN_SCHEDULE, false); | LOGI(TAG, "addOrRemoveSessionFromSchedule:" |
javaBin/AndroiditoJZ12 | android/src/main/java/com/google/android/apps/iosched/sync/ScheduleUpdaterService.java | // Path: android/src/main/java/com/google/android/apps/iosched/io/HandlerException.java
// public class HandlerException extends IOException {
//
// public HandlerException() {
// super();
// }
//
// public HandlerException(String message) {
// super(message);
// }
//
// public HandlerException(String message, Throwable cause) {
// super(message);
// initCause(cause);
// }
//
// @Override
// public String toString() {
// if (getCause() != null) {
// return getLocalizedMessage() + ": " + getCause();
// } else {
// return getLocalizedMessage();
// }
// }
//
// public static class UnauthorizedException extends HandlerException {
// public UnauthorizedException() {
// }
//
// public UnauthorizedException(String message) {
// super(message);
// }
//
// public UnauthorizedException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// public static class NoDevsiteProfileException extends HandlerException {
// public NoDevsiteProfileException() {
// }
//
// public NoDevsiteProfileException(String message) {
// super(message);
// }
//
// public NoDevsiteProfileException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGI(final String tag, String message) {
// Log.i(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGW(final String tag, String message) {
// Log.w(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
| import java.util.LinkedList;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import com.google.android.apps.iosched.io.HandlerException;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator; |
@Override
public void onDestroy() {
mServiceLooper.quit();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void processPendingScheduleUpdates() {
try {
// Operate on a local copy of the schedule update list so as not to block
// the main thread adding to this list
List<Intent> scheduleUpdates = new ArrayList<Intent>();
synchronized (mScheduleUpdates) {
scheduleUpdates.addAll(mScheduleUpdates);
mScheduleUpdates.clear();
}
SyncHelper syncHelper = new SyncHelper(this);
for (Intent updateIntent : scheduleUpdates) {
String sessionId = updateIntent.getStringExtra(EXTRA_SESSION_ID);
boolean inSchedule = updateIntent.getBooleanExtra(EXTRA_IN_SCHEDULE, false);
LOGI(TAG, "addOrRemoveSessionFromSchedule:"
+ " sessionId=" + sessionId
+ " inSchedule=" + inSchedule);
syncHelper.addOrRemoveSessionFromSchedule(this, sessionId, inSchedule);
} | // Path: android/src/main/java/com/google/android/apps/iosched/io/HandlerException.java
// public class HandlerException extends IOException {
//
// public HandlerException() {
// super();
// }
//
// public HandlerException(String message) {
// super(message);
// }
//
// public HandlerException(String message, Throwable cause) {
// super(message);
// initCause(cause);
// }
//
// @Override
// public String toString() {
// if (getCause() != null) {
// return getLocalizedMessage() + ": " + getCause();
// } else {
// return getLocalizedMessage();
// }
// }
//
// public static class UnauthorizedException extends HandlerException {
// public UnauthorizedException() {
// }
//
// public UnauthorizedException(String message) {
// super(message);
// }
//
// public UnauthorizedException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// public static class NoDevsiteProfileException extends HandlerException {
// public NoDevsiteProfileException() {
// }
//
// public NoDevsiteProfileException(String message) {
// super(message);
// }
//
// public NoDevsiteProfileException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGI(final String tag, String message) {
// Log.i(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGW(final String tag, String message) {
// Log.w(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
// Path: android/src/main/java/com/google/android/apps/iosched/sync/ScheduleUpdaterService.java
import java.util.LinkedList;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import com.google.android.apps.iosched.io.HandlerException;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
@Override
public void onDestroy() {
mServiceLooper.quit();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void processPendingScheduleUpdates() {
try {
// Operate on a local copy of the schedule update list so as not to block
// the main thread adding to this list
List<Intent> scheduleUpdates = new ArrayList<Intent>();
synchronized (mScheduleUpdates) {
scheduleUpdates.addAll(mScheduleUpdates);
mScheduleUpdates.clear();
}
SyncHelper syncHelper = new SyncHelper(this);
for (Intent updateIntent : scheduleUpdates) {
String sessionId = updateIntent.getStringExtra(EXTRA_SESSION_ID);
boolean inSchedule = updateIntent.getBooleanExtra(EXTRA_IN_SCHEDULE, false);
LOGI(TAG, "addOrRemoveSessionFromSchedule:"
+ " sessionId=" + sessionId
+ " inSchedule=" + inSchedule);
syncHelper.addOrRemoveSessionFromSchedule(this, sessionId, inSchedule);
} | } catch (HandlerException.NoDevsiteProfileException e) { |
javaBin/AndroiditoJZ12 | android/src/main/java/com/google/android/apps/iosched/sync/ScheduleUpdaterService.java | // Path: android/src/main/java/com/google/android/apps/iosched/io/HandlerException.java
// public class HandlerException extends IOException {
//
// public HandlerException() {
// super();
// }
//
// public HandlerException(String message) {
// super(message);
// }
//
// public HandlerException(String message, Throwable cause) {
// super(message);
// initCause(cause);
// }
//
// @Override
// public String toString() {
// if (getCause() != null) {
// return getLocalizedMessage() + ": " + getCause();
// } else {
// return getLocalizedMessage();
// }
// }
//
// public static class UnauthorizedException extends HandlerException {
// public UnauthorizedException() {
// }
//
// public UnauthorizedException(String message) {
// super(message);
// }
//
// public UnauthorizedException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// public static class NoDevsiteProfileException extends HandlerException {
// public NoDevsiteProfileException() {
// }
//
// public NoDevsiteProfileException(String message) {
// super(message);
// }
//
// public NoDevsiteProfileException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGI(final String tag, String message) {
// Log.i(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGW(final String tag, String message) {
// Log.w(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
| import java.util.LinkedList;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import com.google.android.apps.iosched.io.HandlerException;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator; | mServiceLooper.quit();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void processPendingScheduleUpdates() {
try {
// Operate on a local copy of the schedule update list so as not to block
// the main thread adding to this list
List<Intent> scheduleUpdates = new ArrayList<Intent>();
synchronized (mScheduleUpdates) {
scheduleUpdates.addAll(mScheduleUpdates);
mScheduleUpdates.clear();
}
SyncHelper syncHelper = new SyncHelper(this);
for (Intent updateIntent : scheduleUpdates) {
String sessionId = updateIntent.getStringExtra(EXTRA_SESSION_ID);
boolean inSchedule = updateIntent.getBooleanExtra(EXTRA_IN_SCHEDULE, false);
LOGI(TAG, "addOrRemoveSessionFromSchedule:"
+ " sessionId=" + sessionId
+ " inSchedule=" + inSchedule);
syncHelper.addOrRemoveSessionFromSchedule(this, sessionId, inSchedule);
}
} catch (HandlerException.NoDevsiteProfileException e) {
// The user doesn't have a profile, message this to them.
// TODO: better UX for this type of error | // Path: android/src/main/java/com/google/android/apps/iosched/io/HandlerException.java
// public class HandlerException extends IOException {
//
// public HandlerException() {
// super();
// }
//
// public HandlerException(String message) {
// super(message);
// }
//
// public HandlerException(String message, Throwable cause) {
// super(message);
// initCause(cause);
// }
//
// @Override
// public String toString() {
// if (getCause() != null) {
// return getLocalizedMessage() + ": " + getCause();
// } else {
// return getLocalizedMessage();
// }
// }
//
// public static class UnauthorizedException extends HandlerException {
// public UnauthorizedException() {
// }
//
// public UnauthorizedException(String message) {
// super(message);
// }
//
// public UnauthorizedException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// public static class NoDevsiteProfileException extends HandlerException {
// public NoDevsiteProfileException() {
// }
//
// public NoDevsiteProfileException(String message) {
// super(message);
// }
//
// public NoDevsiteProfileException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGI(final String tag, String message) {
// Log.i(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGW(final String tag, String message) {
// Log.w(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
// Path: android/src/main/java/com/google/android/apps/iosched/sync/ScheduleUpdaterService.java
import java.util.LinkedList;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import com.google.android.apps.iosched.io.HandlerException;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
mServiceLooper.quit();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void processPendingScheduleUpdates() {
try {
// Operate on a local copy of the schedule update list so as not to block
// the main thread adding to this list
List<Intent> scheduleUpdates = new ArrayList<Intent>();
synchronized (mScheduleUpdates) {
scheduleUpdates.addAll(mScheduleUpdates);
mScheduleUpdates.clear();
}
SyncHelper syncHelper = new SyncHelper(this);
for (Intent updateIntent : scheduleUpdates) {
String sessionId = updateIntent.getStringExtra(EXTRA_SESSION_ID);
boolean inSchedule = updateIntent.getBooleanExtra(EXTRA_IN_SCHEDULE, false);
LOGI(TAG, "addOrRemoveSessionFromSchedule:"
+ " sessionId=" + sessionId
+ " inSchedule=" + inSchedule);
syncHelper.addOrRemoveSessionFromSchedule(this, sessionId, inSchedule);
}
} catch (HandlerException.NoDevsiteProfileException e) {
// The user doesn't have a profile, message this to them.
// TODO: better UX for this type of error | LOGW(TAG, "To sync your schedule to the web, login to developers.google.com.", e); |
javaBin/AndroiditoJZ12 | android/src/main/java/com/google/android/apps/iosched/sync/ScheduleUpdaterService.java | // Path: android/src/main/java/com/google/android/apps/iosched/io/HandlerException.java
// public class HandlerException extends IOException {
//
// public HandlerException() {
// super();
// }
//
// public HandlerException(String message) {
// super(message);
// }
//
// public HandlerException(String message, Throwable cause) {
// super(message);
// initCause(cause);
// }
//
// @Override
// public String toString() {
// if (getCause() != null) {
// return getLocalizedMessage() + ": " + getCause();
// } else {
// return getLocalizedMessage();
// }
// }
//
// public static class UnauthorizedException extends HandlerException {
// public UnauthorizedException() {
// }
//
// public UnauthorizedException(String message) {
// super(message);
// }
//
// public UnauthorizedException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// public static class NoDevsiteProfileException extends HandlerException {
// public NoDevsiteProfileException() {
// }
//
// public NoDevsiteProfileException(String message) {
// super(message);
// }
//
// public NoDevsiteProfileException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGI(final String tag, String message) {
// Log.i(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGW(final String tag, String message) {
// Log.w(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
| import java.util.LinkedList;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import com.google.android.apps.iosched.io.HandlerException;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator; | synchronized (mScheduleUpdates) {
scheduleUpdates.addAll(mScheduleUpdates);
mScheduleUpdates.clear();
}
SyncHelper syncHelper = new SyncHelper(this);
for (Intent updateIntent : scheduleUpdates) {
String sessionId = updateIntent.getStringExtra(EXTRA_SESSION_ID);
boolean inSchedule = updateIntent.getBooleanExtra(EXTRA_IN_SCHEDULE, false);
LOGI(TAG, "addOrRemoveSessionFromSchedule:"
+ " sessionId=" + sessionId
+ " inSchedule=" + inSchedule);
syncHelper.addOrRemoveSessionFromSchedule(this, sessionId, inSchedule);
}
} catch (HandlerException.NoDevsiteProfileException e) {
// The user doesn't have a profile, message this to them.
// TODO: better UX for this type of error
LOGW(TAG, "To sync your schedule to the web, login to developers.google.com.", e);
mUiThreadHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(ScheduleUpdaterService.this,
"To sync your schedule to the web, login to developers.google.com.",
Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
// TODO: do something useful here, like revert the changes locally in the
// content provider to maintain client/server sync | // Path: android/src/main/java/com/google/android/apps/iosched/io/HandlerException.java
// public class HandlerException extends IOException {
//
// public HandlerException() {
// super();
// }
//
// public HandlerException(String message) {
// super(message);
// }
//
// public HandlerException(String message, Throwable cause) {
// super(message);
// initCause(cause);
// }
//
// @Override
// public String toString() {
// if (getCause() != null) {
// return getLocalizedMessage() + ": " + getCause();
// } else {
// return getLocalizedMessage();
// }
// }
//
// public static class UnauthorizedException extends HandlerException {
// public UnauthorizedException() {
// }
//
// public UnauthorizedException(String message) {
// super(message);
// }
//
// public UnauthorizedException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// public static class NoDevsiteProfileException extends HandlerException {
// public NoDevsiteProfileException() {
// }
//
// public NoDevsiteProfileException(String message) {
// super(message);
// }
//
// public NoDevsiteProfileException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGI(final String tag, String message) {
// Log.i(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGW(final String tag, String message) {
// Log.w(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
// Path: android/src/main/java/com/google/android/apps/iosched/sync/ScheduleUpdaterService.java
import java.util.LinkedList;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import com.google.android.apps.iosched.io.HandlerException;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
synchronized (mScheduleUpdates) {
scheduleUpdates.addAll(mScheduleUpdates);
mScheduleUpdates.clear();
}
SyncHelper syncHelper = new SyncHelper(this);
for (Intent updateIntent : scheduleUpdates) {
String sessionId = updateIntent.getStringExtra(EXTRA_SESSION_ID);
boolean inSchedule = updateIntent.getBooleanExtra(EXTRA_IN_SCHEDULE, false);
LOGI(TAG, "addOrRemoveSessionFromSchedule:"
+ " sessionId=" + sessionId
+ " inSchedule=" + inSchedule);
syncHelper.addOrRemoveSessionFromSchedule(this, sessionId, inSchedule);
}
} catch (HandlerException.NoDevsiteProfileException e) {
// The user doesn't have a profile, message this to them.
// TODO: better UX for this type of error
LOGW(TAG, "To sync your schedule to the web, login to developers.google.com.", e);
mUiThreadHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(ScheduleUpdaterService.this,
"To sync your schedule to the web, login to developers.google.com.",
Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
// TODO: do something useful here, like revert the changes locally in the
// content provider to maintain client/server sync | LOGE(TAG, "Error processing schedule update", e); |
javaBin/AndroiditoJZ12 | android/src/main/java/com/google/android/apps/iosched/ui/widget/BezelImageView.java | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGD(final String tag, String message) {
// if (Log.isLoggable(tag, Log.DEBUG)) {
// Log.d(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
| import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import no.java.schedule.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView; | @Override
protected void drawableStateChanged() {
super.drawableStateChanged();
if (mBorderDrawable.isStateful()) {
mBorderDrawable.setState(getDrawableState());
}
if (mMaskDrawable.isStateful()) {
mMaskDrawable.setState(getDrawableState());
}
// TODO: may need to invalidate elsewhere
invalidate();
}
@Override
public void invalidate() {
if (mGuardInvalidate) {
removeCallbacks(mInvalidateCacheRunnable);
postDelayed(mInvalidateCacheRunnable, 16);
} else {
super.invalidate();
invalidateCache();
}
}
private Runnable mInvalidateCacheRunnable = new Runnable() {
@Override
public void run() {
invalidateCache();
BezelImageView.super.invalidate(); | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGD(final String tag, String message) {
// if (Log.isLoggable(tag, Log.DEBUG)) {
// Log.d(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
// Path: android/src/main/java/com/google/android/apps/iosched/ui/widget/BezelImageView.java
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import no.java.schedule.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
if (mBorderDrawable.isStateful()) {
mBorderDrawable.setState(getDrawableState());
}
if (mMaskDrawable.isStateful()) {
mMaskDrawable.setState(getDrawableState());
}
// TODO: may need to invalidate elsewhere
invalidate();
}
@Override
public void invalidate() {
if (mGuardInvalidate) {
removeCallbacks(mInvalidateCacheRunnable);
postDelayed(mInvalidateCacheRunnable, 16);
} else {
super.invalidate();
invalidateCache();
}
}
private Runnable mInvalidateCacheRunnable = new Runnable() {
@Override
public void run() {
invalidateCache();
BezelImageView.super.invalidate(); | LOGD(TAG, "delayed invalidate"); |
javaBin/AndroiditoJZ12 | android/src/main/java/com/google/android/apps/iosched/util/ImageCache.java | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGD(final String tag, String message) {
// if (Log.isLoggable(tag, Log.DEBUG)) {
// Log.d(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGV(final String tag, String message) {
// //noinspection PointlessBooleanExpression,ConstantConditions
// if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
// Log.v(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
| import no.java.schedule.BuildConfig;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.util.LruCache;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; |
// No existing ImageCache, create one and store it in RetainFragment
if (imageCache == null) {
imageCache = new ImageCache(activity, cacheParams);
mRetainFragment.setObject(imageCache);
}
return imageCache;
}
/**
* Initialize the cache, providing all parameters.
*
* @param context The context to use
* @param cacheParams The cache parameters to initialize the cache
*/
private void init(Context context, ImageCacheParams cacheParams) {
mCacheParams = cacheParams;
final File diskCacheDir = getDiskCacheDir(context, cacheParams.uniqueName);
if (cacheParams.diskCacheEnabled) {
if (!diskCacheDir.exists()) {
diskCacheDir.mkdir();
}
if (getUsableSpace(diskCacheDir) > cacheParams.diskCacheSize) {
try {
mICSDiskCache = ICSDiskLruCache.open(
diskCacheDir, 1, 1, cacheParams.diskCacheSize);
} catch (final IOException e) { | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGD(final String tag, String message) {
// if (Log.isLoggable(tag, Log.DEBUG)) {
// Log.d(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGV(final String tag, String message) {
// //noinspection PointlessBooleanExpression,ConstantConditions
// if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
// Log.v(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
// Path: android/src/main/java/com/google/android/apps/iosched/util/ImageCache.java
import no.java.schedule.BuildConfig;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.util.LruCache;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
// No existing ImageCache, create one and store it in RetainFragment
if (imageCache == null) {
imageCache = new ImageCache(activity, cacheParams);
mRetainFragment.setObject(imageCache);
}
return imageCache;
}
/**
* Initialize the cache, providing all parameters.
*
* @param context The context to use
* @param cacheParams The cache parameters to initialize the cache
*/
private void init(Context context, ImageCacheParams cacheParams) {
mCacheParams = cacheParams;
final File diskCacheDir = getDiskCacheDir(context, cacheParams.uniqueName);
if (cacheParams.diskCacheEnabled) {
if (!diskCacheDir.exists()) {
diskCacheDir.mkdir();
}
if (getUsableSpace(diskCacheDir) > cacheParams.diskCacheSize) {
try {
mICSDiskCache = ICSDiskLruCache.open(
diskCacheDir, 1, 1, cacheParams.diskCacheSize);
} catch (final IOException e) { | LOGE(TAG, "init - " + e); |
javaBin/AndroiditoJZ12 | android/src/main/java/com/google/android/apps/iosched/util/ImageCache.java | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGD(final String tag, String message) {
// if (Log.isLoggable(tag, Log.DEBUG)) {
// Log.d(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGV(final String tag, String message) {
// //noinspection PointlessBooleanExpression,ConstantConditions
// if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
// Log.v(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
| import no.java.schedule.BuildConfig;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.util.LruCache;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; | // Add to disk cache
if (mICSDiskCache != null) {
final String key = hashKeyForDisk(data);
try {
if (mICSDiskCache.get(key) == null) {
final ICSDiskLruCache.Editor editor = mICSDiskCache.edit(key);
if (editor != null) {
final OutputStream out = editor.newOutputStream(ICS_DISK_CACHE_INDEX);
bitmap.compress(
mCacheParams.compressFormat, mCacheParams.compressQuality, out);
editor.commit();
}
}
} catch (final IOException e) {
LOGE(TAG, "addBitmapToCache - " + e);
}
}
}
/**
* Get from memory cache.
*
* @param data Unique identifier for which item to get
* @return The bitmap if found in cache, null otherwise
*/
public Bitmap getBitmapFromMemCache(String data) {
if (mMemoryCache != null) {
final Bitmap memBitmap = mMemoryCache.get(data);
if (memBitmap != null) {
if (BuildConfig.DEBUG) { | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGD(final String tag, String message) {
// if (Log.isLoggable(tag, Log.DEBUG)) {
// Log.d(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGV(final String tag, String message) {
// //noinspection PointlessBooleanExpression,ConstantConditions
// if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
// Log.v(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
// Path: android/src/main/java/com/google/android/apps/iosched/util/ImageCache.java
import no.java.schedule.BuildConfig;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.util.LruCache;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
// Add to disk cache
if (mICSDiskCache != null) {
final String key = hashKeyForDisk(data);
try {
if (mICSDiskCache.get(key) == null) {
final ICSDiskLruCache.Editor editor = mICSDiskCache.edit(key);
if (editor != null) {
final OutputStream out = editor.newOutputStream(ICS_DISK_CACHE_INDEX);
bitmap.compress(
mCacheParams.compressFormat, mCacheParams.compressQuality, out);
editor.commit();
}
}
} catch (final IOException e) {
LOGE(TAG, "addBitmapToCache - " + e);
}
}
}
/**
* Get from memory cache.
*
* @param data Unique identifier for which item to get
* @return The bitmap if found in cache, null otherwise
*/
public Bitmap getBitmapFromMemCache(String data) {
if (mMemoryCache != null) {
final Bitmap memBitmap = mMemoryCache.get(data);
if (memBitmap != null) {
if (BuildConfig.DEBUG) { | LOGD(TAG, "Memory cache hit"); |
javaBin/AndroiditoJZ12 | android/src/main/java/com/google/android/apps/iosched/util/ImageCache.java | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGD(final String tag, String message) {
// if (Log.isLoggable(tag, Log.DEBUG)) {
// Log.d(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGV(final String tag, String message) {
// //noinspection PointlessBooleanExpression,ConstantConditions
// if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
// Log.v(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
| import no.java.schedule.BuildConfig;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.util.LruCache;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; | * Get from memory cache.
*
* @param data Unique identifier for which item to get
* @return The bitmap if found in cache, null otherwise
*/
public Bitmap getBitmapFromMemCache(String data) {
if (mMemoryCache != null) {
final Bitmap memBitmap = mMemoryCache.get(data);
if (memBitmap != null) {
if (BuildConfig.DEBUG) {
LOGD(TAG, "Memory cache hit");
}
return memBitmap;
}
}
return null;
}
/**
* Get from disk cache.
*
* @param data Unique identifier for which item to get
* @return The bitmap if found in cache, null otherwise
*/
public Bitmap getBitmapFromDiskCache(String data) {
final String key = hashKeyForDisk(data);
if (mICSDiskCache != null) {
try {
final ICSDiskLruCache.Snapshot snapshot = mICSDiskCache.get(key);
if (snapshot != null) { | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGD(final String tag, String message) {
// if (Log.isLoggable(tag, Log.DEBUG)) {
// Log.d(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGV(final String tag, String message) {
// //noinspection PointlessBooleanExpression,ConstantConditions
// if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
// Log.v(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
// Path: android/src/main/java/com/google/android/apps/iosched/util/ImageCache.java
import no.java.schedule.BuildConfig;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.util.LruCache;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
* Get from memory cache.
*
* @param data Unique identifier for which item to get
* @return The bitmap if found in cache, null otherwise
*/
public Bitmap getBitmapFromMemCache(String data) {
if (mMemoryCache != null) {
final Bitmap memBitmap = mMemoryCache.get(data);
if (memBitmap != null) {
if (BuildConfig.DEBUG) {
LOGD(TAG, "Memory cache hit");
}
return memBitmap;
}
}
return null;
}
/**
* Get from disk cache.
*
* @param data Unique identifier for which item to get
* @return The bitmap if found in cache, null otherwise
*/
public Bitmap getBitmapFromDiskCache(String data) {
final String key = hashKeyForDisk(data);
if (mICSDiskCache != null) {
try {
final ICSDiskLruCache.Snapshot snapshot = mICSDiskCache.get(key);
if (snapshot != null) { | LOGV(TAG, "ICS disk cache hit"); |
javaBin/AndroiditoJZ12 | android/src/main/java/com/google/android/apps/iosched/ui/widget/ShowHideMasterLayout.java | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGW(final String tag, String message) {
// Log.w(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
| import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import static com.google.android.apps.iosched.util.LogUtils.LOGW; | /*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.ui.widget;
/**
* A layout that supports the Show/Hide pattern for portrait tablet layouts. See <a
* href="http://developer.android.com/design/patterns/multi-pane-layouts.html#orientation">Android
* Design > Patterns > Multi-pane Layouts & gt; Compound Views and Orientation Changes</a> for
* more details on this pattern. This layout should normally be used in association with the Up
* button. Specifically, show the master pane using {@link #showMaster(boolean, int)} when the Up
* button is pressed. If the master pane is visible, defer to normal Up behavior.
*
* <p>TODO: swiping should be more tactile and actually follow the user's finger.
*
* <p>Requires API level 11
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class ShowHideMasterLayout extends ViewGroup implements Animator.AnimatorListener {
| // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGW(final String tag, String message) {
// Log.w(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
// Path: android/src/main/java/com/google/android/apps/iosched/ui/widget/ShowHideMasterLayout.java
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.ui.widget;
/**
* A layout that supports the Show/Hide pattern for portrait tablet layouts. See <a
* href="http://developer.android.com/design/patterns/multi-pane-layouts.html#orientation">Android
* Design > Patterns > Multi-pane Layouts & gt; Compound Views and Orientation Changes</a> for
* more details on this pattern. This layout should normally be used in association with the Up
* button. Specifically, show the master pane using {@link #showMaster(boolean, int)} when the Up
* button is pressed. If the master pane is visible, defer to normal Up behavior.
*
* <p>TODO: swiping should be more tactile and actually follow the user's finger.
*
* <p>Requires API level 11
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class ShowHideMasterLayout extends ViewGroup implements Animator.AnimatorListener {
| private static final String TAG = makeLogTag(ShowHideMasterLayout.class); |
javaBin/AndroiditoJZ12 | android/src/main/java/com/google/android/apps/iosched/ui/widget/ShowHideMasterLayout.java | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGW(final String tag, String message) {
// Log.w(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
| import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import static com.google.android.apps.iosched.util.LogUtils.LOGW; | childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth() -
getPaddingLeft() - getPaddingRight() -
lp.leftMargin - lp.rightMargin,
MeasureSpec.EXACTLY);
} else {
childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin,
lp.width);
}
if (lp.height == LayoutParams.MATCH_PARENT) {
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight() -
getPaddingTop() - getPaddingBottom() -
lp.topMargin - lp.bottomMargin,
MeasureSpec.EXACTLY);
} else {
childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin,
lp.height);
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
updateChildReferences();
if (mMasterView == null || mDetailView == null) { | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGW(final String tag, String message) {
// Log.w(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
// Path: android/src/main/java/com/google/android/apps/iosched/ui/widget/ShowHideMasterLayout.java
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth() -
getPaddingLeft() - getPaddingRight() -
lp.leftMargin - lp.rightMargin,
MeasureSpec.EXACTLY);
} else {
childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin,
lp.width);
}
if (lp.height == LayoutParams.MATCH_PARENT) {
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight() -
getPaddingTop() - getPaddingBottom() -
lp.topMargin - lp.bottomMargin,
MeasureSpec.EXACTLY);
} else {
childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin,
lp.height);
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
updateChildReferences();
if (mMasterView == null || mDetailView == null) { | LOGW(TAG, "Master or detail is missing (need 2 children), can't layout."); |
javaBin/AndroiditoJZ12 | android/src/main/java/com/google/android/apps/iosched/util/ImageWorker.java | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGD(final String tag, String message) {
// if (Log.isLoggable(tag, Log.DEBUG)) {
// Log.d(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGV(final String tag, String message) {
// //noinspection PointlessBooleanExpression,ConstantConditions
// if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
// Log.v(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
| import java.lang.ref.WeakReference;
import java.util.Hashtable;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import no.java.schedule.BuildConfig;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.widget.ImageView; | /**
* If set to true, the image will fade-in once it has been loaded by the
* background thread.
*/
public void setImageFadeIn(boolean fadeIn) {
mFadeInBitmap = fadeIn;
}
public void setExitTasksEarly(boolean exitTasksEarly) {
mExitTasksEarly = exitTasksEarly;
}
/**
* Subclasses should override this to define any processing or work that
* must happen to produce the final bitmap. This will be executed in a
* background thread and be long running. For example, you could resize a
* large bitmap here, or pull down an image from the network.
*
* @param data The data to identify which image to process, as provided by
* {@link ImageWorker#loadImage(Object, ImageView)}
* @return The processed bitmap
*/
protected abstract Bitmap processBitmap(Object data);
public static void cancelWork(ImageView imageView) {
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (bitmapWorkerTask != null) {
bitmapWorkerTask.cancel(true);
if (BuildConfig.DEBUG) {
final Object bitmapData = bitmapWorkerTask.data; | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGD(final String tag, String message) {
// if (Log.isLoggable(tag, Log.DEBUG)) {
// Log.d(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGV(final String tag, String message) {
// //noinspection PointlessBooleanExpression,ConstantConditions
// if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
// Log.v(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
// Path: android/src/main/java/com/google/android/apps/iosched/util/ImageWorker.java
import java.lang.ref.WeakReference;
import java.util.Hashtable;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import no.java.schedule.BuildConfig;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.widget.ImageView;
/**
* If set to true, the image will fade-in once it has been loaded by the
* background thread.
*/
public void setImageFadeIn(boolean fadeIn) {
mFadeInBitmap = fadeIn;
}
public void setExitTasksEarly(boolean exitTasksEarly) {
mExitTasksEarly = exitTasksEarly;
}
/**
* Subclasses should override this to define any processing or work that
* must happen to produce the final bitmap. This will be executed in a
* background thread and be long running. For example, you could resize a
* large bitmap here, or pull down an image from the network.
*
* @param data The data to identify which image to process, as provided by
* {@link ImageWorker#loadImage(Object, ImageView)}
* @return The processed bitmap
*/
protected abstract Bitmap processBitmap(Object data);
public static void cancelWork(ImageView imageView) {
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (bitmapWorkerTask != null) {
bitmapWorkerTask.cancel(true);
if (BuildConfig.DEBUG) {
final Object bitmapData = bitmapWorkerTask.data; | LOGD(TAG, "cancelWork - cancelled work for " + bitmapData); |
javaBin/AndroiditoJZ12 | android/src/main/java/com/google/android/apps/iosched/util/ImageWorker.java | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGD(final String tag, String message) {
// if (Log.isLoggable(tag, Log.DEBUG)) {
// Log.d(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGV(final String tag, String message) {
// //noinspection PointlessBooleanExpression,ConstantConditions
// if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
// Log.v(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
| import java.lang.ref.WeakReference;
import java.util.Hashtable;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import no.java.schedule.BuildConfig;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.widget.ImageView; | *
* @param data The data to identify which image to process, as provided by
* {@link ImageWorker#loadImage(Object, ImageView)}
* @return The processed bitmap
*/
protected abstract Bitmap processBitmap(Object data);
public static void cancelWork(ImageView imageView) {
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (bitmapWorkerTask != null) {
bitmapWorkerTask.cancel(true);
if (BuildConfig.DEBUG) {
final Object bitmapData = bitmapWorkerTask.data;
LOGD(TAG, "cancelWork - cancelled work for " + bitmapData);
}
}
}
/**
* Returns true if the current work has been canceled or if there was no
* work in progress on this image view. Returns false if the work in
* progress deals with the same data. The work is not stopped in that case.
*/
public static boolean cancelPotentialWork(Object data, ImageView imageView) {
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (bitmapWorkerTask != null) {
final Object bitmapData = bitmapWorkerTask.data;
if (bitmapData == null || !bitmapData.equals(data)) {
bitmapWorkerTask.cancel(true); | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGD(final String tag, String message) {
// if (Log.isLoggable(tag, Log.DEBUG)) {
// Log.d(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGV(final String tag, String message) {
// //noinspection PointlessBooleanExpression,ConstantConditions
// if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
// Log.v(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
// Path: android/src/main/java/com/google/android/apps/iosched/util/ImageWorker.java
import java.lang.ref.WeakReference;
import java.util.Hashtable;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import no.java.schedule.BuildConfig;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.widget.ImageView;
*
* @param data The data to identify which image to process, as provided by
* {@link ImageWorker#loadImage(Object, ImageView)}
* @return The processed bitmap
*/
protected abstract Bitmap processBitmap(Object data);
public static void cancelWork(ImageView imageView) {
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (bitmapWorkerTask != null) {
bitmapWorkerTask.cancel(true);
if (BuildConfig.DEBUG) {
final Object bitmapData = bitmapWorkerTask.data;
LOGD(TAG, "cancelWork - cancelled work for " + bitmapData);
}
}
}
/**
* Returns true if the current work has been canceled or if there was no
* work in progress on this image view. Returns false if the work in
* progress deals with the same data. The work is not stopped in that case.
*/
public static boolean cancelPotentialWork(Object data, ImageView imageView) {
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (bitmapWorkerTask != null) {
final Object bitmapData = bitmapWorkerTask.data;
if (bitmapData == null || !bitmapData.equals(data)) {
bitmapWorkerTask.cancel(true); | LOGV(TAG, "cancelPotentialWork - cancelled work for " + data); |
javaBin/AndroiditoJZ12 | android/src/main/java/com/google/android/apps/iosched/sync/SyncAdapter.java | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGI(final String tag, String message) {
// Log.i(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
| import android.content.*;
import android.preference.PreferenceManager;
import no.java.schedule.BuildConfig;
import android.accounts.Account;
import android.os.Bundle;
import java.io.IOException;
import java.util.regex.Pattern;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; | /*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.sync;
/**
* Sync adapter for Google I/O data. Note that this sync adapter makes heavy use of a
* "conference API" that is not currently open source.
*/
public class SyncAdapter extends AbstractThreadedSyncAdapter {
private static final String TAG = makeLogTag(SyncAdapter.class);
private static final Pattern sSanitizeAccountNamePattern = Pattern.compile("(.).*?(.?)@");
private final Context mContext;
private SyncHelper mSyncHelper;
public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
mContext = context;
//noinspection ConstantConditions,PointlessBooleanExpression
if (!BuildConfig.DEBUG) {
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable throwable) { | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGI(final String tag, String message) {
// Log.i(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
// Path: android/src/main/java/com/google/android/apps/iosched/sync/SyncAdapter.java
import android.content.*;
import android.preference.PreferenceManager;
import no.java.schedule.BuildConfig;
import android.accounts.Account;
import android.os.Bundle;
import java.io.IOException;
import java.util.regex.Pattern;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.sync;
/**
* Sync adapter for Google I/O data. Note that this sync adapter makes heavy use of a
* "conference API" that is not currently open source.
*/
public class SyncAdapter extends AbstractThreadedSyncAdapter {
private static final String TAG = makeLogTag(SyncAdapter.class);
private static final Pattern sSanitizeAccountNamePattern = Pattern.compile("(.).*?(.?)@");
private final Context mContext;
private SyncHelper mSyncHelper;
public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
mContext = context;
//noinspection ConstantConditions,PointlessBooleanExpression
if (!BuildConfig.DEBUG) {
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable throwable) { | LOGE(TAG, "Uncaught sync exception, suppressing UI in release build.", |
javaBin/AndroiditoJZ12 | android/src/main/java/com/google/android/apps/iosched/sync/SyncAdapter.java | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGI(final String tag, String message) {
// Log.i(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
| import android.content.*;
import android.preference.PreferenceManager;
import no.java.schedule.BuildConfig;
import android.accounts.Account;
import android.os.Bundle;
import java.io.IOException;
import java.util.regex.Pattern;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; | /*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.sync;
/**
* Sync adapter for Google I/O data. Note that this sync adapter makes heavy use of a
* "conference API" that is not currently open source.
*/
public class SyncAdapter extends AbstractThreadedSyncAdapter {
private static final String TAG = makeLogTag(SyncAdapter.class);
private static final Pattern sSanitizeAccountNamePattern = Pattern.compile("(.).*?(.?)@");
private final Context mContext;
private SyncHelper mSyncHelper;
public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
mContext = context;
//noinspection ConstantConditions,PointlessBooleanExpression
if (!BuildConfig.DEBUG) {
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
LOGE(TAG, "Uncaught sync exception, suppressing UI in release build.",
throwable);
}
});
}
}
@Override
public void onPerformSync(final Account account, Bundle extras, String authority,
final ContentProviderClient provider, final SyncResult syncResult) {
final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false);
final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
final boolean initialize = extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false);
final String logSanitizedAccountName = sSanitizeAccountNamePattern
.matcher(account.name).replaceAll("$1...$2@");
if (uploadOnly) {
return;
}
| // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGI(final String tag, String message) {
// Log.i(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
// Path: android/src/main/java/com/google/android/apps/iosched/sync/SyncAdapter.java
import android.content.*;
import android.preference.PreferenceManager;
import no.java.schedule.BuildConfig;
import android.accounts.Account;
import android.os.Bundle;
import java.io.IOException;
import java.util.regex.Pattern;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.sync;
/**
* Sync adapter for Google I/O data. Note that this sync adapter makes heavy use of a
* "conference API" that is not currently open source.
*/
public class SyncAdapter extends AbstractThreadedSyncAdapter {
private static final String TAG = makeLogTag(SyncAdapter.class);
private static final Pattern sSanitizeAccountNamePattern = Pattern.compile("(.).*?(.?)@");
private final Context mContext;
private SyncHelper mSyncHelper;
public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
mContext = context;
//noinspection ConstantConditions,PointlessBooleanExpression
if (!BuildConfig.DEBUG) {
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
LOGE(TAG, "Uncaught sync exception, suppressing UI in release build.",
throwable);
}
});
}
}
@Override
public void onPerformSync(final Account account, Bundle extras, String authority,
final ContentProviderClient provider, final SyncResult syncResult) {
final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false);
final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
final boolean initialize = extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false);
final String logSanitizedAccountName = sSanitizeAccountNamePattern
.matcher(account.name).replaceAll("$1...$2@");
if (uploadOnly) {
return;
}
| LOGI(TAG, "Beginning sync for account " + logSanitizedAccountName + "," + |
javaBin/AndroiditoJZ12 | android/src/main/java/com/google/android/apps/iosched/util/ImageFetcher.java | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGD(final String tag, String message) {
// if (Log.isLoggable(tag, Log.DEBUG)) {
// Log.d(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGV(final String tag, String message) {
// //noinspection PointlessBooleanExpression,ConstantConditions
// if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
// Log.v(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
| import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL; | loadImage(new ImageData(key, ImageData.IMAGE_TYPE_NORMAL), imageView, mLoadingBitmap);
}
public void setParams(ImageFetcherParams params) {
mFetcherParams = params;
}
/**
* Set the target image width and height.
*/
public void setImageSize(int width, int height) {
mFetcherParams.mImageWidth = width;
mFetcherParams.mImageHeight = height;
}
/**
* Set the target image size (width and height will be the same).
*/
public void setImageSize(int size) {
setImageSize(size, size);
}
/**
* The main process method, which will be called by the ImageWorker in the AsyncTask background
* thread.
*
* @param key The key to load the bitmap, in this case, a regular http URL
* @return The downloaded and resized bitmap
*/
private Bitmap processBitmap(String key, int type) { | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGD(final String tag, String message) {
// if (Log.isLoggable(tag, Log.DEBUG)) {
// Log.d(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGV(final String tag, String message) {
// //noinspection PointlessBooleanExpression,ConstantConditions
// if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
// Log.v(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
// Path: android/src/main/java/com/google/android/apps/iosched/util/ImageFetcher.java
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
loadImage(new ImageData(key, ImageData.IMAGE_TYPE_NORMAL), imageView, mLoadingBitmap);
}
public void setParams(ImageFetcherParams params) {
mFetcherParams = params;
}
/**
* Set the target image width and height.
*/
public void setImageSize(int width, int height) {
mFetcherParams.mImageWidth = width;
mFetcherParams.mImageHeight = height;
}
/**
* Set the target image size (width and height will be the same).
*/
public void setImageSize(int size) {
setImageSize(size, size);
}
/**
* The main process method, which will be called by the ImageWorker in the AsyncTask background
* thread.
*
* @param key The key to load the bitmap, in this case, a regular http URL
* @return The downloaded and resized bitmap
*/
private Bitmap processBitmap(String key, int type) { | LOGD(TAG, "processBitmap - " + key); |
javaBin/AndroiditoJZ12 | android/src/main/java/com/google/android/apps/iosched/util/ImageFetcher.java | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGD(final String tag, String message) {
// if (Log.isLoggable(tag, Log.DEBUG)) {
// Log.d(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGV(final String tag, String message) {
// //noinspection PointlessBooleanExpression,ConstantConditions
// if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
// Log.v(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
| import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL; | */
public static byte[] downloadBitmapToMemory(Context context, String urlString, int maxBytes) {
disableConnectionReuseIfNecessary();
HttpURLConnection urlConnection = null;
ByteArrayOutputStream out = null;
InputStream in = null;
try {
final URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE_BYTES);
out = new ByteArrayOutputStream(IO_BUFFER_SIZE_BYTES);
final byte[] buffer = new byte[128];
int total = 0;
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
total += bytesRead;
if (total > maxBytes) {
return null;
}
out.write(buffer, 0, bytesRead);
}
return out.toByteArray();
} catch (final IOException e) { | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGD(final String tag, String message) {
// if (Log.isLoggable(tag, Log.DEBUG)) {
// Log.d(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGV(final String tag, String message) {
// //noinspection PointlessBooleanExpression,ConstantConditions
// if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
// Log.v(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
// Path: android/src/main/java/com/google/android/apps/iosched/util/ImageFetcher.java
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
*/
public static byte[] downloadBitmapToMemory(Context context, String urlString, int maxBytes) {
disableConnectionReuseIfNecessary();
HttpURLConnection urlConnection = null;
ByteArrayOutputStream out = null;
InputStream in = null;
try {
final URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE_BYTES);
out = new ByteArrayOutputStream(IO_BUFFER_SIZE_BYTES);
final byte[] buffer = new byte[128];
int total = 0;
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
total += bytesRead;
if (total > maxBytes) {
return null;
}
out.write(buffer, 0, bytesRead);
}
return out.toByteArray();
} catch (final IOException e) { | LOGE(TAG, "Error in downloadBitmapToMemory - " + e); |
javaBin/AndroiditoJZ12 | android/src/main/java/com/google/android/apps/iosched/util/ImageFetcher.java | // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGD(final String tag, String message) {
// if (Log.isLoggable(tag, Log.DEBUG)) {
// Log.d(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGV(final String tag, String message) {
// //noinspection PointlessBooleanExpression,ConstantConditions
// if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
// Log.v(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
| import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL; | try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (final IOException e) {
LOGE(TAG, "Error in downloadBitmapToMemory - " + e);
}
}
return null;
}
/**
* Download a bitmap from a URL, write it to a disk and return the File pointer. This
* implementation uses a simple disk cache.
*
* @param context The context to use
* @param urlString The URL to fetch
* @return A File pointing to the fetched bitmap
*/
public static File downloadBitmapToFile(Context context, String urlString, String uniqueName) {
final File cacheDir = ImageCache.getDiskCacheDir(context, uniqueName);
if (!cacheDir.exists()) {
cacheDir.mkdir();
}
| // Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGD(final String tag, String message) {
// if (Log.isLoggable(tag, Log.DEBUG)) {
// Log.d(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGE(final String tag, String message) {
// Log.e(tag, message);
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static void LOGV(final String tag, String message) {
// //noinspection PointlessBooleanExpression,ConstantConditions
// if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
// Log.v(tag, message);
// }
// }
//
// Path: android/src/main/java/com/google/android/apps/iosched/util/LogUtils.java
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
// Path: android/src/main/java/com/google/android/apps/iosched/util/ImageFetcher.java
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (final IOException e) {
LOGE(TAG, "Error in downloadBitmapToMemory - " + e);
}
}
return null;
}
/**
* Download a bitmap from a URL, write it to a disk and return the File pointer. This
* implementation uses a simple disk cache.
*
* @param context The context to use
* @param urlString The URL to fetch
* @return A File pointing to the fetched bitmap
*/
public static File downloadBitmapToFile(Context context, String urlString, String uniqueName) {
final File cacheDir = ImageCache.getDiskCacheDir(context, uniqueName);
if (!cacheDir.exists()) {
cacheDir.mkdir();
}
| LOGV(TAG, "downloadBitmap - downloading - " + urlString); |
javaBin/AndroiditoJZ12 | android/src/main/java/com/google/android/apps/iosched/util/RestServiceDevNull.java | // Path: android/src/main/java/com/google/android/apps/iosched/io/model/Constants.java
// public class Constants {
// public static final String LIGHTNINGTALK = "lightning-talk";
// public static final String WORKSHOP = "workshop";
//
// // session feedback key for passing data to intent
// public static final String SESSION_FEEDBACK_TITLE = "SESSION_FEEDBACK_TITLE";
// public static final String SESSION_FEEDBACK_SUBTITLE = "SESSION_FEEDBACK_SUBTITLE";
// public static final String SESSION_ID = "SESSION_ID";
//
// public static final String SESSION_FEEDBACK_WEB_URI_TEST = "http://test.javazone.no/devnull/server";
// public static final String SESSION_FEEDBACK_WEB_URI = "http://javazone.no/devnull/server";
//
// }
| import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.google.android.apps.iosched.io.model.Constants;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import no.java.schedule.io.model.JZFeedback;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response; | package com.google.android.apps.iosched.util;
public class RestServiceDevNull {
private static RestServiceDevNull instance = null;
private RestDevApi restDevApi = null;
private Activity activity = null;
private RestServiceDevNull(String mode) {
//TODO | // Path: android/src/main/java/com/google/android/apps/iosched/io/model/Constants.java
// public class Constants {
// public static final String LIGHTNINGTALK = "lightning-talk";
// public static final String WORKSHOP = "workshop";
//
// // session feedback key for passing data to intent
// public static final String SESSION_FEEDBACK_TITLE = "SESSION_FEEDBACK_TITLE";
// public static final String SESSION_FEEDBACK_SUBTITLE = "SESSION_FEEDBACK_SUBTITLE";
// public static final String SESSION_ID = "SESSION_ID";
//
// public static final String SESSION_FEEDBACK_WEB_URI_TEST = "http://test.javazone.no/devnull/server";
// public static final String SESSION_FEEDBACK_WEB_URI = "http://javazone.no/devnull/server";
//
// }
// Path: android/src/main/java/com/google/android/apps/iosched/util/RestServiceDevNull.java
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.google.android.apps.iosched.io.model.Constants;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import no.java.schedule.io.model.JZFeedback;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
package com.google.android.apps.iosched.util;
public class RestServiceDevNull {
private static RestServiceDevNull instance = null;
private RestDevApi restDevApi = null;
private Activity activity = null;
private RestServiceDevNull(String mode) {
//TODO | String endPoint = Constants.SESSION_FEEDBACK_WEB_URI; |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/composite/SumType.java | // Path: src/main/java/org/hummingbirdlang/types/CompositeType.java
// public abstract class CompositeType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
| import org.hummingbirdlang.types.CompositeType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.Type; | package org.hummingbirdlang.types.composite;
/**
* Disjoint union type (aka. sum type): it is composed of members A and B.
* Eventually the union is discriminated into either A or B.
*/
public class SumType extends CompositeType {
public final Type[] subTypes;
public SumType(Type[] subTypes) {
this.subTypes = subTypes;
}
@Override | // Path: src/main/java/org/hummingbirdlang/types/CompositeType.java
// public abstract class CompositeType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
// Path: src/main/java/org/hummingbirdlang/types/composite/SumType.java
import org.hummingbirdlang.types.CompositeType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.Type;
package org.hummingbirdlang.types.composite;
/**
* Disjoint union type (aka. sum type): it is composed of members A and B.
* Eventually the union is discriminated into either A or B.
*/
public class SumType extends CompositeType {
public final Type[] subTypes;
public SumType(Type[] subTypes) {
this.subTypes = subTypes;
}
@Override | public Property getProperty(String name) throws PropertyNotFoundException { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/composite/SumType.java | // Path: src/main/java/org/hummingbirdlang/types/CompositeType.java
// public abstract class CompositeType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
| import org.hummingbirdlang.types.CompositeType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.Type; | package org.hummingbirdlang.types.composite;
/**
* Disjoint union type (aka. sum type): it is composed of members A and B.
* Eventually the union is discriminated into either A or B.
*/
public class SumType extends CompositeType {
public final Type[] subTypes;
public SumType(Type[] subTypes) {
this.subTypes = subTypes;
}
@Override | // Path: src/main/java/org/hummingbirdlang/types/CompositeType.java
// public abstract class CompositeType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
// Path: src/main/java/org/hummingbirdlang/types/composite/SumType.java
import org.hummingbirdlang.types.CompositeType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.Type;
package org.hummingbirdlang.types.composite;
/**
* Disjoint union type (aka. sum type): it is composed of members A and B.
* Eventually the union is discriminated into either A or B.
*/
public class SumType extends CompositeType {
public final Type[] subTypes;
public SumType(Type[] subTypes) {
this.subTypes = subTypes;
}
@Override | public Property getProperty(String name) throws PropertyNotFoundException { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/concrete/BooleanType.java | // Path: src/main/java/org/hummingbirdlang/types/ConcreteType.java
// public abstract class ConcreteType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
| import org.hummingbirdlang.types.ConcreteType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException; | package org.hummingbirdlang.types.concrete;
public final class BooleanType extends ConcreteType {
public static final BooleanType SINGLETON = new BooleanType();
private BooleanType() {
}
@Override | // Path: src/main/java/org/hummingbirdlang/types/ConcreteType.java
// public abstract class ConcreteType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
// Path: src/main/java/org/hummingbirdlang/types/concrete/BooleanType.java
import org.hummingbirdlang.types.ConcreteType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
package org.hummingbirdlang.types.concrete;
public final class BooleanType extends ConcreteType {
public static final BooleanType SINGLETON = new BooleanType();
private BooleanType() {
}
@Override | public Property getProperty(String name) throws PropertyNotFoundException { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/concrete/BooleanType.java | // Path: src/main/java/org/hummingbirdlang/types/ConcreteType.java
// public abstract class ConcreteType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
| import org.hummingbirdlang.types.ConcreteType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException; | package org.hummingbirdlang.types.concrete;
public final class BooleanType extends ConcreteType {
public static final BooleanType SINGLETON = new BooleanType();
private BooleanType() {
}
@Override | // Path: src/main/java/org/hummingbirdlang/types/ConcreteType.java
// public abstract class ConcreteType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
// Path: src/main/java/org/hummingbirdlang/types/concrete/BooleanType.java
import org.hummingbirdlang.types.ConcreteType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
package org.hummingbirdlang.types.concrete;
public final class BooleanType extends ConcreteType {
public static final BooleanType SINGLETON = new BooleanType();
private BooleanType() {
}
@Override | public Property getProperty(String name) throws PropertyNotFoundException { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/nodes/builtins/StringNodes.java | // Path: src/main/java/org/hummingbirdlang/nodes/HBNode.java
// @NodeInfo(language = "HB")
// public abstract class HBNode extends Node {
// // Execute with a generic unspecialized return value.
// public abstract Object executeGeneric(VirtualFrame frame);
//
// // Execute without a return value.
// public void executeVoid(VirtualFrame frame) {
// executeGeneric(frame);
// }
// }
| import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.Specialization;
import org.hummingbirdlang.nodes.HBNode; | package org.hummingbirdlang.nodes.builtins;
@BuiltinClass("String")
public abstract class StringNodes {
@BuiltinMethod("toUpperCase") | // Path: src/main/java/org/hummingbirdlang/nodes/HBNode.java
// @NodeInfo(language = "HB")
// public abstract class HBNode extends Node {
// // Execute with a generic unspecialized return value.
// public abstract Object executeGeneric(VirtualFrame frame);
//
// // Execute without a return value.
// public void executeVoid(VirtualFrame frame) {
// executeGeneric(frame);
// }
// }
// Path: src/main/java/org/hummingbirdlang/nodes/builtins/StringNodes.java
import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.Specialization;
import org.hummingbirdlang.nodes.HBNode;
package org.hummingbirdlang.nodes.builtins;
@BuiltinClass("String")
public abstract class StringNodes {
@BuiltinMethod("toUpperCase") | @NodeChild(value = "self", type = HBNode.class) |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/nodes/HBIntegerLiteralNode.java | // Path: src/main/java/org/hummingbirdlang/types/realize/InferenceVisitor.java
// public final class InferenceVisitor {
// private final Index index;
// private BuiltinScope builtinScope;
// private Scope currentScope;
//
// public InferenceVisitor(Index index) {
// this.builtinScope = new BuiltinScope(index);
// this.currentScope = new SourceScope(this.builtinScope);
// this.index = index;
// }
//
// private void pushScope() {
// Scope parentScope = this.currentScope;
// this.currentScope = new LocalScope(parentScope);
// }
//
// private void popScope() {
// this.currentScope = this.currentScope.getParent();
// }
//
// public void enter(HBSourceRootNode rootNode) {
// rootNode.setBuiltinScope(this.builtinScope);
// }
//
// public void leave(HBSourceRootNode rootNode) {
// // Current scope should be the `SourceScope`.
// if (!(this.currentScope instanceof SourceScope)) {
// throw new RuntimeException("Did not return to SourceScope");
// }
// this.currentScope.close();
// }
//
// public void enter(HBFunctionNode functionNode) {
// // TODO: Actually set and/or infer parameter and return types.
// FunctionType functionType = new FunctionType(
// new Type[]{},
// new UnknownType(),
// functionNode.getName(),
// functionNode.getCallTarget()
// );
// functionNode.setFunctionType(functionType);
// functionType.setDeclarationScope(this.currentScope);
// this.currentScope.setLocal(functionNode.getName(), functionType);
// this.pushScope();
// functionType.setOwnScope(this.currentScope);
// }
//
// public void leave(HBFunctionNode functionNode) {
// this.currentScope.close();
// this.popScope();
// }
//
// public void enter(HBBlockNode blockNode) {
// return;
// }
//
// public void leave(HBBlockNode blockNode) {
// return;
// }
//
// public void visit(HBAssignmentNode assignmentNode) throws TypeMismatchException {
// Type targetType = assignmentNode.getTargetNode().getType();
// Type valueType = assignmentNode.getValueNode().getType();
// targetType.assertEquals(valueType);
// }
//
// public void visit(HBCallNode callNode) throws TypeMismatchException {
// Type targetType = callNode.getTargetNode().getType();
//
// Type[] parameterTypes;
// Type returnType;
// if (targetType instanceof FunctionType) {
// FunctionType functionType = (FunctionType)targetType;
// parameterTypes = functionType.getParameterTypes();
// returnType = functionType.getReturnType();
// } else if (targetType instanceof MethodType) {
// MethodType methodType = (MethodType)targetType;
// parameterTypes = methodType.getParameterTypes();
// returnType = methodType.getReturnType();
// } else {
// throw new RuntimeException("Cannot call target of type: " + String.valueOf(targetType));
// }
//
// HBExpressionNode[] argumentNodes = callNode.getArgumentNodes();
// int expectedParameters = parameterTypes.length;
// int actualArguments = argumentNodes.length;
// if (expectedParameters != actualArguments) {
// throw new TypeMismatchException("Argument count mismatch: expected " + expectedParameters + " got " + actualArguments);
// }
//
// for (int index = 0; index < expectedParameters; index++) {
// Type parameterType = parameterTypes[index];
// Type argumentType = argumentNodes[index].getType();
// if (!parameterType.equals(argumentType)) {
// throw new TypeMismatchException("Argument " + (index + 1) + " mismatch: expected " + parameterType.toString() + " got " + String.valueOf(argumentType));
// }
// }
//
// callNode.setType(returnType);
// }
//
// public void visit(HBIdentifierNode identifierNode) throws NameNotFoundException {
// Resolution resolution = this.currentScope.resolve(identifierNode.getName());
// identifierNode.setResolution(resolution);
// }
//
// public void visit(HBIntegerLiteralNode literalNode) {
// literalNode.setType(this.getIntegerType());
// }
//
// public void visit(HBLetDeclarationNode letNode) {
// Type rightType = letNode.getRightNode().getType();
// String left = letNode.getLeft();
// this.currentScope.setLocal(left, rightType);
// }
//
// public void visit(HBLogicalAndNode andNode) {
// Type leftType = andNode.getLeftNode().getType();
// Type rightType = andNode.getRightNode().getType();
//
// Type resultType;
// if (!rightType.equals(BooleanType.SINGLETON)) {
// resultType = new SumType(new Type[]{ BooleanType.SINGLETON, rightType, });
// } else {
// resultType = BooleanType.SINGLETON;
// }
// andNode.setType(resultType);
// }
//
// public void visit(HBPropertyNode propertyNode) throws PropertyNotFoundException {
// Type targetType = propertyNode.getTargetNode().getType();
// Property property = targetType.getProperty(propertyNode.getPropertyName());
// propertyNode.setProperty(property);
// propertyNode.setType(property.getType());
// }
//
// public void visit(HBReturnNode returnNode) {
// Type returnType = NullType.SINGLETON;
// HBExpressionNode expressionNode = returnNode.getExpressionNode();
// if (expressionNode != null) {
// returnType = expressionNode.getType();
// }
// returnNode.setReturnType(returnType);
// }
//
// public void visit(HBStringLiteralNode literalNode) {
// literalNode.setType(this.getStringType());
// }
//
// private StringType getStringType() {
// Type type = this.index.getBuiltin().getType(StringType.BUILTIN_NAME);
// return (StringType)type;
// }
//
// private IntegerType getIntegerType() {
// Type type = this.index.getBuiltin().getType(IntegerType.BUILTIN_NAME);
// return (IntegerType)type;
// }
// }
| import com.oracle.truffle.api.frame.VirtualFrame;
import org.hummingbirdlang.types.realize.InferenceVisitor; | package org.hummingbirdlang.nodes;
public class HBIntegerLiteralNode extends HBExpressionNode {
private final long value;
public HBIntegerLiteralNode(String value) {
this.value = Long.decode(value);
}
| // Path: src/main/java/org/hummingbirdlang/types/realize/InferenceVisitor.java
// public final class InferenceVisitor {
// private final Index index;
// private BuiltinScope builtinScope;
// private Scope currentScope;
//
// public InferenceVisitor(Index index) {
// this.builtinScope = new BuiltinScope(index);
// this.currentScope = new SourceScope(this.builtinScope);
// this.index = index;
// }
//
// private void pushScope() {
// Scope parentScope = this.currentScope;
// this.currentScope = new LocalScope(parentScope);
// }
//
// private void popScope() {
// this.currentScope = this.currentScope.getParent();
// }
//
// public void enter(HBSourceRootNode rootNode) {
// rootNode.setBuiltinScope(this.builtinScope);
// }
//
// public void leave(HBSourceRootNode rootNode) {
// // Current scope should be the `SourceScope`.
// if (!(this.currentScope instanceof SourceScope)) {
// throw new RuntimeException("Did not return to SourceScope");
// }
// this.currentScope.close();
// }
//
// public void enter(HBFunctionNode functionNode) {
// // TODO: Actually set and/or infer parameter and return types.
// FunctionType functionType = new FunctionType(
// new Type[]{},
// new UnknownType(),
// functionNode.getName(),
// functionNode.getCallTarget()
// );
// functionNode.setFunctionType(functionType);
// functionType.setDeclarationScope(this.currentScope);
// this.currentScope.setLocal(functionNode.getName(), functionType);
// this.pushScope();
// functionType.setOwnScope(this.currentScope);
// }
//
// public void leave(HBFunctionNode functionNode) {
// this.currentScope.close();
// this.popScope();
// }
//
// public void enter(HBBlockNode blockNode) {
// return;
// }
//
// public void leave(HBBlockNode blockNode) {
// return;
// }
//
// public void visit(HBAssignmentNode assignmentNode) throws TypeMismatchException {
// Type targetType = assignmentNode.getTargetNode().getType();
// Type valueType = assignmentNode.getValueNode().getType();
// targetType.assertEquals(valueType);
// }
//
// public void visit(HBCallNode callNode) throws TypeMismatchException {
// Type targetType = callNode.getTargetNode().getType();
//
// Type[] parameterTypes;
// Type returnType;
// if (targetType instanceof FunctionType) {
// FunctionType functionType = (FunctionType)targetType;
// parameterTypes = functionType.getParameterTypes();
// returnType = functionType.getReturnType();
// } else if (targetType instanceof MethodType) {
// MethodType methodType = (MethodType)targetType;
// parameterTypes = methodType.getParameterTypes();
// returnType = methodType.getReturnType();
// } else {
// throw new RuntimeException("Cannot call target of type: " + String.valueOf(targetType));
// }
//
// HBExpressionNode[] argumentNodes = callNode.getArgumentNodes();
// int expectedParameters = parameterTypes.length;
// int actualArguments = argumentNodes.length;
// if (expectedParameters != actualArguments) {
// throw new TypeMismatchException("Argument count mismatch: expected " + expectedParameters + " got " + actualArguments);
// }
//
// for (int index = 0; index < expectedParameters; index++) {
// Type parameterType = parameterTypes[index];
// Type argumentType = argumentNodes[index].getType();
// if (!parameterType.equals(argumentType)) {
// throw new TypeMismatchException("Argument " + (index + 1) + " mismatch: expected " + parameterType.toString() + " got " + String.valueOf(argumentType));
// }
// }
//
// callNode.setType(returnType);
// }
//
// public void visit(HBIdentifierNode identifierNode) throws NameNotFoundException {
// Resolution resolution = this.currentScope.resolve(identifierNode.getName());
// identifierNode.setResolution(resolution);
// }
//
// public void visit(HBIntegerLiteralNode literalNode) {
// literalNode.setType(this.getIntegerType());
// }
//
// public void visit(HBLetDeclarationNode letNode) {
// Type rightType = letNode.getRightNode().getType();
// String left = letNode.getLeft();
// this.currentScope.setLocal(left, rightType);
// }
//
// public void visit(HBLogicalAndNode andNode) {
// Type leftType = andNode.getLeftNode().getType();
// Type rightType = andNode.getRightNode().getType();
//
// Type resultType;
// if (!rightType.equals(BooleanType.SINGLETON)) {
// resultType = new SumType(new Type[]{ BooleanType.SINGLETON, rightType, });
// } else {
// resultType = BooleanType.SINGLETON;
// }
// andNode.setType(resultType);
// }
//
// public void visit(HBPropertyNode propertyNode) throws PropertyNotFoundException {
// Type targetType = propertyNode.getTargetNode().getType();
// Property property = targetType.getProperty(propertyNode.getPropertyName());
// propertyNode.setProperty(property);
// propertyNode.setType(property.getType());
// }
//
// public void visit(HBReturnNode returnNode) {
// Type returnType = NullType.SINGLETON;
// HBExpressionNode expressionNode = returnNode.getExpressionNode();
// if (expressionNode != null) {
// returnType = expressionNode.getType();
// }
// returnNode.setReturnType(returnType);
// }
//
// public void visit(HBStringLiteralNode literalNode) {
// literalNode.setType(this.getStringType());
// }
//
// private StringType getStringType() {
// Type type = this.index.getBuiltin().getType(StringType.BUILTIN_NAME);
// return (StringType)type;
// }
//
// private IntegerType getIntegerType() {
// Type type = this.index.getBuiltin().getType(IntegerType.BUILTIN_NAME);
// return (IntegerType)type;
// }
// }
// Path: src/main/java/org/hummingbirdlang/nodes/HBIntegerLiteralNode.java
import com.oracle.truffle.api.frame.VirtualFrame;
import org.hummingbirdlang.types.realize.InferenceVisitor;
package org.hummingbirdlang.nodes;
public class HBIntegerLiteralNode extends HBExpressionNode {
private final long value;
public HBIntegerLiteralNode(String value) {
this.value = Long.decode(value);
}
| public void accept(InferenceVisitor visitor) { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/nodes/frames/SetBindingsNode.java | // Path: src/main/java/org/hummingbirdlang/nodes/HBNode.java
// @NodeInfo(language = "HB")
// public abstract class HBNode extends Node {
// // Execute with a generic unspecialized return value.
// public abstract Object executeGeneric(VirtualFrame frame);
//
// // Execute without a return value.
// public void executeVoid(VirtualFrame frame) {
// executeGeneric(frame);
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/runtime/bindings/Bindings.java
// public final class Bindings {
// private Map<String, Binding> bindings;
//
// public Bindings() {
// this.bindings = new HashMap<>();
// }
//
// public Bindings(BuiltinScope builtinScope) throws NameNotFoundException {
// this();
// // Bootstrap builtins into frame.
// for (String name : builtinScope) {
// Type type = builtinScope.get(name);
// if (type instanceof FunctionType) {
// Object function = new Function((FunctionType)type, null);
// this.bindings.put(name, new BuiltinBinding(name, function));
// } else {
// System.out.println("Skipping bootstrap of builtin " + name + ": " + type.toString());
// }
// }
// }
//
// public boolean contains(String name) {
// return this.bindings.containsKey(name);
// }
//
// public Binding get(String name) {
// return this.bindings.get(name);
// }
//
// public Object getValue(String name) {
// Binding binding = this.get(name);
// return binding.get();
// }
//
// public void add(String name, Binding binding) {
// this.bindings.put(name, binding);
// }
//
// public static final BindingsIdentifier IDENTIFIER = new BindingsIdentifier();
//
// private static final class BindingsIdentifier {
// private BindingsIdentifier() {
// }
// }
// }
| import org.hummingbirdlang.nodes.HBNode;
import org.hummingbirdlang.runtime.bindings.Bindings;
import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.FrameDescriptor;
import com.oracle.truffle.api.frame.FrameSlot;
import com.oracle.truffle.api.frame.VirtualFrame; | package org.hummingbirdlang.nodes.frames;
// Child node should return bindings when executed.
@NodeChild("node")
public abstract class SetBindingsNode extends HBNode {
@Specialization | // Path: src/main/java/org/hummingbirdlang/nodes/HBNode.java
// @NodeInfo(language = "HB")
// public abstract class HBNode extends Node {
// // Execute with a generic unspecialized return value.
// public abstract Object executeGeneric(VirtualFrame frame);
//
// // Execute without a return value.
// public void executeVoid(VirtualFrame frame) {
// executeGeneric(frame);
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/runtime/bindings/Bindings.java
// public final class Bindings {
// private Map<String, Binding> bindings;
//
// public Bindings() {
// this.bindings = new HashMap<>();
// }
//
// public Bindings(BuiltinScope builtinScope) throws NameNotFoundException {
// this();
// // Bootstrap builtins into frame.
// for (String name : builtinScope) {
// Type type = builtinScope.get(name);
// if (type instanceof FunctionType) {
// Object function = new Function((FunctionType)type, null);
// this.bindings.put(name, new BuiltinBinding(name, function));
// } else {
// System.out.println("Skipping bootstrap of builtin " + name + ": " + type.toString());
// }
// }
// }
//
// public boolean contains(String name) {
// return this.bindings.containsKey(name);
// }
//
// public Binding get(String name) {
// return this.bindings.get(name);
// }
//
// public Object getValue(String name) {
// Binding binding = this.get(name);
// return binding.get();
// }
//
// public void add(String name, Binding binding) {
// this.bindings.put(name, binding);
// }
//
// public static final BindingsIdentifier IDENTIFIER = new BindingsIdentifier();
//
// private static final class BindingsIdentifier {
// private BindingsIdentifier() {
// }
// }
// }
// Path: src/main/java/org/hummingbirdlang/nodes/frames/SetBindingsNode.java
import org.hummingbirdlang.nodes.HBNode;
import org.hummingbirdlang.runtime.bindings.Bindings;
import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.FrameDescriptor;
import com.oracle.truffle.api.frame.FrameSlot;
import com.oracle.truffle.api.frame.VirtualFrame;
package org.hummingbirdlang.nodes.frames;
// Child node should return bindings when executed.
@NodeChild("node")
public abstract class SetBindingsNode extends HBNode {
@Specialization | public Object executeSet(VirtualFrame frame, Bindings bindings) { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/scope/SourceScope.java | // Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/realize/Index.java
// public final class Index {
// public static final String BUILTIN = "builtin";
//
// private final HashMap<String, Module> modules = new HashMap<>();
//
// private Index(BuiltinNodes builtins) {
// // Instantiate all the bootstrappable types.
// ArrayList<BootstrappableConcreteType> bootstrappableTypes = new ArrayList<>();
// bootstrappableTypes.add(new IntegerType());
// bootstrappableTypes.add(new StringType());
//
// Module builtin = new Module(Index.BUILTIN);
//
// // Bootstrap the types with the builtins (so that they can instantiate
// // methods with call targets).
// for (BootstrappableConcreteType type : bootstrappableTypes) {
// type.bootstrapBuiltins(builtins);
// builtin.put(type.getBootstrapName(), new TypeReferenceType(type));
// }
//
// // Add root builtin functions to the module.
// builtin.put(builtins.createFunctionType(
// new Type[]{
// new SumType(new Type[]{
// builtin.getType(IntegerType.BUILTIN_NAME),
// builtin.getType(StringType.BUILTIN_NAME),
// }),
// },
// NullType.SINGLETON,
// GlobalNodes.PrintlnNode.class
// ));
//
// // Finalize the bootstrapped types; now that all the types are in the
// // builtin module they can now reference each other.
// for (BootstrappableConcreteType type : bootstrappableTypes) {
// type.bootstrapTypes(builtin);
// }
//
// this.put(builtin);
// }
//
// public static Index bootstrap(BuiltinNodes builtins) {
// return new Index(builtins);
// }
//
// public Module get(String name) {
// return this.modules.get(name);
// }
//
// public Module getBuiltin() {
// return this.modules.get(Index.BUILTIN);
// }
//
// public Module put(Module module) {
// this.modules.put(module.getName(), module);
// return module;
// }
//
// /**
// * Resolves names in a module to type. Names are fully-qualified (eg.
// * "MyClass.MY_CONSTANT").
// */
// public final class Module implements Iterable<String> {
// private final String name;
// private final HashMap<String, Type> types = new HashMap<>();
//
// public Module(String name) {
// this.name = name;
// }
//
// public String getName() {
// return this.name;
// }
//
// public Type get(String name) {
// if (!this.types.containsKey(name)) {
// throw new RuntimeException("Name not found in module " + this.name + ": " + name);
// }
// return this.types.get(name);
// }
//
// /**
// * Unwraps a `TypeReferenceType` to return the inner type.
// */
// public Type getType(String name) {
// Type type = this.get(name);
// TypeReferenceType typeReferenceType = (TypeReferenceType)type;
// return typeReferenceType.getType();
// }
//
// public void put(String name, Type type) {
// this.types.put(name, type);
// }
//
// public void put(FunctionType type) {
// String name = type.getName();
// this.types.put(name, type);
// }
//
// @Override
// public Iterator<String> iterator() {
// return this.types.keySet().iterator();
// }
// }
// }
| import java.util.HashMap;
import java.util.Map;
import org.hummingbirdlang.types.Type;
import org.hummingbirdlang.types.realize.Index; | package org.hummingbirdlang.types.scope;
/**
* Source files are the top-level containers of types. Every source file
* corresponds to a source scope containing names referencing types.
*/
public class SourceScope extends AbstractScope implements Scope {
private final BuiltinScope parent; | // Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/realize/Index.java
// public final class Index {
// public static final String BUILTIN = "builtin";
//
// private final HashMap<String, Module> modules = new HashMap<>();
//
// private Index(BuiltinNodes builtins) {
// // Instantiate all the bootstrappable types.
// ArrayList<BootstrappableConcreteType> bootstrappableTypes = new ArrayList<>();
// bootstrappableTypes.add(new IntegerType());
// bootstrappableTypes.add(new StringType());
//
// Module builtin = new Module(Index.BUILTIN);
//
// // Bootstrap the types with the builtins (so that they can instantiate
// // methods with call targets).
// for (BootstrappableConcreteType type : bootstrappableTypes) {
// type.bootstrapBuiltins(builtins);
// builtin.put(type.getBootstrapName(), new TypeReferenceType(type));
// }
//
// // Add root builtin functions to the module.
// builtin.put(builtins.createFunctionType(
// new Type[]{
// new SumType(new Type[]{
// builtin.getType(IntegerType.BUILTIN_NAME),
// builtin.getType(StringType.BUILTIN_NAME),
// }),
// },
// NullType.SINGLETON,
// GlobalNodes.PrintlnNode.class
// ));
//
// // Finalize the bootstrapped types; now that all the types are in the
// // builtin module they can now reference each other.
// for (BootstrappableConcreteType type : bootstrappableTypes) {
// type.bootstrapTypes(builtin);
// }
//
// this.put(builtin);
// }
//
// public static Index bootstrap(BuiltinNodes builtins) {
// return new Index(builtins);
// }
//
// public Module get(String name) {
// return this.modules.get(name);
// }
//
// public Module getBuiltin() {
// return this.modules.get(Index.BUILTIN);
// }
//
// public Module put(Module module) {
// this.modules.put(module.getName(), module);
// return module;
// }
//
// /**
// * Resolves names in a module to type. Names are fully-qualified (eg.
// * "MyClass.MY_CONSTANT").
// */
// public final class Module implements Iterable<String> {
// private final String name;
// private final HashMap<String, Type> types = new HashMap<>();
//
// public Module(String name) {
// this.name = name;
// }
//
// public String getName() {
// return this.name;
// }
//
// public Type get(String name) {
// if (!this.types.containsKey(name)) {
// throw new RuntimeException("Name not found in module " + this.name + ": " + name);
// }
// return this.types.get(name);
// }
//
// /**
// * Unwraps a `TypeReferenceType` to return the inner type.
// */
// public Type getType(String name) {
// Type type = this.get(name);
// TypeReferenceType typeReferenceType = (TypeReferenceType)type;
// return typeReferenceType.getType();
// }
//
// public void put(String name, Type type) {
// this.types.put(name, type);
// }
//
// public void put(FunctionType type) {
// String name = type.getName();
// this.types.put(name, type);
// }
//
// @Override
// public Iterator<String> iterator() {
// return this.types.keySet().iterator();
// }
// }
// }
// Path: src/main/java/org/hummingbirdlang/types/scope/SourceScope.java
import java.util.HashMap;
import java.util.Map;
import org.hummingbirdlang.types.Type;
import org.hummingbirdlang.types.realize.Index;
package org.hummingbirdlang.types.scope;
/**
* Source files are the top-level containers of types. Every source file
* corresponds to a source scope containing names referencing types.
*/
public class SourceScope extends AbstractScope implements Scope {
private final BuiltinScope parent; | private Map<String, Type> types; |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/runtime/bindings/Bindings.java | // Path: src/main/java/org/hummingbirdlang/objects/Function.java
// public final class Function {
// private final FunctionType type;
// private final Bindings bindings;
// private final CallTarget callTarget;
// private final String name;
//
// public Function(FunctionType type, Bindings bindings) {
// this.type = type;
// this.bindings = bindings;
// this.callTarget = type.getCallTarget();
// this.name = type.getName();
// }
//
// public FunctionType getType() {
// return this.type;
// }
//
// public Bindings getBindings() {
// return this.bindings;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/FunctionType.java
// public final class FunctionType extends ConcreteType {
// private final Type[] parameterTypes;
// private final Type returnType;
// private final String name;
// private final CallTarget callTarget;
// // Scope where the function was declared.
// private Scope declarationScope;
// // Scope inside the function (ie. of its block).
// private Scope ownScope;
//
// public FunctionType(
// Type[] parameterTypes,
// Type returnType,
// String name,
// CallTarget callTarget
// ) {
// this.parameterTypes = parameterTypes;
// this.returnType = returnType;
// this.name = name;
// this.callTarget = callTarget;
// }
//
// public Type[] getParameterTypes() {
// return this.parameterTypes;
// }
//
// public Type getReturnType() {
// return this.returnType;
// }
//
// public String getName() {
// return this.name;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
//
// public Scope getOwnScope() {
// if (this.ownScope != null && !this.ownScope.isClosed()) {
// throw new RuntimeException("Scope not yet closed");
// }
// return this.ownScope;
// }
//
// public void setOwnScope(Scope scope) {
// if (this.ownScope != null) {
// throw new RuntimeException("Cannot re-set scope");
// }
// this.ownScope = scope;
// }
//
// public Scope getDeclarationScope() {
// if (this.declarationScope != null && !this.declarationScope.isClosed()) {
// throw new RuntimeException("Scope not yet closed");
// }
// return this.declarationScope;
// }
//
// public void setDeclarationScope(Scope declarationScope) {
// if (this.declarationScope != null) {
// throw new RuntimeException("Cannot re-set scope");
// }
// this.declarationScope = declarationScope;
// }
//
// @Override
// public Property getProperty(String name) throws PropertyNotFoundException {
// throw new PropertyNotFoundException("Not yet implemented");
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/scope/BuiltinScope.java
// public class BuiltinScope extends AbstractScope implements Scope, Iterable<String> {
// private final Map<String, Type> types;
//
// public BuiltinScope(Index index) {
// Map<String, Type> types = new HashMap<>();
// // Bootstrap the global types.
// Index.Module builtin = index.getBuiltin();
// for (String name : builtin) {
// types.put(name, builtin.get(name));
// }
// this.types = types;
// // You can't modify the builtin scope!
// this.close();
// }
//
// @Override
// public void accept(Resolution resolution) throws NameNotFoundException {
// resolution.pushScope(this);
// if (this.types.containsKey(resolution.getName())) {
// resolution.setType(this.types.get(resolution.getName()));
// } else {
// throw new NameNotFoundException("Name not found in BuiltinScope: " + resolution.getName());
// }
// }
//
// @Override
// public void setLocal(String name, Type type) {
// throw new RuntimeException("Cannot modify BuiltinScope: " + name);
// }
//
// @Override
// public Scope getParent() {
// throw new RuntimeException("Cannot getParent of BuiltinScope");
// }
//
// @Override
// public List<Resolution> getNonLocalResolutions() {
// throw new RuntimeException("Cannot getNonLocalResolutions of BuiltinScope");
// }
//
// @Override
// public Iterator<String> iterator() {
// return this.types.keySet().iterator();
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/scope/NameNotFoundException.java
// public class NameNotFoundException extends TypeException {
// public NameNotFoundException(String message) {
// super(message);
// }
// }
| import java.util.HashMap;
import java.util.Map;
import org.hummingbirdlang.objects.Function;
import org.hummingbirdlang.types.FunctionType;
import org.hummingbirdlang.types.Type;
import org.hummingbirdlang.types.scope.BuiltinScope;
import org.hummingbirdlang.types.scope.NameNotFoundException; | package org.hummingbirdlang.runtime.bindings;
// Holds references to values closed from an outer scope.
public final class Bindings {
private Map<String, Binding> bindings;
public Bindings() {
this.bindings = new HashMap<>();
}
| // Path: src/main/java/org/hummingbirdlang/objects/Function.java
// public final class Function {
// private final FunctionType type;
// private final Bindings bindings;
// private final CallTarget callTarget;
// private final String name;
//
// public Function(FunctionType type, Bindings bindings) {
// this.type = type;
// this.bindings = bindings;
// this.callTarget = type.getCallTarget();
// this.name = type.getName();
// }
//
// public FunctionType getType() {
// return this.type;
// }
//
// public Bindings getBindings() {
// return this.bindings;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/FunctionType.java
// public final class FunctionType extends ConcreteType {
// private final Type[] parameterTypes;
// private final Type returnType;
// private final String name;
// private final CallTarget callTarget;
// // Scope where the function was declared.
// private Scope declarationScope;
// // Scope inside the function (ie. of its block).
// private Scope ownScope;
//
// public FunctionType(
// Type[] parameterTypes,
// Type returnType,
// String name,
// CallTarget callTarget
// ) {
// this.parameterTypes = parameterTypes;
// this.returnType = returnType;
// this.name = name;
// this.callTarget = callTarget;
// }
//
// public Type[] getParameterTypes() {
// return this.parameterTypes;
// }
//
// public Type getReturnType() {
// return this.returnType;
// }
//
// public String getName() {
// return this.name;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
//
// public Scope getOwnScope() {
// if (this.ownScope != null && !this.ownScope.isClosed()) {
// throw new RuntimeException("Scope not yet closed");
// }
// return this.ownScope;
// }
//
// public void setOwnScope(Scope scope) {
// if (this.ownScope != null) {
// throw new RuntimeException("Cannot re-set scope");
// }
// this.ownScope = scope;
// }
//
// public Scope getDeclarationScope() {
// if (this.declarationScope != null && !this.declarationScope.isClosed()) {
// throw new RuntimeException("Scope not yet closed");
// }
// return this.declarationScope;
// }
//
// public void setDeclarationScope(Scope declarationScope) {
// if (this.declarationScope != null) {
// throw new RuntimeException("Cannot re-set scope");
// }
// this.declarationScope = declarationScope;
// }
//
// @Override
// public Property getProperty(String name) throws PropertyNotFoundException {
// throw new PropertyNotFoundException("Not yet implemented");
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/scope/BuiltinScope.java
// public class BuiltinScope extends AbstractScope implements Scope, Iterable<String> {
// private final Map<String, Type> types;
//
// public BuiltinScope(Index index) {
// Map<String, Type> types = new HashMap<>();
// // Bootstrap the global types.
// Index.Module builtin = index.getBuiltin();
// for (String name : builtin) {
// types.put(name, builtin.get(name));
// }
// this.types = types;
// // You can't modify the builtin scope!
// this.close();
// }
//
// @Override
// public void accept(Resolution resolution) throws NameNotFoundException {
// resolution.pushScope(this);
// if (this.types.containsKey(resolution.getName())) {
// resolution.setType(this.types.get(resolution.getName()));
// } else {
// throw new NameNotFoundException("Name not found in BuiltinScope: " + resolution.getName());
// }
// }
//
// @Override
// public void setLocal(String name, Type type) {
// throw new RuntimeException("Cannot modify BuiltinScope: " + name);
// }
//
// @Override
// public Scope getParent() {
// throw new RuntimeException("Cannot getParent of BuiltinScope");
// }
//
// @Override
// public List<Resolution> getNonLocalResolutions() {
// throw new RuntimeException("Cannot getNonLocalResolutions of BuiltinScope");
// }
//
// @Override
// public Iterator<String> iterator() {
// return this.types.keySet().iterator();
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/scope/NameNotFoundException.java
// public class NameNotFoundException extends TypeException {
// public NameNotFoundException(String message) {
// super(message);
// }
// }
// Path: src/main/java/org/hummingbirdlang/runtime/bindings/Bindings.java
import java.util.HashMap;
import java.util.Map;
import org.hummingbirdlang.objects.Function;
import org.hummingbirdlang.types.FunctionType;
import org.hummingbirdlang.types.Type;
import org.hummingbirdlang.types.scope.BuiltinScope;
import org.hummingbirdlang.types.scope.NameNotFoundException;
package org.hummingbirdlang.runtime.bindings;
// Holds references to values closed from an outer scope.
public final class Bindings {
private Map<String, Binding> bindings;
public Bindings() {
this.bindings = new HashMap<>();
}
| public Bindings(BuiltinScope builtinScope) throws NameNotFoundException { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/runtime/bindings/Bindings.java | // Path: src/main/java/org/hummingbirdlang/objects/Function.java
// public final class Function {
// private final FunctionType type;
// private final Bindings bindings;
// private final CallTarget callTarget;
// private final String name;
//
// public Function(FunctionType type, Bindings bindings) {
// this.type = type;
// this.bindings = bindings;
// this.callTarget = type.getCallTarget();
// this.name = type.getName();
// }
//
// public FunctionType getType() {
// return this.type;
// }
//
// public Bindings getBindings() {
// return this.bindings;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/FunctionType.java
// public final class FunctionType extends ConcreteType {
// private final Type[] parameterTypes;
// private final Type returnType;
// private final String name;
// private final CallTarget callTarget;
// // Scope where the function was declared.
// private Scope declarationScope;
// // Scope inside the function (ie. of its block).
// private Scope ownScope;
//
// public FunctionType(
// Type[] parameterTypes,
// Type returnType,
// String name,
// CallTarget callTarget
// ) {
// this.parameterTypes = parameterTypes;
// this.returnType = returnType;
// this.name = name;
// this.callTarget = callTarget;
// }
//
// public Type[] getParameterTypes() {
// return this.parameterTypes;
// }
//
// public Type getReturnType() {
// return this.returnType;
// }
//
// public String getName() {
// return this.name;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
//
// public Scope getOwnScope() {
// if (this.ownScope != null && !this.ownScope.isClosed()) {
// throw new RuntimeException("Scope not yet closed");
// }
// return this.ownScope;
// }
//
// public void setOwnScope(Scope scope) {
// if (this.ownScope != null) {
// throw new RuntimeException("Cannot re-set scope");
// }
// this.ownScope = scope;
// }
//
// public Scope getDeclarationScope() {
// if (this.declarationScope != null && !this.declarationScope.isClosed()) {
// throw new RuntimeException("Scope not yet closed");
// }
// return this.declarationScope;
// }
//
// public void setDeclarationScope(Scope declarationScope) {
// if (this.declarationScope != null) {
// throw new RuntimeException("Cannot re-set scope");
// }
// this.declarationScope = declarationScope;
// }
//
// @Override
// public Property getProperty(String name) throws PropertyNotFoundException {
// throw new PropertyNotFoundException("Not yet implemented");
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/scope/BuiltinScope.java
// public class BuiltinScope extends AbstractScope implements Scope, Iterable<String> {
// private final Map<String, Type> types;
//
// public BuiltinScope(Index index) {
// Map<String, Type> types = new HashMap<>();
// // Bootstrap the global types.
// Index.Module builtin = index.getBuiltin();
// for (String name : builtin) {
// types.put(name, builtin.get(name));
// }
// this.types = types;
// // You can't modify the builtin scope!
// this.close();
// }
//
// @Override
// public void accept(Resolution resolution) throws NameNotFoundException {
// resolution.pushScope(this);
// if (this.types.containsKey(resolution.getName())) {
// resolution.setType(this.types.get(resolution.getName()));
// } else {
// throw new NameNotFoundException("Name not found in BuiltinScope: " + resolution.getName());
// }
// }
//
// @Override
// public void setLocal(String name, Type type) {
// throw new RuntimeException("Cannot modify BuiltinScope: " + name);
// }
//
// @Override
// public Scope getParent() {
// throw new RuntimeException("Cannot getParent of BuiltinScope");
// }
//
// @Override
// public List<Resolution> getNonLocalResolutions() {
// throw new RuntimeException("Cannot getNonLocalResolutions of BuiltinScope");
// }
//
// @Override
// public Iterator<String> iterator() {
// return this.types.keySet().iterator();
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/scope/NameNotFoundException.java
// public class NameNotFoundException extends TypeException {
// public NameNotFoundException(String message) {
// super(message);
// }
// }
| import java.util.HashMap;
import java.util.Map;
import org.hummingbirdlang.objects.Function;
import org.hummingbirdlang.types.FunctionType;
import org.hummingbirdlang.types.Type;
import org.hummingbirdlang.types.scope.BuiltinScope;
import org.hummingbirdlang.types.scope.NameNotFoundException; | package org.hummingbirdlang.runtime.bindings;
// Holds references to values closed from an outer scope.
public final class Bindings {
private Map<String, Binding> bindings;
public Bindings() {
this.bindings = new HashMap<>();
}
| // Path: src/main/java/org/hummingbirdlang/objects/Function.java
// public final class Function {
// private final FunctionType type;
// private final Bindings bindings;
// private final CallTarget callTarget;
// private final String name;
//
// public Function(FunctionType type, Bindings bindings) {
// this.type = type;
// this.bindings = bindings;
// this.callTarget = type.getCallTarget();
// this.name = type.getName();
// }
//
// public FunctionType getType() {
// return this.type;
// }
//
// public Bindings getBindings() {
// return this.bindings;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/FunctionType.java
// public final class FunctionType extends ConcreteType {
// private final Type[] parameterTypes;
// private final Type returnType;
// private final String name;
// private final CallTarget callTarget;
// // Scope where the function was declared.
// private Scope declarationScope;
// // Scope inside the function (ie. of its block).
// private Scope ownScope;
//
// public FunctionType(
// Type[] parameterTypes,
// Type returnType,
// String name,
// CallTarget callTarget
// ) {
// this.parameterTypes = parameterTypes;
// this.returnType = returnType;
// this.name = name;
// this.callTarget = callTarget;
// }
//
// public Type[] getParameterTypes() {
// return this.parameterTypes;
// }
//
// public Type getReturnType() {
// return this.returnType;
// }
//
// public String getName() {
// return this.name;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
//
// public Scope getOwnScope() {
// if (this.ownScope != null && !this.ownScope.isClosed()) {
// throw new RuntimeException("Scope not yet closed");
// }
// return this.ownScope;
// }
//
// public void setOwnScope(Scope scope) {
// if (this.ownScope != null) {
// throw new RuntimeException("Cannot re-set scope");
// }
// this.ownScope = scope;
// }
//
// public Scope getDeclarationScope() {
// if (this.declarationScope != null && !this.declarationScope.isClosed()) {
// throw new RuntimeException("Scope not yet closed");
// }
// return this.declarationScope;
// }
//
// public void setDeclarationScope(Scope declarationScope) {
// if (this.declarationScope != null) {
// throw new RuntimeException("Cannot re-set scope");
// }
// this.declarationScope = declarationScope;
// }
//
// @Override
// public Property getProperty(String name) throws PropertyNotFoundException {
// throw new PropertyNotFoundException("Not yet implemented");
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/scope/BuiltinScope.java
// public class BuiltinScope extends AbstractScope implements Scope, Iterable<String> {
// private final Map<String, Type> types;
//
// public BuiltinScope(Index index) {
// Map<String, Type> types = new HashMap<>();
// // Bootstrap the global types.
// Index.Module builtin = index.getBuiltin();
// for (String name : builtin) {
// types.put(name, builtin.get(name));
// }
// this.types = types;
// // You can't modify the builtin scope!
// this.close();
// }
//
// @Override
// public void accept(Resolution resolution) throws NameNotFoundException {
// resolution.pushScope(this);
// if (this.types.containsKey(resolution.getName())) {
// resolution.setType(this.types.get(resolution.getName()));
// } else {
// throw new NameNotFoundException("Name not found in BuiltinScope: " + resolution.getName());
// }
// }
//
// @Override
// public void setLocal(String name, Type type) {
// throw new RuntimeException("Cannot modify BuiltinScope: " + name);
// }
//
// @Override
// public Scope getParent() {
// throw new RuntimeException("Cannot getParent of BuiltinScope");
// }
//
// @Override
// public List<Resolution> getNonLocalResolutions() {
// throw new RuntimeException("Cannot getNonLocalResolutions of BuiltinScope");
// }
//
// @Override
// public Iterator<String> iterator() {
// return this.types.keySet().iterator();
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/scope/NameNotFoundException.java
// public class NameNotFoundException extends TypeException {
// public NameNotFoundException(String message) {
// super(message);
// }
// }
// Path: src/main/java/org/hummingbirdlang/runtime/bindings/Bindings.java
import java.util.HashMap;
import java.util.Map;
import org.hummingbirdlang.objects.Function;
import org.hummingbirdlang.types.FunctionType;
import org.hummingbirdlang.types.Type;
import org.hummingbirdlang.types.scope.BuiltinScope;
import org.hummingbirdlang.types.scope.NameNotFoundException;
package org.hummingbirdlang.runtime.bindings;
// Holds references to values closed from an outer scope.
public final class Bindings {
private Map<String, Binding> bindings;
public Bindings() {
this.bindings = new HashMap<>();
}
| public Bindings(BuiltinScope builtinScope) throws NameNotFoundException { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/runtime/bindings/Bindings.java | // Path: src/main/java/org/hummingbirdlang/objects/Function.java
// public final class Function {
// private final FunctionType type;
// private final Bindings bindings;
// private final CallTarget callTarget;
// private final String name;
//
// public Function(FunctionType type, Bindings bindings) {
// this.type = type;
// this.bindings = bindings;
// this.callTarget = type.getCallTarget();
// this.name = type.getName();
// }
//
// public FunctionType getType() {
// return this.type;
// }
//
// public Bindings getBindings() {
// return this.bindings;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/FunctionType.java
// public final class FunctionType extends ConcreteType {
// private final Type[] parameterTypes;
// private final Type returnType;
// private final String name;
// private final CallTarget callTarget;
// // Scope where the function was declared.
// private Scope declarationScope;
// // Scope inside the function (ie. of its block).
// private Scope ownScope;
//
// public FunctionType(
// Type[] parameterTypes,
// Type returnType,
// String name,
// CallTarget callTarget
// ) {
// this.parameterTypes = parameterTypes;
// this.returnType = returnType;
// this.name = name;
// this.callTarget = callTarget;
// }
//
// public Type[] getParameterTypes() {
// return this.parameterTypes;
// }
//
// public Type getReturnType() {
// return this.returnType;
// }
//
// public String getName() {
// return this.name;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
//
// public Scope getOwnScope() {
// if (this.ownScope != null && !this.ownScope.isClosed()) {
// throw new RuntimeException("Scope not yet closed");
// }
// return this.ownScope;
// }
//
// public void setOwnScope(Scope scope) {
// if (this.ownScope != null) {
// throw new RuntimeException("Cannot re-set scope");
// }
// this.ownScope = scope;
// }
//
// public Scope getDeclarationScope() {
// if (this.declarationScope != null && !this.declarationScope.isClosed()) {
// throw new RuntimeException("Scope not yet closed");
// }
// return this.declarationScope;
// }
//
// public void setDeclarationScope(Scope declarationScope) {
// if (this.declarationScope != null) {
// throw new RuntimeException("Cannot re-set scope");
// }
// this.declarationScope = declarationScope;
// }
//
// @Override
// public Property getProperty(String name) throws PropertyNotFoundException {
// throw new PropertyNotFoundException("Not yet implemented");
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/scope/BuiltinScope.java
// public class BuiltinScope extends AbstractScope implements Scope, Iterable<String> {
// private final Map<String, Type> types;
//
// public BuiltinScope(Index index) {
// Map<String, Type> types = new HashMap<>();
// // Bootstrap the global types.
// Index.Module builtin = index.getBuiltin();
// for (String name : builtin) {
// types.put(name, builtin.get(name));
// }
// this.types = types;
// // You can't modify the builtin scope!
// this.close();
// }
//
// @Override
// public void accept(Resolution resolution) throws NameNotFoundException {
// resolution.pushScope(this);
// if (this.types.containsKey(resolution.getName())) {
// resolution.setType(this.types.get(resolution.getName()));
// } else {
// throw new NameNotFoundException("Name not found in BuiltinScope: " + resolution.getName());
// }
// }
//
// @Override
// public void setLocal(String name, Type type) {
// throw new RuntimeException("Cannot modify BuiltinScope: " + name);
// }
//
// @Override
// public Scope getParent() {
// throw new RuntimeException("Cannot getParent of BuiltinScope");
// }
//
// @Override
// public List<Resolution> getNonLocalResolutions() {
// throw new RuntimeException("Cannot getNonLocalResolutions of BuiltinScope");
// }
//
// @Override
// public Iterator<String> iterator() {
// return this.types.keySet().iterator();
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/scope/NameNotFoundException.java
// public class NameNotFoundException extends TypeException {
// public NameNotFoundException(String message) {
// super(message);
// }
// }
| import java.util.HashMap;
import java.util.Map;
import org.hummingbirdlang.objects.Function;
import org.hummingbirdlang.types.FunctionType;
import org.hummingbirdlang.types.Type;
import org.hummingbirdlang.types.scope.BuiltinScope;
import org.hummingbirdlang.types.scope.NameNotFoundException; | package org.hummingbirdlang.runtime.bindings;
// Holds references to values closed from an outer scope.
public final class Bindings {
private Map<String, Binding> bindings;
public Bindings() {
this.bindings = new HashMap<>();
}
public Bindings(BuiltinScope builtinScope) throws NameNotFoundException {
this();
// Bootstrap builtins into frame.
for (String name : builtinScope) { | // Path: src/main/java/org/hummingbirdlang/objects/Function.java
// public final class Function {
// private final FunctionType type;
// private final Bindings bindings;
// private final CallTarget callTarget;
// private final String name;
//
// public Function(FunctionType type, Bindings bindings) {
// this.type = type;
// this.bindings = bindings;
// this.callTarget = type.getCallTarget();
// this.name = type.getName();
// }
//
// public FunctionType getType() {
// return this.type;
// }
//
// public Bindings getBindings() {
// return this.bindings;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/FunctionType.java
// public final class FunctionType extends ConcreteType {
// private final Type[] parameterTypes;
// private final Type returnType;
// private final String name;
// private final CallTarget callTarget;
// // Scope where the function was declared.
// private Scope declarationScope;
// // Scope inside the function (ie. of its block).
// private Scope ownScope;
//
// public FunctionType(
// Type[] parameterTypes,
// Type returnType,
// String name,
// CallTarget callTarget
// ) {
// this.parameterTypes = parameterTypes;
// this.returnType = returnType;
// this.name = name;
// this.callTarget = callTarget;
// }
//
// public Type[] getParameterTypes() {
// return this.parameterTypes;
// }
//
// public Type getReturnType() {
// return this.returnType;
// }
//
// public String getName() {
// return this.name;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
//
// public Scope getOwnScope() {
// if (this.ownScope != null && !this.ownScope.isClosed()) {
// throw new RuntimeException("Scope not yet closed");
// }
// return this.ownScope;
// }
//
// public void setOwnScope(Scope scope) {
// if (this.ownScope != null) {
// throw new RuntimeException("Cannot re-set scope");
// }
// this.ownScope = scope;
// }
//
// public Scope getDeclarationScope() {
// if (this.declarationScope != null && !this.declarationScope.isClosed()) {
// throw new RuntimeException("Scope not yet closed");
// }
// return this.declarationScope;
// }
//
// public void setDeclarationScope(Scope declarationScope) {
// if (this.declarationScope != null) {
// throw new RuntimeException("Cannot re-set scope");
// }
// this.declarationScope = declarationScope;
// }
//
// @Override
// public Property getProperty(String name) throws PropertyNotFoundException {
// throw new PropertyNotFoundException("Not yet implemented");
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/scope/BuiltinScope.java
// public class BuiltinScope extends AbstractScope implements Scope, Iterable<String> {
// private final Map<String, Type> types;
//
// public BuiltinScope(Index index) {
// Map<String, Type> types = new HashMap<>();
// // Bootstrap the global types.
// Index.Module builtin = index.getBuiltin();
// for (String name : builtin) {
// types.put(name, builtin.get(name));
// }
// this.types = types;
// // You can't modify the builtin scope!
// this.close();
// }
//
// @Override
// public void accept(Resolution resolution) throws NameNotFoundException {
// resolution.pushScope(this);
// if (this.types.containsKey(resolution.getName())) {
// resolution.setType(this.types.get(resolution.getName()));
// } else {
// throw new NameNotFoundException("Name not found in BuiltinScope: " + resolution.getName());
// }
// }
//
// @Override
// public void setLocal(String name, Type type) {
// throw new RuntimeException("Cannot modify BuiltinScope: " + name);
// }
//
// @Override
// public Scope getParent() {
// throw new RuntimeException("Cannot getParent of BuiltinScope");
// }
//
// @Override
// public List<Resolution> getNonLocalResolutions() {
// throw new RuntimeException("Cannot getNonLocalResolutions of BuiltinScope");
// }
//
// @Override
// public Iterator<String> iterator() {
// return this.types.keySet().iterator();
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/scope/NameNotFoundException.java
// public class NameNotFoundException extends TypeException {
// public NameNotFoundException(String message) {
// super(message);
// }
// }
// Path: src/main/java/org/hummingbirdlang/runtime/bindings/Bindings.java
import java.util.HashMap;
import java.util.Map;
import org.hummingbirdlang.objects.Function;
import org.hummingbirdlang.types.FunctionType;
import org.hummingbirdlang.types.Type;
import org.hummingbirdlang.types.scope.BuiltinScope;
import org.hummingbirdlang.types.scope.NameNotFoundException;
package org.hummingbirdlang.runtime.bindings;
// Holds references to values closed from an outer scope.
public final class Bindings {
private Map<String, Binding> bindings;
public Bindings() {
this.bindings = new HashMap<>();
}
public Bindings(BuiltinScope builtinScope) throws NameNotFoundException {
this();
// Bootstrap builtins into frame.
for (String name : builtinScope) { | Type type = builtinScope.get(name); |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/runtime/bindings/Bindings.java | // Path: src/main/java/org/hummingbirdlang/objects/Function.java
// public final class Function {
// private final FunctionType type;
// private final Bindings bindings;
// private final CallTarget callTarget;
// private final String name;
//
// public Function(FunctionType type, Bindings bindings) {
// this.type = type;
// this.bindings = bindings;
// this.callTarget = type.getCallTarget();
// this.name = type.getName();
// }
//
// public FunctionType getType() {
// return this.type;
// }
//
// public Bindings getBindings() {
// return this.bindings;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/FunctionType.java
// public final class FunctionType extends ConcreteType {
// private final Type[] parameterTypes;
// private final Type returnType;
// private final String name;
// private final CallTarget callTarget;
// // Scope where the function was declared.
// private Scope declarationScope;
// // Scope inside the function (ie. of its block).
// private Scope ownScope;
//
// public FunctionType(
// Type[] parameterTypes,
// Type returnType,
// String name,
// CallTarget callTarget
// ) {
// this.parameterTypes = parameterTypes;
// this.returnType = returnType;
// this.name = name;
// this.callTarget = callTarget;
// }
//
// public Type[] getParameterTypes() {
// return this.parameterTypes;
// }
//
// public Type getReturnType() {
// return this.returnType;
// }
//
// public String getName() {
// return this.name;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
//
// public Scope getOwnScope() {
// if (this.ownScope != null && !this.ownScope.isClosed()) {
// throw new RuntimeException("Scope not yet closed");
// }
// return this.ownScope;
// }
//
// public void setOwnScope(Scope scope) {
// if (this.ownScope != null) {
// throw new RuntimeException("Cannot re-set scope");
// }
// this.ownScope = scope;
// }
//
// public Scope getDeclarationScope() {
// if (this.declarationScope != null && !this.declarationScope.isClosed()) {
// throw new RuntimeException("Scope not yet closed");
// }
// return this.declarationScope;
// }
//
// public void setDeclarationScope(Scope declarationScope) {
// if (this.declarationScope != null) {
// throw new RuntimeException("Cannot re-set scope");
// }
// this.declarationScope = declarationScope;
// }
//
// @Override
// public Property getProperty(String name) throws PropertyNotFoundException {
// throw new PropertyNotFoundException("Not yet implemented");
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/scope/BuiltinScope.java
// public class BuiltinScope extends AbstractScope implements Scope, Iterable<String> {
// private final Map<String, Type> types;
//
// public BuiltinScope(Index index) {
// Map<String, Type> types = new HashMap<>();
// // Bootstrap the global types.
// Index.Module builtin = index.getBuiltin();
// for (String name : builtin) {
// types.put(name, builtin.get(name));
// }
// this.types = types;
// // You can't modify the builtin scope!
// this.close();
// }
//
// @Override
// public void accept(Resolution resolution) throws NameNotFoundException {
// resolution.pushScope(this);
// if (this.types.containsKey(resolution.getName())) {
// resolution.setType(this.types.get(resolution.getName()));
// } else {
// throw new NameNotFoundException("Name not found in BuiltinScope: " + resolution.getName());
// }
// }
//
// @Override
// public void setLocal(String name, Type type) {
// throw new RuntimeException("Cannot modify BuiltinScope: " + name);
// }
//
// @Override
// public Scope getParent() {
// throw new RuntimeException("Cannot getParent of BuiltinScope");
// }
//
// @Override
// public List<Resolution> getNonLocalResolutions() {
// throw new RuntimeException("Cannot getNonLocalResolutions of BuiltinScope");
// }
//
// @Override
// public Iterator<String> iterator() {
// return this.types.keySet().iterator();
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/scope/NameNotFoundException.java
// public class NameNotFoundException extends TypeException {
// public NameNotFoundException(String message) {
// super(message);
// }
// }
| import java.util.HashMap;
import java.util.Map;
import org.hummingbirdlang.objects.Function;
import org.hummingbirdlang.types.FunctionType;
import org.hummingbirdlang.types.Type;
import org.hummingbirdlang.types.scope.BuiltinScope;
import org.hummingbirdlang.types.scope.NameNotFoundException; | package org.hummingbirdlang.runtime.bindings;
// Holds references to values closed from an outer scope.
public final class Bindings {
private Map<String, Binding> bindings;
public Bindings() {
this.bindings = new HashMap<>();
}
public Bindings(BuiltinScope builtinScope) throws NameNotFoundException {
this();
// Bootstrap builtins into frame.
for (String name : builtinScope) {
Type type = builtinScope.get(name); | // Path: src/main/java/org/hummingbirdlang/objects/Function.java
// public final class Function {
// private final FunctionType type;
// private final Bindings bindings;
// private final CallTarget callTarget;
// private final String name;
//
// public Function(FunctionType type, Bindings bindings) {
// this.type = type;
// this.bindings = bindings;
// this.callTarget = type.getCallTarget();
// this.name = type.getName();
// }
//
// public FunctionType getType() {
// return this.type;
// }
//
// public Bindings getBindings() {
// return this.bindings;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/FunctionType.java
// public final class FunctionType extends ConcreteType {
// private final Type[] parameterTypes;
// private final Type returnType;
// private final String name;
// private final CallTarget callTarget;
// // Scope where the function was declared.
// private Scope declarationScope;
// // Scope inside the function (ie. of its block).
// private Scope ownScope;
//
// public FunctionType(
// Type[] parameterTypes,
// Type returnType,
// String name,
// CallTarget callTarget
// ) {
// this.parameterTypes = parameterTypes;
// this.returnType = returnType;
// this.name = name;
// this.callTarget = callTarget;
// }
//
// public Type[] getParameterTypes() {
// return this.parameterTypes;
// }
//
// public Type getReturnType() {
// return this.returnType;
// }
//
// public String getName() {
// return this.name;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
//
// public Scope getOwnScope() {
// if (this.ownScope != null && !this.ownScope.isClosed()) {
// throw new RuntimeException("Scope not yet closed");
// }
// return this.ownScope;
// }
//
// public void setOwnScope(Scope scope) {
// if (this.ownScope != null) {
// throw new RuntimeException("Cannot re-set scope");
// }
// this.ownScope = scope;
// }
//
// public Scope getDeclarationScope() {
// if (this.declarationScope != null && !this.declarationScope.isClosed()) {
// throw new RuntimeException("Scope not yet closed");
// }
// return this.declarationScope;
// }
//
// public void setDeclarationScope(Scope declarationScope) {
// if (this.declarationScope != null) {
// throw new RuntimeException("Cannot re-set scope");
// }
// this.declarationScope = declarationScope;
// }
//
// @Override
// public Property getProperty(String name) throws PropertyNotFoundException {
// throw new PropertyNotFoundException("Not yet implemented");
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/scope/BuiltinScope.java
// public class BuiltinScope extends AbstractScope implements Scope, Iterable<String> {
// private final Map<String, Type> types;
//
// public BuiltinScope(Index index) {
// Map<String, Type> types = new HashMap<>();
// // Bootstrap the global types.
// Index.Module builtin = index.getBuiltin();
// for (String name : builtin) {
// types.put(name, builtin.get(name));
// }
// this.types = types;
// // You can't modify the builtin scope!
// this.close();
// }
//
// @Override
// public void accept(Resolution resolution) throws NameNotFoundException {
// resolution.pushScope(this);
// if (this.types.containsKey(resolution.getName())) {
// resolution.setType(this.types.get(resolution.getName()));
// } else {
// throw new NameNotFoundException("Name not found in BuiltinScope: " + resolution.getName());
// }
// }
//
// @Override
// public void setLocal(String name, Type type) {
// throw new RuntimeException("Cannot modify BuiltinScope: " + name);
// }
//
// @Override
// public Scope getParent() {
// throw new RuntimeException("Cannot getParent of BuiltinScope");
// }
//
// @Override
// public List<Resolution> getNonLocalResolutions() {
// throw new RuntimeException("Cannot getNonLocalResolutions of BuiltinScope");
// }
//
// @Override
// public Iterator<String> iterator() {
// return this.types.keySet().iterator();
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/scope/NameNotFoundException.java
// public class NameNotFoundException extends TypeException {
// public NameNotFoundException(String message) {
// super(message);
// }
// }
// Path: src/main/java/org/hummingbirdlang/runtime/bindings/Bindings.java
import java.util.HashMap;
import java.util.Map;
import org.hummingbirdlang.objects.Function;
import org.hummingbirdlang.types.FunctionType;
import org.hummingbirdlang.types.Type;
import org.hummingbirdlang.types.scope.BuiltinScope;
import org.hummingbirdlang.types.scope.NameNotFoundException;
package org.hummingbirdlang.runtime.bindings;
// Holds references to values closed from an outer scope.
public final class Bindings {
private Map<String, Binding> bindings;
public Bindings() {
this.bindings = new HashMap<>();
}
public Bindings(BuiltinScope builtinScope) throws NameNotFoundException {
this();
// Bootstrap builtins into frame.
for (String name : builtinScope) {
Type type = builtinScope.get(name); | if (type instanceof FunctionType) { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/runtime/bindings/Bindings.java | // Path: src/main/java/org/hummingbirdlang/objects/Function.java
// public final class Function {
// private final FunctionType type;
// private final Bindings bindings;
// private final CallTarget callTarget;
// private final String name;
//
// public Function(FunctionType type, Bindings bindings) {
// this.type = type;
// this.bindings = bindings;
// this.callTarget = type.getCallTarget();
// this.name = type.getName();
// }
//
// public FunctionType getType() {
// return this.type;
// }
//
// public Bindings getBindings() {
// return this.bindings;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/FunctionType.java
// public final class FunctionType extends ConcreteType {
// private final Type[] parameterTypes;
// private final Type returnType;
// private final String name;
// private final CallTarget callTarget;
// // Scope where the function was declared.
// private Scope declarationScope;
// // Scope inside the function (ie. of its block).
// private Scope ownScope;
//
// public FunctionType(
// Type[] parameterTypes,
// Type returnType,
// String name,
// CallTarget callTarget
// ) {
// this.parameterTypes = parameterTypes;
// this.returnType = returnType;
// this.name = name;
// this.callTarget = callTarget;
// }
//
// public Type[] getParameterTypes() {
// return this.parameterTypes;
// }
//
// public Type getReturnType() {
// return this.returnType;
// }
//
// public String getName() {
// return this.name;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
//
// public Scope getOwnScope() {
// if (this.ownScope != null && !this.ownScope.isClosed()) {
// throw new RuntimeException("Scope not yet closed");
// }
// return this.ownScope;
// }
//
// public void setOwnScope(Scope scope) {
// if (this.ownScope != null) {
// throw new RuntimeException("Cannot re-set scope");
// }
// this.ownScope = scope;
// }
//
// public Scope getDeclarationScope() {
// if (this.declarationScope != null && !this.declarationScope.isClosed()) {
// throw new RuntimeException("Scope not yet closed");
// }
// return this.declarationScope;
// }
//
// public void setDeclarationScope(Scope declarationScope) {
// if (this.declarationScope != null) {
// throw new RuntimeException("Cannot re-set scope");
// }
// this.declarationScope = declarationScope;
// }
//
// @Override
// public Property getProperty(String name) throws PropertyNotFoundException {
// throw new PropertyNotFoundException("Not yet implemented");
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/scope/BuiltinScope.java
// public class BuiltinScope extends AbstractScope implements Scope, Iterable<String> {
// private final Map<String, Type> types;
//
// public BuiltinScope(Index index) {
// Map<String, Type> types = new HashMap<>();
// // Bootstrap the global types.
// Index.Module builtin = index.getBuiltin();
// for (String name : builtin) {
// types.put(name, builtin.get(name));
// }
// this.types = types;
// // You can't modify the builtin scope!
// this.close();
// }
//
// @Override
// public void accept(Resolution resolution) throws NameNotFoundException {
// resolution.pushScope(this);
// if (this.types.containsKey(resolution.getName())) {
// resolution.setType(this.types.get(resolution.getName()));
// } else {
// throw new NameNotFoundException("Name not found in BuiltinScope: " + resolution.getName());
// }
// }
//
// @Override
// public void setLocal(String name, Type type) {
// throw new RuntimeException("Cannot modify BuiltinScope: " + name);
// }
//
// @Override
// public Scope getParent() {
// throw new RuntimeException("Cannot getParent of BuiltinScope");
// }
//
// @Override
// public List<Resolution> getNonLocalResolutions() {
// throw new RuntimeException("Cannot getNonLocalResolutions of BuiltinScope");
// }
//
// @Override
// public Iterator<String> iterator() {
// return this.types.keySet().iterator();
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/scope/NameNotFoundException.java
// public class NameNotFoundException extends TypeException {
// public NameNotFoundException(String message) {
// super(message);
// }
// }
| import java.util.HashMap;
import java.util.Map;
import org.hummingbirdlang.objects.Function;
import org.hummingbirdlang.types.FunctionType;
import org.hummingbirdlang.types.Type;
import org.hummingbirdlang.types.scope.BuiltinScope;
import org.hummingbirdlang.types.scope.NameNotFoundException; | package org.hummingbirdlang.runtime.bindings;
// Holds references to values closed from an outer scope.
public final class Bindings {
private Map<String, Binding> bindings;
public Bindings() {
this.bindings = new HashMap<>();
}
public Bindings(BuiltinScope builtinScope) throws NameNotFoundException {
this();
// Bootstrap builtins into frame.
for (String name : builtinScope) {
Type type = builtinScope.get(name);
if (type instanceof FunctionType) { | // Path: src/main/java/org/hummingbirdlang/objects/Function.java
// public final class Function {
// private final FunctionType type;
// private final Bindings bindings;
// private final CallTarget callTarget;
// private final String name;
//
// public Function(FunctionType type, Bindings bindings) {
// this.type = type;
// this.bindings = bindings;
// this.callTarget = type.getCallTarget();
// this.name = type.getName();
// }
//
// public FunctionType getType() {
// return this.type;
// }
//
// public Bindings getBindings() {
// return this.bindings;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/FunctionType.java
// public final class FunctionType extends ConcreteType {
// private final Type[] parameterTypes;
// private final Type returnType;
// private final String name;
// private final CallTarget callTarget;
// // Scope where the function was declared.
// private Scope declarationScope;
// // Scope inside the function (ie. of its block).
// private Scope ownScope;
//
// public FunctionType(
// Type[] parameterTypes,
// Type returnType,
// String name,
// CallTarget callTarget
// ) {
// this.parameterTypes = parameterTypes;
// this.returnType = returnType;
// this.name = name;
// this.callTarget = callTarget;
// }
//
// public Type[] getParameterTypes() {
// return this.parameterTypes;
// }
//
// public Type getReturnType() {
// return this.returnType;
// }
//
// public String getName() {
// return this.name;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
//
// public Scope getOwnScope() {
// if (this.ownScope != null && !this.ownScope.isClosed()) {
// throw new RuntimeException("Scope not yet closed");
// }
// return this.ownScope;
// }
//
// public void setOwnScope(Scope scope) {
// if (this.ownScope != null) {
// throw new RuntimeException("Cannot re-set scope");
// }
// this.ownScope = scope;
// }
//
// public Scope getDeclarationScope() {
// if (this.declarationScope != null && !this.declarationScope.isClosed()) {
// throw new RuntimeException("Scope not yet closed");
// }
// return this.declarationScope;
// }
//
// public void setDeclarationScope(Scope declarationScope) {
// if (this.declarationScope != null) {
// throw new RuntimeException("Cannot re-set scope");
// }
// this.declarationScope = declarationScope;
// }
//
// @Override
// public Property getProperty(String name) throws PropertyNotFoundException {
// throw new PropertyNotFoundException("Not yet implemented");
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/scope/BuiltinScope.java
// public class BuiltinScope extends AbstractScope implements Scope, Iterable<String> {
// private final Map<String, Type> types;
//
// public BuiltinScope(Index index) {
// Map<String, Type> types = new HashMap<>();
// // Bootstrap the global types.
// Index.Module builtin = index.getBuiltin();
// for (String name : builtin) {
// types.put(name, builtin.get(name));
// }
// this.types = types;
// // You can't modify the builtin scope!
// this.close();
// }
//
// @Override
// public void accept(Resolution resolution) throws NameNotFoundException {
// resolution.pushScope(this);
// if (this.types.containsKey(resolution.getName())) {
// resolution.setType(this.types.get(resolution.getName()));
// } else {
// throw new NameNotFoundException("Name not found in BuiltinScope: " + resolution.getName());
// }
// }
//
// @Override
// public void setLocal(String name, Type type) {
// throw new RuntimeException("Cannot modify BuiltinScope: " + name);
// }
//
// @Override
// public Scope getParent() {
// throw new RuntimeException("Cannot getParent of BuiltinScope");
// }
//
// @Override
// public List<Resolution> getNonLocalResolutions() {
// throw new RuntimeException("Cannot getNonLocalResolutions of BuiltinScope");
// }
//
// @Override
// public Iterator<String> iterator() {
// return this.types.keySet().iterator();
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/scope/NameNotFoundException.java
// public class NameNotFoundException extends TypeException {
// public NameNotFoundException(String message) {
// super(message);
// }
// }
// Path: src/main/java/org/hummingbirdlang/runtime/bindings/Bindings.java
import java.util.HashMap;
import java.util.Map;
import org.hummingbirdlang.objects.Function;
import org.hummingbirdlang.types.FunctionType;
import org.hummingbirdlang.types.Type;
import org.hummingbirdlang.types.scope.BuiltinScope;
import org.hummingbirdlang.types.scope.NameNotFoundException;
package org.hummingbirdlang.runtime.bindings;
// Holds references to values closed from an outer scope.
public final class Bindings {
private Map<String, Binding> bindings;
public Bindings() {
this.bindings = new HashMap<>();
}
public Bindings(BuiltinScope builtinScope) throws NameNotFoundException {
this();
// Bootstrap builtins into frame.
for (String name : builtinScope) {
Type type = builtinScope.get(name);
if (type instanceof FunctionType) { | Object function = new Function((FunctionType)type, null); |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/concrete/NullType.java | // Path: src/main/java/org/hummingbirdlang/types/ConcreteType.java
// public abstract class ConcreteType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
| import org.hummingbirdlang.types.ConcreteType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException; | package org.hummingbirdlang.types.concrete;
public final class NullType extends ConcreteType {
public static final NullType SINGLETON = new NullType();
private NullType() {
}
@Override | // Path: src/main/java/org/hummingbirdlang/types/ConcreteType.java
// public abstract class ConcreteType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
// Path: src/main/java/org/hummingbirdlang/types/concrete/NullType.java
import org.hummingbirdlang.types.ConcreteType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
package org.hummingbirdlang.types.concrete;
public final class NullType extends ConcreteType {
public static final NullType SINGLETON = new NullType();
private NullType() {
}
@Override | public Property getProperty(String name) throws PropertyNotFoundException { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/concrete/NullType.java | // Path: src/main/java/org/hummingbirdlang/types/ConcreteType.java
// public abstract class ConcreteType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
| import org.hummingbirdlang.types.ConcreteType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException; | package org.hummingbirdlang.types.concrete;
public final class NullType extends ConcreteType {
public static final NullType SINGLETON = new NullType();
private NullType() {
}
@Override | // Path: src/main/java/org/hummingbirdlang/types/ConcreteType.java
// public abstract class ConcreteType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
// Path: src/main/java/org/hummingbirdlang/types/concrete/NullType.java
import org.hummingbirdlang.types.ConcreteType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
package org.hummingbirdlang.types.concrete;
public final class NullType extends ConcreteType {
public static final NullType SINGLETON = new NullType();
private NullType() {
}
@Override | public Property getProperty(String name) throws PropertyNotFoundException { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/FunctionType.java | // Path: src/main/java/org/hummingbirdlang/types/scope/Scope.java
// public interface Scope {
// // Loose visitor pattern: scopes accept visitors; if they have the name the
// // resolution is looking for then they push themselves onto the path and
// // assign the type, otherwise they push themselves onto the path and
// // recurse to their parent scope.
// public void accept(Resolution resolution) throws NameNotFoundException;
//
// public Resolution resolve(String name) throws NameNotFoundException;
//
// // Get the type for the given name. Should create a `Resolution` and call
// // the `accept` recursion under the hood.
// public Type get(String name) throws NameNotFoundException;
//
// public void setLocal(String name, Type type);
//
// public Scope getParent();
//
// // Close the scope to prevent further modifications.
// public void close();
//
// // Returns whether or not the scope has been closed.
// public boolean isClosed();
//
// // Should only be called on closed scopes.
// public List<Resolution> getNonLocalResolutions();
// }
| import org.hummingbirdlang.types.scope.Scope;
import com.oracle.truffle.api.CallTarget; | package org.hummingbirdlang.types;
public final class FunctionType extends ConcreteType {
private final Type[] parameterTypes;
private final Type returnType;
private final String name;
private final CallTarget callTarget;
// Scope where the function was declared. | // Path: src/main/java/org/hummingbirdlang/types/scope/Scope.java
// public interface Scope {
// // Loose visitor pattern: scopes accept visitors; if they have the name the
// // resolution is looking for then they push themselves onto the path and
// // assign the type, otherwise they push themselves onto the path and
// // recurse to their parent scope.
// public void accept(Resolution resolution) throws NameNotFoundException;
//
// public Resolution resolve(String name) throws NameNotFoundException;
//
// // Get the type for the given name. Should create a `Resolution` and call
// // the `accept` recursion under the hood.
// public Type get(String name) throws NameNotFoundException;
//
// public void setLocal(String name, Type type);
//
// public Scope getParent();
//
// // Close the scope to prevent further modifications.
// public void close();
//
// // Returns whether or not the scope has been closed.
// public boolean isClosed();
//
// // Should only be called on closed scopes.
// public List<Resolution> getNonLocalResolutions();
// }
// Path: src/main/java/org/hummingbirdlang/types/FunctionType.java
import org.hummingbirdlang.types.scope.Scope;
import com.oracle.truffle.api.CallTarget;
package org.hummingbirdlang.types;
public final class FunctionType extends ConcreteType {
private final Type[] parameterTypes;
private final Type returnType;
private final String name;
private final CallTarget callTarget;
// Scope where the function was declared. | private Scope declarationScope; |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/nodes/builtins/IntegerNodes.java | // Path: src/main/java/org/hummingbirdlang/nodes/HBNode.java
// @NodeInfo(language = "HB")
// public abstract class HBNode extends Node {
// // Execute with a generic unspecialized return value.
// public abstract Object executeGeneric(VirtualFrame frame);
//
// // Execute without a return value.
// public void executeVoid(VirtualFrame frame) {
// executeGeneric(frame);
// }
// }
| import org.hummingbirdlang.nodes.HBNode;
import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.Specialization; | package org.hummingbirdlang.nodes.builtins;
@BuiltinClass("Integer")
public abstract class IntegerNodes {
@BuiltinMethod("toString") | // Path: src/main/java/org/hummingbirdlang/nodes/HBNode.java
// @NodeInfo(language = "HB")
// public abstract class HBNode extends Node {
// // Execute with a generic unspecialized return value.
// public abstract Object executeGeneric(VirtualFrame frame);
//
// // Execute without a return value.
// public void executeVoid(VirtualFrame frame) {
// executeGeneric(frame);
// }
// }
// Path: src/main/java/org/hummingbirdlang/nodes/builtins/IntegerNodes.java
import org.hummingbirdlang.nodes.HBNode;
import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.Specialization;
package org.hummingbirdlang.nodes.builtins;
@BuiltinClass("Integer")
public abstract class IntegerNodes {
@BuiltinMethod("toString") | @NodeChild(value = "self", type = HBNode.class) |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/scope/AbstractScope.java | // Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hummingbirdlang.types.Type; | package org.hummingbirdlang.types.scope;
/**
* Provides a cached implementation of `get`.
*/
abstract class AbstractScope implements Scope {
private boolean closed = false;
private Map<String, Resolution> cachedResolutions = new HashMap<>();
@Override
public Resolution resolve(String name) throws NameNotFoundException {
Resolution resolution;
if (this.cachedResolutions.containsKey(name)) {
resolution = this.cachedResolutions.get(name);
} else {
resolution = new Resolution(name);
this.accept(resolution);
this.cachedResolutions.put(name, resolution);
}
return resolution;
}
@Override | // Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
// Path: src/main/java/org/hummingbirdlang/types/scope/AbstractScope.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hummingbirdlang.types.Type;
package org.hummingbirdlang.types.scope;
/**
* Provides a cached implementation of `get`.
*/
abstract class AbstractScope implements Scope {
private boolean closed = false;
private Map<String, Resolution> cachedResolutions = new HashMap<>();
@Override
public Resolution resolve(String name) throws NameNotFoundException {
Resolution resolution;
if (this.cachedResolutions.containsKey(name)) {
resolution = this.cachedResolutions.get(name);
} else {
resolution = new Resolution(name);
this.accept(resolution);
this.cachedResolutions.put(name, resolution);
}
return resolution;
}
@Override | public Type get(String name) throws NameNotFoundException { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/scope/Resolution.java | // Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.hummingbirdlang.types.Type; | package org.hummingbirdlang.types.scope;
/**
* Resolved path to a name in a series of parent scope(s).
*/
public final class Resolution {
private String name; | // Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
// Path: src/main/java/org/hummingbirdlang/types/scope/Resolution.java
import java.util.ArrayList;
import java.util.List;
import org.hummingbirdlang.types.Type;
package org.hummingbirdlang.types.scope;
/**
* Resolved path to a name in a series of parent scope(s).
*/
public final class Resolution {
private String name; | private Type type; |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/composite/AnyType.java | // Path: src/main/java/org/hummingbirdlang/types/CompositeType.java
// public abstract class CompositeType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
| import org.hummingbirdlang.types.CompositeType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException; | package org.hummingbirdlang.types.composite;
public class AnyType extends CompositeType {
public AnyType() {
}
@Override | // Path: src/main/java/org/hummingbirdlang/types/CompositeType.java
// public abstract class CompositeType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
// Path: src/main/java/org/hummingbirdlang/types/composite/AnyType.java
import org.hummingbirdlang.types.CompositeType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
package org.hummingbirdlang.types.composite;
public class AnyType extends CompositeType {
public AnyType() {
}
@Override | public Property getProperty(String name) throws PropertyNotFoundException { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/composite/AnyType.java | // Path: src/main/java/org/hummingbirdlang/types/CompositeType.java
// public abstract class CompositeType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
| import org.hummingbirdlang.types.CompositeType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException; | package org.hummingbirdlang.types.composite;
public class AnyType extends CompositeType {
public AnyType() {
}
@Override | // Path: src/main/java/org/hummingbirdlang/types/CompositeType.java
// public abstract class CompositeType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
// Path: src/main/java/org/hummingbirdlang/types/composite/AnyType.java
import org.hummingbirdlang.types.CompositeType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
package org.hummingbirdlang.types.composite;
public class AnyType extends CompositeType {
public AnyType() {
}
@Override | public Property getProperty(String name) throws PropertyNotFoundException { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/nodes/builtins/GlobalNodes.java | // Path: src/main/java/org/hummingbirdlang/nodes/HBNode.java
// @NodeInfo(language = "HB")
// public abstract class HBNode extends Node {
// // Execute with a generic unspecialized return value.
// public abstract Object executeGeneric(VirtualFrame frame);
//
// // Execute without a return value.
// public void executeVoid(VirtualFrame frame) {
// executeGeneric(frame);
// }
// }
| import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.Specialization;
import org.hummingbirdlang.nodes.HBNode; | package org.hummingbirdlang.nodes.builtins;
@BuiltinClass("Global")
public abstract class GlobalNodes {
@BuiltinMethod(value = "println", usesThis = false, required = 1) | // Path: src/main/java/org/hummingbirdlang/nodes/HBNode.java
// @NodeInfo(language = "HB")
// public abstract class HBNode extends Node {
// // Execute with a generic unspecialized return value.
// public abstract Object executeGeneric(VirtualFrame frame);
//
// // Execute without a return value.
// public void executeVoid(VirtualFrame frame) {
// executeGeneric(frame);
// }
// }
// Path: src/main/java/org/hummingbirdlang/nodes/builtins/GlobalNodes.java
import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.Specialization;
import org.hummingbirdlang.nodes.HBNode;
package org.hummingbirdlang.nodes.builtins;
@BuiltinClass("Global")
public abstract class GlobalNodes {
@BuiltinMethod(value = "println", usesThis = false, required = 1) | @NodeChild(value = "object", type = HBNode.class) |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/composite/ClassType.java | // Path: src/main/java/org/hummingbirdlang/types/CompositeType.java
// public abstract class CompositeType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
| import org.hummingbirdlang.types.CompositeType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.Type; | package org.hummingbirdlang.types.composite;
public class ClassType extends CompositeType {
private String name; | // Path: src/main/java/org/hummingbirdlang/types/CompositeType.java
// public abstract class CompositeType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
// Path: src/main/java/org/hummingbirdlang/types/composite/ClassType.java
import org.hummingbirdlang.types.CompositeType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.Type;
package org.hummingbirdlang.types.composite;
public class ClassType extends CompositeType {
private String name; | private Type superClass; |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/composite/ClassType.java | // Path: src/main/java/org/hummingbirdlang/types/CompositeType.java
// public abstract class CompositeType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
| import org.hummingbirdlang.types.CompositeType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.Type; | package org.hummingbirdlang.types.composite;
public class ClassType extends CompositeType {
private String name;
private Type superClass;
public ClassType(String name, Type superClass) {
this.name = name;
this.superClass = superClass;
}
@Override | // Path: src/main/java/org/hummingbirdlang/types/CompositeType.java
// public abstract class CompositeType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
// Path: src/main/java/org/hummingbirdlang/types/composite/ClassType.java
import org.hummingbirdlang.types.CompositeType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.Type;
package org.hummingbirdlang.types.composite;
public class ClassType extends CompositeType {
private String name;
private Type superClass;
public ClassType(String name, Type superClass) {
this.name = name;
this.superClass = superClass;
}
@Override | public Property getProperty(String name) throws PropertyNotFoundException { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/composite/ClassType.java | // Path: src/main/java/org/hummingbirdlang/types/CompositeType.java
// public abstract class CompositeType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
| import org.hummingbirdlang.types.CompositeType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.Type; | package org.hummingbirdlang.types.composite;
public class ClassType extends CompositeType {
private String name;
private Type superClass;
public ClassType(String name, Type superClass) {
this.name = name;
this.superClass = superClass;
}
@Override | // Path: src/main/java/org/hummingbirdlang/types/CompositeType.java
// public abstract class CompositeType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
// Path: src/main/java/org/hummingbirdlang/types/composite/ClassType.java
import org.hummingbirdlang.types.CompositeType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.Type;
package org.hummingbirdlang.types.composite;
public class ClassType extends CompositeType {
private String name;
private Type superClass;
public ClassType(String name, Type superClass) {
this.name = name;
this.superClass = superClass;
}
@Override | public Property getProperty(String name) throws PropertyNotFoundException { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/concrete/MethodType.java | // Path: src/main/java/org/hummingbirdlang/nodes/HBFunctionRootNode.java
// public class HBFunctionRootNode extends RootNode implements InferenceVisitable {
// @Child private HBBlockNode bodyNode;
// private final SourceSection sourceSection;
//
// public HBFunctionRootNode(HBLanguage language, SourceSection sourceSection, FrameDescriptor frameDescriptor, HBBlockNode bodyNode) {
// super(language, frameDescriptor);
// this.sourceSection = sourceSection;
// this.bodyNode = bodyNode;
// }
//
// public void accept(InferenceVisitor visitor) throws TypeException {
// this.bodyNode.accept(visitor);
// }
//
// @Override
// public SourceSection getSourceSection() {
// return this.sourceSection;
// }
//
// @Override
// public Object execute(VirtualFrame frame) {
// try {
// createBindingsGetterAndSetterNodes().executeGeneric(frame);
// this.bodyNode.executeGeneric(frame);
// } catch (HBReturnException exception) {
// return exception.getReturnValue();
// }
// return null;
// }
//
// private SetBindingsNode createBindingsGetterAndSetterNodes() {
// return (
// SetBindingsNodeGen.create(
// GetFunctionBindingsNodeGen.create(
// new GetTargetNode()
// )
// )
// );
// }
//
// @Override
// public String toString() {
// return this.bodyNode.toString();
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/nodes/builtins/BuiltinNode.java
// @GenerateNodeFactory
// public abstract class BuiltinNode extends HBNode {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/ConcreteType.java
// public abstract class ConcreteType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
| import org.hummingbirdlang.nodes.HBFunctionRootNode;
import org.hummingbirdlang.nodes.builtins.BuiltinNode;
import org.hummingbirdlang.types.ConcreteType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.Type;
import com.oracle.truffle.api.CallTarget;
import com.oracle.truffle.api.Truffle;
import com.oracle.truffle.api.dsl.NodeFactory; | return this.receiverType;
}
public Type[] getParameterTypes() {
return this.parameterTypes;
}
public Type getReturnType() {
return this.returnType;
}
public String getName() {
return this.name;
}
public CallTarget getCallTarget() {
return this.callTarget;
}
/**
* Get a new method instance with a different return type. Methods are
* currently immutable, so this is used during bootstrap to create methods
* with an unknown return type and then overwrite them with ones with a
* real return type.
*/
public MethodType cloneWithReturnType(Type returnType) {
return new MethodType(this.receiverType, this.parameterTypes, returnType, this.name, this.callTarget);
}
@Override | // Path: src/main/java/org/hummingbirdlang/nodes/HBFunctionRootNode.java
// public class HBFunctionRootNode extends RootNode implements InferenceVisitable {
// @Child private HBBlockNode bodyNode;
// private final SourceSection sourceSection;
//
// public HBFunctionRootNode(HBLanguage language, SourceSection sourceSection, FrameDescriptor frameDescriptor, HBBlockNode bodyNode) {
// super(language, frameDescriptor);
// this.sourceSection = sourceSection;
// this.bodyNode = bodyNode;
// }
//
// public void accept(InferenceVisitor visitor) throws TypeException {
// this.bodyNode.accept(visitor);
// }
//
// @Override
// public SourceSection getSourceSection() {
// return this.sourceSection;
// }
//
// @Override
// public Object execute(VirtualFrame frame) {
// try {
// createBindingsGetterAndSetterNodes().executeGeneric(frame);
// this.bodyNode.executeGeneric(frame);
// } catch (HBReturnException exception) {
// return exception.getReturnValue();
// }
// return null;
// }
//
// private SetBindingsNode createBindingsGetterAndSetterNodes() {
// return (
// SetBindingsNodeGen.create(
// GetFunctionBindingsNodeGen.create(
// new GetTargetNode()
// )
// )
// );
// }
//
// @Override
// public String toString() {
// return this.bodyNode.toString();
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/nodes/builtins/BuiltinNode.java
// @GenerateNodeFactory
// public abstract class BuiltinNode extends HBNode {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/ConcreteType.java
// public abstract class ConcreteType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
// Path: src/main/java/org/hummingbirdlang/types/concrete/MethodType.java
import org.hummingbirdlang.nodes.HBFunctionRootNode;
import org.hummingbirdlang.nodes.builtins.BuiltinNode;
import org.hummingbirdlang.types.ConcreteType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.Type;
import com.oracle.truffle.api.CallTarget;
import com.oracle.truffle.api.Truffle;
import com.oracle.truffle.api.dsl.NodeFactory;
return this.receiverType;
}
public Type[] getParameterTypes() {
return this.parameterTypes;
}
public Type getReturnType() {
return this.returnType;
}
public String getName() {
return this.name;
}
public CallTarget getCallTarget() {
return this.callTarget;
}
/**
* Get a new method instance with a different return type. Methods are
* currently immutable, so this is used during bootstrap to create methods
* with an unknown return type and then overwrite them with ones with a
* real return type.
*/
public MethodType cloneWithReturnType(Type returnType) {
return new MethodType(this.receiverType, this.parameterTypes, returnType, this.name, this.callTarget);
}
@Override | public Property getProperty(String name) throws PropertyNotFoundException { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/concrete/MethodType.java | // Path: src/main/java/org/hummingbirdlang/nodes/HBFunctionRootNode.java
// public class HBFunctionRootNode extends RootNode implements InferenceVisitable {
// @Child private HBBlockNode bodyNode;
// private final SourceSection sourceSection;
//
// public HBFunctionRootNode(HBLanguage language, SourceSection sourceSection, FrameDescriptor frameDescriptor, HBBlockNode bodyNode) {
// super(language, frameDescriptor);
// this.sourceSection = sourceSection;
// this.bodyNode = bodyNode;
// }
//
// public void accept(InferenceVisitor visitor) throws TypeException {
// this.bodyNode.accept(visitor);
// }
//
// @Override
// public SourceSection getSourceSection() {
// return this.sourceSection;
// }
//
// @Override
// public Object execute(VirtualFrame frame) {
// try {
// createBindingsGetterAndSetterNodes().executeGeneric(frame);
// this.bodyNode.executeGeneric(frame);
// } catch (HBReturnException exception) {
// return exception.getReturnValue();
// }
// return null;
// }
//
// private SetBindingsNode createBindingsGetterAndSetterNodes() {
// return (
// SetBindingsNodeGen.create(
// GetFunctionBindingsNodeGen.create(
// new GetTargetNode()
// )
// )
// );
// }
//
// @Override
// public String toString() {
// return this.bodyNode.toString();
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/nodes/builtins/BuiltinNode.java
// @GenerateNodeFactory
// public abstract class BuiltinNode extends HBNode {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/ConcreteType.java
// public abstract class ConcreteType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
| import org.hummingbirdlang.nodes.HBFunctionRootNode;
import org.hummingbirdlang.nodes.builtins.BuiltinNode;
import org.hummingbirdlang.types.ConcreteType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.Type;
import com.oracle.truffle.api.CallTarget;
import com.oracle.truffle.api.Truffle;
import com.oracle.truffle.api.dsl.NodeFactory; | return this.receiverType;
}
public Type[] getParameterTypes() {
return this.parameterTypes;
}
public Type getReturnType() {
return this.returnType;
}
public String getName() {
return this.name;
}
public CallTarget getCallTarget() {
return this.callTarget;
}
/**
* Get a new method instance with a different return type. Methods are
* currently immutable, so this is used during bootstrap to create methods
* with an unknown return type and then overwrite them with ones with a
* real return type.
*/
public MethodType cloneWithReturnType(Type returnType) {
return new MethodType(this.receiverType, this.parameterTypes, returnType, this.name, this.callTarget);
}
@Override | // Path: src/main/java/org/hummingbirdlang/nodes/HBFunctionRootNode.java
// public class HBFunctionRootNode extends RootNode implements InferenceVisitable {
// @Child private HBBlockNode bodyNode;
// private final SourceSection sourceSection;
//
// public HBFunctionRootNode(HBLanguage language, SourceSection sourceSection, FrameDescriptor frameDescriptor, HBBlockNode bodyNode) {
// super(language, frameDescriptor);
// this.sourceSection = sourceSection;
// this.bodyNode = bodyNode;
// }
//
// public void accept(InferenceVisitor visitor) throws TypeException {
// this.bodyNode.accept(visitor);
// }
//
// @Override
// public SourceSection getSourceSection() {
// return this.sourceSection;
// }
//
// @Override
// public Object execute(VirtualFrame frame) {
// try {
// createBindingsGetterAndSetterNodes().executeGeneric(frame);
// this.bodyNode.executeGeneric(frame);
// } catch (HBReturnException exception) {
// return exception.getReturnValue();
// }
// return null;
// }
//
// private SetBindingsNode createBindingsGetterAndSetterNodes() {
// return (
// SetBindingsNodeGen.create(
// GetFunctionBindingsNodeGen.create(
// new GetTargetNode()
// )
// )
// );
// }
//
// @Override
// public String toString() {
// return this.bodyNode.toString();
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/nodes/builtins/BuiltinNode.java
// @GenerateNodeFactory
// public abstract class BuiltinNode extends HBNode {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/ConcreteType.java
// public abstract class ConcreteType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
// Path: src/main/java/org/hummingbirdlang/types/concrete/MethodType.java
import org.hummingbirdlang.nodes.HBFunctionRootNode;
import org.hummingbirdlang.nodes.builtins.BuiltinNode;
import org.hummingbirdlang.types.ConcreteType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.Type;
import com.oracle.truffle.api.CallTarget;
import com.oracle.truffle.api.Truffle;
import com.oracle.truffle.api.dsl.NodeFactory;
return this.receiverType;
}
public Type[] getParameterTypes() {
return this.parameterTypes;
}
public Type getReturnType() {
return this.returnType;
}
public String getName() {
return this.name;
}
public CallTarget getCallTarget() {
return this.callTarget;
}
/**
* Get a new method instance with a different return type. Methods are
* currently immutable, so this is used during bootstrap to create methods
* with an unknown return type and then overwrite them with ones with a
* real return type.
*/
public MethodType cloneWithReturnType(Type returnType) {
return new MethodType(this.receiverType, this.parameterTypes, returnType, this.name, this.callTarget);
}
@Override | public Property getProperty(String name) throws PropertyNotFoundException { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/nodes/HBFloatLiteralNode.java | // Path: src/main/java/org/hummingbirdlang/types/realize/InferenceVisitor.java
// public final class InferenceVisitor {
// private final Index index;
// private BuiltinScope builtinScope;
// private Scope currentScope;
//
// public InferenceVisitor(Index index) {
// this.builtinScope = new BuiltinScope(index);
// this.currentScope = new SourceScope(this.builtinScope);
// this.index = index;
// }
//
// private void pushScope() {
// Scope parentScope = this.currentScope;
// this.currentScope = new LocalScope(parentScope);
// }
//
// private void popScope() {
// this.currentScope = this.currentScope.getParent();
// }
//
// public void enter(HBSourceRootNode rootNode) {
// rootNode.setBuiltinScope(this.builtinScope);
// }
//
// public void leave(HBSourceRootNode rootNode) {
// // Current scope should be the `SourceScope`.
// if (!(this.currentScope instanceof SourceScope)) {
// throw new RuntimeException("Did not return to SourceScope");
// }
// this.currentScope.close();
// }
//
// public void enter(HBFunctionNode functionNode) {
// // TODO: Actually set and/or infer parameter and return types.
// FunctionType functionType = new FunctionType(
// new Type[]{},
// new UnknownType(),
// functionNode.getName(),
// functionNode.getCallTarget()
// );
// functionNode.setFunctionType(functionType);
// functionType.setDeclarationScope(this.currentScope);
// this.currentScope.setLocal(functionNode.getName(), functionType);
// this.pushScope();
// functionType.setOwnScope(this.currentScope);
// }
//
// public void leave(HBFunctionNode functionNode) {
// this.currentScope.close();
// this.popScope();
// }
//
// public void enter(HBBlockNode blockNode) {
// return;
// }
//
// public void leave(HBBlockNode blockNode) {
// return;
// }
//
// public void visit(HBAssignmentNode assignmentNode) throws TypeMismatchException {
// Type targetType = assignmentNode.getTargetNode().getType();
// Type valueType = assignmentNode.getValueNode().getType();
// targetType.assertEquals(valueType);
// }
//
// public void visit(HBCallNode callNode) throws TypeMismatchException {
// Type targetType = callNode.getTargetNode().getType();
//
// Type[] parameterTypes;
// Type returnType;
// if (targetType instanceof FunctionType) {
// FunctionType functionType = (FunctionType)targetType;
// parameterTypes = functionType.getParameterTypes();
// returnType = functionType.getReturnType();
// } else if (targetType instanceof MethodType) {
// MethodType methodType = (MethodType)targetType;
// parameterTypes = methodType.getParameterTypes();
// returnType = methodType.getReturnType();
// } else {
// throw new RuntimeException("Cannot call target of type: " + String.valueOf(targetType));
// }
//
// HBExpressionNode[] argumentNodes = callNode.getArgumentNodes();
// int expectedParameters = parameterTypes.length;
// int actualArguments = argumentNodes.length;
// if (expectedParameters != actualArguments) {
// throw new TypeMismatchException("Argument count mismatch: expected " + expectedParameters + " got " + actualArguments);
// }
//
// for (int index = 0; index < expectedParameters; index++) {
// Type parameterType = parameterTypes[index];
// Type argumentType = argumentNodes[index].getType();
// if (!parameterType.equals(argumentType)) {
// throw new TypeMismatchException("Argument " + (index + 1) + " mismatch: expected " + parameterType.toString() + " got " + String.valueOf(argumentType));
// }
// }
//
// callNode.setType(returnType);
// }
//
// public void visit(HBIdentifierNode identifierNode) throws NameNotFoundException {
// Resolution resolution = this.currentScope.resolve(identifierNode.getName());
// identifierNode.setResolution(resolution);
// }
//
// public void visit(HBIntegerLiteralNode literalNode) {
// literalNode.setType(this.getIntegerType());
// }
//
// public void visit(HBLetDeclarationNode letNode) {
// Type rightType = letNode.getRightNode().getType();
// String left = letNode.getLeft();
// this.currentScope.setLocal(left, rightType);
// }
//
// public void visit(HBLogicalAndNode andNode) {
// Type leftType = andNode.getLeftNode().getType();
// Type rightType = andNode.getRightNode().getType();
//
// Type resultType;
// if (!rightType.equals(BooleanType.SINGLETON)) {
// resultType = new SumType(new Type[]{ BooleanType.SINGLETON, rightType, });
// } else {
// resultType = BooleanType.SINGLETON;
// }
// andNode.setType(resultType);
// }
//
// public void visit(HBPropertyNode propertyNode) throws PropertyNotFoundException {
// Type targetType = propertyNode.getTargetNode().getType();
// Property property = targetType.getProperty(propertyNode.getPropertyName());
// propertyNode.setProperty(property);
// propertyNode.setType(property.getType());
// }
//
// public void visit(HBReturnNode returnNode) {
// Type returnType = NullType.SINGLETON;
// HBExpressionNode expressionNode = returnNode.getExpressionNode();
// if (expressionNode != null) {
// returnType = expressionNode.getType();
// }
// returnNode.setReturnType(returnType);
// }
//
// public void visit(HBStringLiteralNode literalNode) {
// literalNode.setType(this.getStringType());
// }
//
// private StringType getStringType() {
// Type type = this.index.getBuiltin().getType(StringType.BUILTIN_NAME);
// return (StringType)type;
// }
//
// private IntegerType getIntegerType() {
// Type type = this.index.getBuiltin().getType(IntegerType.BUILTIN_NAME);
// return (IntegerType)type;
// }
// }
| import com.oracle.truffle.api.frame.VirtualFrame;
import org.hummingbirdlang.types.realize.InferenceVisitor; | package org.hummingbirdlang.nodes;
public class HBFloatLiteralNode extends HBExpressionNode {
private final double value;
public HBFloatLiteralNode(String value) {
this.value = Double.parseDouble(value);
}
| // Path: src/main/java/org/hummingbirdlang/types/realize/InferenceVisitor.java
// public final class InferenceVisitor {
// private final Index index;
// private BuiltinScope builtinScope;
// private Scope currentScope;
//
// public InferenceVisitor(Index index) {
// this.builtinScope = new BuiltinScope(index);
// this.currentScope = new SourceScope(this.builtinScope);
// this.index = index;
// }
//
// private void pushScope() {
// Scope parentScope = this.currentScope;
// this.currentScope = new LocalScope(parentScope);
// }
//
// private void popScope() {
// this.currentScope = this.currentScope.getParent();
// }
//
// public void enter(HBSourceRootNode rootNode) {
// rootNode.setBuiltinScope(this.builtinScope);
// }
//
// public void leave(HBSourceRootNode rootNode) {
// // Current scope should be the `SourceScope`.
// if (!(this.currentScope instanceof SourceScope)) {
// throw new RuntimeException("Did not return to SourceScope");
// }
// this.currentScope.close();
// }
//
// public void enter(HBFunctionNode functionNode) {
// // TODO: Actually set and/or infer parameter and return types.
// FunctionType functionType = new FunctionType(
// new Type[]{},
// new UnknownType(),
// functionNode.getName(),
// functionNode.getCallTarget()
// );
// functionNode.setFunctionType(functionType);
// functionType.setDeclarationScope(this.currentScope);
// this.currentScope.setLocal(functionNode.getName(), functionType);
// this.pushScope();
// functionType.setOwnScope(this.currentScope);
// }
//
// public void leave(HBFunctionNode functionNode) {
// this.currentScope.close();
// this.popScope();
// }
//
// public void enter(HBBlockNode blockNode) {
// return;
// }
//
// public void leave(HBBlockNode blockNode) {
// return;
// }
//
// public void visit(HBAssignmentNode assignmentNode) throws TypeMismatchException {
// Type targetType = assignmentNode.getTargetNode().getType();
// Type valueType = assignmentNode.getValueNode().getType();
// targetType.assertEquals(valueType);
// }
//
// public void visit(HBCallNode callNode) throws TypeMismatchException {
// Type targetType = callNode.getTargetNode().getType();
//
// Type[] parameterTypes;
// Type returnType;
// if (targetType instanceof FunctionType) {
// FunctionType functionType = (FunctionType)targetType;
// parameterTypes = functionType.getParameterTypes();
// returnType = functionType.getReturnType();
// } else if (targetType instanceof MethodType) {
// MethodType methodType = (MethodType)targetType;
// parameterTypes = methodType.getParameterTypes();
// returnType = methodType.getReturnType();
// } else {
// throw new RuntimeException("Cannot call target of type: " + String.valueOf(targetType));
// }
//
// HBExpressionNode[] argumentNodes = callNode.getArgumentNodes();
// int expectedParameters = parameterTypes.length;
// int actualArguments = argumentNodes.length;
// if (expectedParameters != actualArguments) {
// throw new TypeMismatchException("Argument count mismatch: expected " + expectedParameters + " got " + actualArguments);
// }
//
// for (int index = 0; index < expectedParameters; index++) {
// Type parameterType = parameterTypes[index];
// Type argumentType = argumentNodes[index].getType();
// if (!parameterType.equals(argumentType)) {
// throw new TypeMismatchException("Argument " + (index + 1) + " mismatch: expected " + parameterType.toString() + " got " + String.valueOf(argumentType));
// }
// }
//
// callNode.setType(returnType);
// }
//
// public void visit(HBIdentifierNode identifierNode) throws NameNotFoundException {
// Resolution resolution = this.currentScope.resolve(identifierNode.getName());
// identifierNode.setResolution(resolution);
// }
//
// public void visit(HBIntegerLiteralNode literalNode) {
// literalNode.setType(this.getIntegerType());
// }
//
// public void visit(HBLetDeclarationNode letNode) {
// Type rightType = letNode.getRightNode().getType();
// String left = letNode.getLeft();
// this.currentScope.setLocal(left, rightType);
// }
//
// public void visit(HBLogicalAndNode andNode) {
// Type leftType = andNode.getLeftNode().getType();
// Type rightType = andNode.getRightNode().getType();
//
// Type resultType;
// if (!rightType.equals(BooleanType.SINGLETON)) {
// resultType = new SumType(new Type[]{ BooleanType.SINGLETON, rightType, });
// } else {
// resultType = BooleanType.SINGLETON;
// }
// andNode.setType(resultType);
// }
//
// public void visit(HBPropertyNode propertyNode) throws PropertyNotFoundException {
// Type targetType = propertyNode.getTargetNode().getType();
// Property property = targetType.getProperty(propertyNode.getPropertyName());
// propertyNode.setProperty(property);
// propertyNode.setType(property.getType());
// }
//
// public void visit(HBReturnNode returnNode) {
// Type returnType = NullType.SINGLETON;
// HBExpressionNode expressionNode = returnNode.getExpressionNode();
// if (expressionNode != null) {
// returnType = expressionNode.getType();
// }
// returnNode.setReturnType(returnType);
// }
//
// public void visit(HBStringLiteralNode literalNode) {
// literalNode.setType(this.getStringType());
// }
//
// private StringType getStringType() {
// Type type = this.index.getBuiltin().getType(StringType.BUILTIN_NAME);
// return (StringType)type;
// }
//
// private IntegerType getIntegerType() {
// Type type = this.index.getBuiltin().getType(IntegerType.BUILTIN_NAME);
// return (IntegerType)type;
// }
// }
// Path: src/main/java/org/hummingbirdlang/nodes/HBFloatLiteralNode.java
import com.oracle.truffle.api.frame.VirtualFrame;
import org.hummingbirdlang.types.realize.InferenceVisitor;
package org.hummingbirdlang.nodes;
public class HBFloatLiteralNode extends HBExpressionNode {
private final double value;
public HBFloatLiteralNode(String value) {
this.value = Double.parseDouble(value);
}
| public void accept(InferenceVisitor visitor) { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/scope/Scope.java | // Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
| import java.util.List;
import org.hummingbirdlang.types.Type; | package org.hummingbirdlang.types.scope;
public interface Scope {
// Loose visitor pattern: scopes accept visitors; if they have the name the
// resolution is looking for then they push themselves onto the path and
// assign the type, otherwise they push themselves onto the path and
// recurse to their parent scope.
public void accept(Resolution resolution) throws NameNotFoundException;
public Resolution resolve(String name) throws NameNotFoundException;
// Get the type for the given name. Should create a `Resolution` and call
// the `accept` recursion under the hood. | // Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
// Path: src/main/java/org/hummingbirdlang/types/scope/Scope.java
import java.util.List;
import org.hummingbirdlang.types.Type;
package org.hummingbirdlang.types.scope;
public interface Scope {
// Loose visitor pattern: scopes accept visitors; if they have the name the
// resolution is looking for then they push themselves onto the path and
// assign the type, otherwise they push themselves onto the path and
// recurse to their parent scope.
public void accept(Resolution resolution) throws NameNotFoundException;
public Resolution resolve(String name) throws NameNotFoundException;
// Get the type for the given name. Should create a `Resolution` and call
// the `accept` recursion under the hood. | public Type get(String name) throws NameNotFoundException; |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/parser/Parser.java | // Path: src/main/java/org/hummingbirdlang/HBLanguage.java
// @TruffleLanguage.Registration(name = "Hummingbird", version = "0.1", mimeType = HBLanguage.MIME_TYPE)
// public final class HBLanguage extends TruffleLanguage<HBContext> {
// public static final String MIME_TYPE = "application/x-hummingbird";
//
// public HBLanguage() {
// }
//
// @Override
// protected HBContext createContext(Env env) {
// BufferedReader in = new BufferedReader(new InputStreamReader(env.in()));
// PrintWriter out = new PrintWriter(env.out(), true);
// return new HBContext(env, in, out);
// }
//
// @Override
// protected CallTarget parse(ParsingRequest request) throws Exception {
// Source source = request.getSource();
// HBSourceRootNode program = ParserWrapper.parse(this, source);
//
// System.out.println(program.toString());
//
// // Bootstrap the builtin node targets and the builtin types in the
// // type-system.
// BuiltinNodes builtinNodes = BuiltinNodes.bootstrap(this);
// Index index = Index.bootstrap(builtinNodes);
//
// InferenceVisitor visitor = new InferenceVisitor(index);
// program.accept(visitor);
//
// return Truffle.getRuntime().createCallTarget(program);
// }
//
// // TODO: Fully remove this deprecated implementation.:
// //
// // @Override
// // protected CallTarget parse(Source source, Node node, String... argumentNames) throws Exception {
// // Object program = ParserWrapper.parse(source);
// // System.out.println(program.toString());
// // return null;
// // }
//
// // Called when some other language is seeking for a global symbol.
// @Override
// protected Object findExportedSymbol(HBContext context, String globalName, boolean onlyExplicit) {
// return null;
// }
//
// @Override
// protected Object getLanguageGlobal(HBContext context) {
// // Context is the highest level global.
// return context;
// }
//
// @Override
// protected boolean isObjectOfLanguage(Object object) {
// return false;
// }
// }
| import java.util.ArrayList;
import java.util.List;
import com.oracle.truffle.api.source.Source;
import org.hummingbirdlang.HBLanguage;
import org.hummingbirdlang.nodes.*; |
package org.hummingbirdlang.parser;
public class Parser {
public static final int _EOF = 0;
public static final int _identifier = 1;
public static final int _let = 2;
public static final int _var = 3;
public static final int _func = 4;
public static final int _return = 5;
public static final int _lf = 6;
public static final int _semicolon = 7;
public static final int _integerLiteral = 8;
public static final int _floatFractional = 9;
public static final int _stringLiteral = 10;
public static final int maxT = 24;
static final boolean _T = true;
static final boolean _x = false;
static final int minErrDist = 2;
public Token t; // last recognized token
public Token la; // lookahead token
int errDist = minErrDist;
public Scanner scanner;
public Errors errors; | // Path: src/main/java/org/hummingbirdlang/HBLanguage.java
// @TruffleLanguage.Registration(name = "Hummingbird", version = "0.1", mimeType = HBLanguage.MIME_TYPE)
// public final class HBLanguage extends TruffleLanguage<HBContext> {
// public static final String MIME_TYPE = "application/x-hummingbird";
//
// public HBLanguage() {
// }
//
// @Override
// protected HBContext createContext(Env env) {
// BufferedReader in = new BufferedReader(new InputStreamReader(env.in()));
// PrintWriter out = new PrintWriter(env.out(), true);
// return new HBContext(env, in, out);
// }
//
// @Override
// protected CallTarget parse(ParsingRequest request) throws Exception {
// Source source = request.getSource();
// HBSourceRootNode program = ParserWrapper.parse(this, source);
//
// System.out.println(program.toString());
//
// // Bootstrap the builtin node targets and the builtin types in the
// // type-system.
// BuiltinNodes builtinNodes = BuiltinNodes.bootstrap(this);
// Index index = Index.bootstrap(builtinNodes);
//
// InferenceVisitor visitor = new InferenceVisitor(index);
// program.accept(visitor);
//
// return Truffle.getRuntime().createCallTarget(program);
// }
//
// // TODO: Fully remove this deprecated implementation.:
// //
// // @Override
// // protected CallTarget parse(Source source, Node node, String... argumentNames) throws Exception {
// // Object program = ParserWrapper.parse(source);
// // System.out.println(program.toString());
// // return null;
// // }
//
// // Called when some other language is seeking for a global symbol.
// @Override
// protected Object findExportedSymbol(HBContext context, String globalName, boolean onlyExplicit) {
// return null;
// }
//
// @Override
// protected Object getLanguageGlobal(HBContext context) {
// // Context is the highest level global.
// return context;
// }
//
// @Override
// protected boolean isObjectOfLanguage(Object object) {
// return false;
// }
// }
// Path: src/main/java/org/hummingbirdlang/parser/Parser.java
import java.util.ArrayList;
import java.util.List;
import com.oracle.truffle.api.source.Source;
import org.hummingbirdlang.HBLanguage;
import org.hummingbirdlang.nodes.*;
package org.hummingbirdlang.parser;
public class Parser {
public static final int _EOF = 0;
public static final int _identifier = 1;
public static final int _let = 2;
public static final int _var = 3;
public static final int _func = 4;
public static final int _return = 5;
public static final int _lf = 6;
public static final int _semicolon = 7;
public static final int _integerLiteral = 8;
public static final int _floatFractional = 9;
public static final int _stringLiteral = 10;
public static final int maxT = 24;
static final boolean _T = true;
static final boolean _x = false;
static final int minErrDist = 2;
public Token t; // last recognized token
public Token la; // lookahead token
int errDist = minErrDist;
public Scanner scanner;
public Errors errors; | private HBLanguage language; |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/nodes/frames/GetFunctionBindingsNode.java | // Path: src/main/java/org/hummingbirdlang/nodes/HBNode.java
// @NodeInfo(language = "HB")
// public abstract class HBNode extends Node {
// // Execute with a generic unspecialized return value.
// public abstract Object executeGeneric(VirtualFrame frame);
//
// // Execute without a return value.
// public void executeVoid(VirtualFrame frame) {
// executeGeneric(frame);
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/objects/Function.java
// public final class Function {
// private final FunctionType type;
// private final Bindings bindings;
// private final CallTarget callTarget;
// private final String name;
//
// public Function(FunctionType type, Bindings bindings) {
// this.type = type;
// this.bindings = bindings;
// this.callTarget = type.getCallTarget();
// this.name = type.getName();
// }
//
// public FunctionType getType() {
// return this.type;
// }
//
// public Bindings getBindings() {
// return this.bindings;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
// }
| import org.hummingbirdlang.nodes.HBNode;
import org.hummingbirdlang.objects.Function;
import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.VirtualFrame; | package org.hummingbirdlang.nodes.frames;
// Extracts and returns the bindings from a function.
//
// Child node should return a `Function` when executed.
@NodeChild("node")
public abstract class GetFunctionBindingsNode extends HBNode {
@Specialization | // Path: src/main/java/org/hummingbirdlang/nodes/HBNode.java
// @NodeInfo(language = "HB")
// public abstract class HBNode extends Node {
// // Execute with a generic unspecialized return value.
// public abstract Object executeGeneric(VirtualFrame frame);
//
// // Execute without a return value.
// public void executeVoid(VirtualFrame frame) {
// executeGeneric(frame);
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/objects/Function.java
// public final class Function {
// private final FunctionType type;
// private final Bindings bindings;
// private final CallTarget callTarget;
// private final String name;
//
// public Function(FunctionType type, Bindings bindings) {
// this.type = type;
// this.bindings = bindings;
// this.callTarget = type.getCallTarget();
// this.name = type.getName();
// }
//
// public FunctionType getType() {
// return this.type;
// }
//
// public Bindings getBindings() {
// return this.bindings;
// }
//
// public CallTarget getCallTarget() {
// return this.callTarget;
// }
// }
// Path: src/main/java/org/hummingbirdlang/nodes/frames/GetFunctionBindingsNode.java
import org.hummingbirdlang.nodes.HBNode;
import org.hummingbirdlang.objects.Function;
import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.VirtualFrame;
package org.hummingbirdlang.nodes.frames;
// Extracts and returns the bindings from a function.
//
// Child node should return a `Function` when executed.
@NodeChild("node")
public abstract class GetFunctionBindingsNode extends HBNode {
@Specialization | public Object executeGet(VirtualFrame frame, Function function) { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/nodes/HBExpressionNode.java | // Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/realize/Typeable.java
// public interface Typeable {
// public void setType(Type type);
// }
| import com.oracle.truffle.api.CompilerDirectives.CompilationFinal;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.NodeInfo;
import org.hummingbirdlang.types.Type;
import org.hummingbirdlang.types.realize.Typeable; | package org.hummingbirdlang.nodes;
@NodeInfo(language = "HB")
public abstract class HBExpressionNode extends HBStatementNode implements Typeable { | // Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/realize/Typeable.java
// public interface Typeable {
// public void setType(Type type);
// }
// Path: src/main/java/org/hummingbirdlang/nodes/HBExpressionNode.java
import com.oracle.truffle.api.CompilerDirectives.CompilationFinal;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.NodeInfo;
import org.hummingbirdlang.types.Type;
import org.hummingbirdlang.types.realize.Typeable;
package org.hummingbirdlang.nodes;
@NodeInfo(language = "HB")
public abstract class HBExpressionNode extends HBStatementNode implements Typeable { | @CompilationFinal Type type; |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/nodes/HBLogicalOrNode.java | // Path: src/main/java/org/hummingbirdlang/types/realize/InferenceVisitor.java
// public final class InferenceVisitor {
// private final Index index;
// private BuiltinScope builtinScope;
// private Scope currentScope;
//
// public InferenceVisitor(Index index) {
// this.builtinScope = new BuiltinScope(index);
// this.currentScope = new SourceScope(this.builtinScope);
// this.index = index;
// }
//
// private void pushScope() {
// Scope parentScope = this.currentScope;
// this.currentScope = new LocalScope(parentScope);
// }
//
// private void popScope() {
// this.currentScope = this.currentScope.getParent();
// }
//
// public void enter(HBSourceRootNode rootNode) {
// rootNode.setBuiltinScope(this.builtinScope);
// }
//
// public void leave(HBSourceRootNode rootNode) {
// // Current scope should be the `SourceScope`.
// if (!(this.currentScope instanceof SourceScope)) {
// throw new RuntimeException("Did not return to SourceScope");
// }
// this.currentScope.close();
// }
//
// public void enter(HBFunctionNode functionNode) {
// // TODO: Actually set and/or infer parameter and return types.
// FunctionType functionType = new FunctionType(
// new Type[]{},
// new UnknownType(),
// functionNode.getName(),
// functionNode.getCallTarget()
// );
// functionNode.setFunctionType(functionType);
// functionType.setDeclarationScope(this.currentScope);
// this.currentScope.setLocal(functionNode.getName(), functionType);
// this.pushScope();
// functionType.setOwnScope(this.currentScope);
// }
//
// public void leave(HBFunctionNode functionNode) {
// this.currentScope.close();
// this.popScope();
// }
//
// public void enter(HBBlockNode blockNode) {
// return;
// }
//
// public void leave(HBBlockNode blockNode) {
// return;
// }
//
// public void visit(HBAssignmentNode assignmentNode) throws TypeMismatchException {
// Type targetType = assignmentNode.getTargetNode().getType();
// Type valueType = assignmentNode.getValueNode().getType();
// targetType.assertEquals(valueType);
// }
//
// public void visit(HBCallNode callNode) throws TypeMismatchException {
// Type targetType = callNode.getTargetNode().getType();
//
// Type[] parameterTypes;
// Type returnType;
// if (targetType instanceof FunctionType) {
// FunctionType functionType = (FunctionType)targetType;
// parameterTypes = functionType.getParameterTypes();
// returnType = functionType.getReturnType();
// } else if (targetType instanceof MethodType) {
// MethodType methodType = (MethodType)targetType;
// parameterTypes = methodType.getParameterTypes();
// returnType = methodType.getReturnType();
// } else {
// throw new RuntimeException("Cannot call target of type: " + String.valueOf(targetType));
// }
//
// HBExpressionNode[] argumentNodes = callNode.getArgumentNodes();
// int expectedParameters = parameterTypes.length;
// int actualArguments = argumentNodes.length;
// if (expectedParameters != actualArguments) {
// throw new TypeMismatchException("Argument count mismatch: expected " + expectedParameters + " got " + actualArguments);
// }
//
// for (int index = 0; index < expectedParameters; index++) {
// Type parameterType = parameterTypes[index];
// Type argumentType = argumentNodes[index].getType();
// if (!parameterType.equals(argumentType)) {
// throw new TypeMismatchException("Argument " + (index + 1) + " mismatch: expected " + parameterType.toString() + " got " + String.valueOf(argumentType));
// }
// }
//
// callNode.setType(returnType);
// }
//
// public void visit(HBIdentifierNode identifierNode) throws NameNotFoundException {
// Resolution resolution = this.currentScope.resolve(identifierNode.getName());
// identifierNode.setResolution(resolution);
// }
//
// public void visit(HBIntegerLiteralNode literalNode) {
// literalNode.setType(this.getIntegerType());
// }
//
// public void visit(HBLetDeclarationNode letNode) {
// Type rightType = letNode.getRightNode().getType();
// String left = letNode.getLeft();
// this.currentScope.setLocal(left, rightType);
// }
//
// public void visit(HBLogicalAndNode andNode) {
// Type leftType = andNode.getLeftNode().getType();
// Type rightType = andNode.getRightNode().getType();
//
// Type resultType;
// if (!rightType.equals(BooleanType.SINGLETON)) {
// resultType = new SumType(new Type[]{ BooleanType.SINGLETON, rightType, });
// } else {
// resultType = BooleanType.SINGLETON;
// }
// andNode.setType(resultType);
// }
//
// public void visit(HBPropertyNode propertyNode) throws PropertyNotFoundException {
// Type targetType = propertyNode.getTargetNode().getType();
// Property property = targetType.getProperty(propertyNode.getPropertyName());
// propertyNode.setProperty(property);
// propertyNode.setType(property.getType());
// }
//
// public void visit(HBReturnNode returnNode) {
// Type returnType = NullType.SINGLETON;
// HBExpressionNode expressionNode = returnNode.getExpressionNode();
// if (expressionNode != null) {
// returnType = expressionNode.getType();
// }
// returnNode.setReturnType(returnType);
// }
//
// public void visit(HBStringLiteralNode literalNode) {
// literalNode.setType(this.getStringType());
// }
//
// private StringType getStringType() {
// Type type = this.index.getBuiltin().getType(StringType.BUILTIN_NAME);
// return (StringType)type;
// }
//
// private IntegerType getIntegerType() {
// Type type = this.index.getBuiltin().getType(IntegerType.BUILTIN_NAME);
// return (IntegerType)type;
// }
// }
| import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.NodeInfo;
import org.hummingbirdlang.types.realize.InferenceVisitor; | package org.hummingbirdlang.nodes;
@NodeInfo(shortName = "||")
public class HBLogicalOrNode extends HBBinaryOperatorNode {
public HBLogicalOrNode(HBExpressionNode leftNode, HBExpressionNode rightNode) {
super(leftNode, rightNode);
}
| // Path: src/main/java/org/hummingbirdlang/types/realize/InferenceVisitor.java
// public final class InferenceVisitor {
// private final Index index;
// private BuiltinScope builtinScope;
// private Scope currentScope;
//
// public InferenceVisitor(Index index) {
// this.builtinScope = new BuiltinScope(index);
// this.currentScope = new SourceScope(this.builtinScope);
// this.index = index;
// }
//
// private void pushScope() {
// Scope parentScope = this.currentScope;
// this.currentScope = new LocalScope(parentScope);
// }
//
// private void popScope() {
// this.currentScope = this.currentScope.getParent();
// }
//
// public void enter(HBSourceRootNode rootNode) {
// rootNode.setBuiltinScope(this.builtinScope);
// }
//
// public void leave(HBSourceRootNode rootNode) {
// // Current scope should be the `SourceScope`.
// if (!(this.currentScope instanceof SourceScope)) {
// throw new RuntimeException("Did not return to SourceScope");
// }
// this.currentScope.close();
// }
//
// public void enter(HBFunctionNode functionNode) {
// // TODO: Actually set and/or infer parameter and return types.
// FunctionType functionType = new FunctionType(
// new Type[]{},
// new UnknownType(),
// functionNode.getName(),
// functionNode.getCallTarget()
// );
// functionNode.setFunctionType(functionType);
// functionType.setDeclarationScope(this.currentScope);
// this.currentScope.setLocal(functionNode.getName(), functionType);
// this.pushScope();
// functionType.setOwnScope(this.currentScope);
// }
//
// public void leave(HBFunctionNode functionNode) {
// this.currentScope.close();
// this.popScope();
// }
//
// public void enter(HBBlockNode blockNode) {
// return;
// }
//
// public void leave(HBBlockNode blockNode) {
// return;
// }
//
// public void visit(HBAssignmentNode assignmentNode) throws TypeMismatchException {
// Type targetType = assignmentNode.getTargetNode().getType();
// Type valueType = assignmentNode.getValueNode().getType();
// targetType.assertEquals(valueType);
// }
//
// public void visit(HBCallNode callNode) throws TypeMismatchException {
// Type targetType = callNode.getTargetNode().getType();
//
// Type[] parameterTypes;
// Type returnType;
// if (targetType instanceof FunctionType) {
// FunctionType functionType = (FunctionType)targetType;
// parameterTypes = functionType.getParameterTypes();
// returnType = functionType.getReturnType();
// } else if (targetType instanceof MethodType) {
// MethodType methodType = (MethodType)targetType;
// parameterTypes = methodType.getParameterTypes();
// returnType = methodType.getReturnType();
// } else {
// throw new RuntimeException("Cannot call target of type: " + String.valueOf(targetType));
// }
//
// HBExpressionNode[] argumentNodes = callNode.getArgumentNodes();
// int expectedParameters = parameterTypes.length;
// int actualArguments = argumentNodes.length;
// if (expectedParameters != actualArguments) {
// throw new TypeMismatchException("Argument count mismatch: expected " + expectedParameters + " got " + actualArguments);
// }
//
// for (int index = 0; index < expectedParameters; index++) {
// Type parameterType = parameterTypes[index];
// Type argumentType = argumentNodes[index].getType();
// if (!parameterType.equals(argumentType)) {
// throw new TypeMismatchException("Argument " + (index + 1) + " mismatch: expected " + parameterType.toString() + " got " + String.valueOf(argumentType));
// }
// }
//
// callNode.setType(returnType);
// }
//
// public void visit(HBIdentifierNode identifierNode) throws NameNotFoundException {
// Resolution resolution = this.currentScope.resolve(identifierNode.getName());
// identifierNode.setResolution(resolution);
// }
//
// public void visit(HBIntegerLiteralNode literalNode) {
// literalNode.setType(this.getIntegerType());
// }
//
// public void visit(HBLetDeclarationNode letNode) {
// Type rightType = letNode.getRightNode().getType();
// String left = letNode.getLeft();
// this.currentScope.setLocal(left, rightType);
// }
//
// public void visit(HBLogicalAndNode andNode) {
// Type leftType = andNode.getLeftNode().getType();
// Type rightType = andNode.getRightNode().getType();
//
// Type resultType;
// if (!rightType.equals(BooleanType.SINGLETON)) {
// resultType = new SumType(new Type[]{ BooleanType.SINGLETON, rightType, });
// } else {
// resultType = BooleanType.SINGLETON;
// }
// andNode.setType(resultType);
// }
//
// public void visit(HBPropertyNode propertyNode) throws PropertyNotFoundException {
// Type targetType = propertyNode.getTargetNode().getType();
// Property property = targetType.getProperty(propertyNode.getPropertyName());
// propertyNode.setProperty(property);
// propertyNode.setType(property.getType());
// }
//
// public void visit(HBReturnNode returnNode) {
// Type returnType = NullType.SINGLETON;
// HBExpressionNode expressionNode = returnNode.getExpressionNode();
// if (expressionNode != null) {
// returnType = expressionNode.getType();
// }
// returnNode.setReturnType(returnType);
// }
//
// public void visit(HBStringLiteralNode literalNode) {
// literalNode.setType(this.getStringType());
// }
//
// private StringType getStringType() {
// Type type = this.index.getBuiltin().getType(StringType.BUILTIN_NAME);
// return (StringType)type;
// }
//
// private IntegerType getIntegerType() {
// Type type = this.index.getBuiltin().getType(IntegerType.BUILTIN_NAME);
// return (IntegerType)type;
// }
// }
// Path: src/main/java/org/hummingbirdlang/nodes/HBLogicalOrNode.java
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.NodeInfo;
import org.hummingbirdlang.types.realize.InferenceVisitor;
package org.hummingbirdlang.nodes;
@NodeInfo(shortName = "||")
public class HBLogicalOrNode extends HBBinaryOperatorNode {
public HBLogicalOrNode(HBExpressionNode leftNode, HBExpressionNode rightNode) {
super(leftNode, rightNode);
}
| public void accept(InferenceVisitor visitor) { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/composite/TupleType.java | // Path: src/main/java/org/hummingbirdlang/types/CompositeType.java
// public abstract class CompositeType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
| import org.hummingbirdlang.types.CompositeType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.Type; | package org.hummingbirdlang.types.composite;
public class TupleType extends CompositeType {
private Type[] elements;
public TupleType(Type[] elements) {
this.elements = elements;
}
public static TupleType unit() {
return new TupleType(new Type[0]);
}
@Override | // Path: src/main/java/org/hummingbirdlang/types/CompositeType.java
// public abstract class CompositeType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
// Path: src/main/java/org/hummingbirdlang/types/composite/TupleType.java
import org.hummingbirdlang.types.CompositeType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.Type;
package org.hummingbirdlang.types.composite;
public class TupleType extends CompositeType {
private Type[] elements;
public TupleType(Type[] elements) {
this.elements = elements;
}
public static TupleType unit() {
return new TupleType(new Type[0]);
}
@Override | public Property getProperty(String name) throws PropertyNotFoundException { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/composite/TupleType.java | // Path: src/main/java/org/hummingbirdlang/types/CompositeType.java
// public abstract class CompositeType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
| import org.hummingbirdlang.types.CompositeType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.Type; | package org.hummingbirdlang.types.composite;
public class TupleType extends CompositeType {
private Type[] elements;
public TupleType(Type[] elements) {
this.elements = elements;
}
public static TupleType unit() {
return new TupleType(new Type[0]);
}
@Override | // Path: src/main/java/org/hummingbirdlang/types/CompositeType.java
// public abstract class CompositeType extends Type {
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Property.java
// public abstract class Property {
// // The type of the thing of which this is a property. For example in
// // `foo.bar` where `foo: Foo`, the parent would be the type `Foo`.
// private final Type parent;
// // The name of the property, in the previous example `bar`.
// private final String name;
//
// protected Property(Type parent, String name) {
// this.parent = parent;
// this.name = name;
// }
//
// // Returns the type of the property (right now just `MethodType`).
// public abstract Type getType();
// }
//
// Path: src/main/java/org/hummingbirdlang/types/PropertyNotFoundException.java
// public class PropertyNotFoundException extends TypeException {
// public PropertyNotFoundException(String message) {
// super(message);
// }
//
// public PropertyNotFoundException(Type type, String name) {
// super("Unknown property " + name + " of " + type.toString());
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/types/Type.java
// public abstract class Type {
// public abstract Property getProperty(String name) throws PropertyNotFoundException;
//
// public void assertEquals(Type otherType) throws TypeMismatchException {
// // Rudimentary pointer comparison by default.
// if (this != otherType) {
// throw new TypeMismatchException(this, otherType);
// }
// }
//
// /**
// * Returns whether or not this type is equal to another type.
// */
// public boolean equals(Type otherType) {
// try {
// this.assertEquals(otherType);
// } catch (TypeMismatchException exception) {
// return false;
// }
// return true;
// }
// }
// Path: src/main/java/org/hummingbirdlang/types/composite/TupleType.java
import org.hummingbirdlang.types.CompositeType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.Type;
package org.hummingbirdlang.types.composite;
public class TupleType extends CompositeType {
private Type[] elements;
public TupleType(Type[] elements) {
this.elements = elements;
}
public static TupleType unit() {
return new TupleType(new Type[0]);
}
@Override | public Property getProperty(String name) throws PropertyNotFoundException { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/types/realize/InferenceVisitable.java | // Path: src/main/java/org/hummingbirdlang/types/TypeException.java
// public abstract class TypeException extends Exception {
// protected TypeException(String message) {
// super(message);
// }
// }
| import org.hummingbirdlang.types.TypeException; | package org.hummingbirdlang.types.realize;
public interface InferenceVisitable {
public void accept(InferenceVisitor visitor) | // Path: src/main/java/org/hummingbirdlang/types/TypeException.java
// public abstract class TypeException extends Exception {
// protected TypeException(String message) {
// super(message);
// }
// }
// Path: src/main/java/org/hummingbirdlang/types/realize/InferenceVisitable.java
import org.hummingbirdlang.types.TypeException;
package org.hummingbirdlang.types.realize;
public interface InferenceVisitable {
public void accept(InferenceVisitor visitor) | throws TypeException; |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/nodes/frames/GetBindingsNode.java | // Path: src/main/java/org/hummingbirdlang/nodes/HBNode.java
// @NodeInfo(language = "HB")
// public abstract class HBNode extends Node {
// // Execute with a generic unspecialized return value.
// public abstract Object executeGeneric(VirtualFrame frame);
//
// // Execute without a return value.
// public void executeVoid(VirtualFrame frame) {
// executeGeneric(frame);
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/runtime/bindings/Bindings.java
// public final class Bindings {
// private Map<String, Binding> bindings;
//
// public Bindings() {
// this.bindings = new HashMap<>();
// }
//
// public Bindings(BuiltinScope builtinScope) throws NameNotFoundException {
// this();
// // Bootstrap builtins into frame.
// for (String name : builtinScope) {
// Type type = builtinScope.get(name);
// if (type instanceof FunctionType) {
// Object function = new Function((FunctionType)type, null);
// this.bindings.put(name, new BuiltinBinding(name, function));
// } else {
// System.out.println("Skipping bootstrap of builtin " + name + ": " + type.toString());
// }
// }
// }
//
// public boolean contains(String name) {
// return this.bindings.containsKey(name);
// }
//
// public Binding get(String name) {
// return this.bindings.get(name);
// }
//
// public Object getValue(String name) {
// Binding binding = this.get(name);
// return binding.get();
// }
//
// public void add(String name, Binding binding) {
// this.bindings.put(name, binding);
// }
//
// public static final BindingsIdentifier IDENTIFIER = new BindingsIdentifier();
//
// private static final class BindingsIdentifier {
// private BindingsIdentifier() {
// }
// }
// }
| import org.hummingbirdlang.nodes.HBNode;
import org.hummingbirdlang.runtime.bindings.Bindings;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.FrameDescriptor;
import com.oracle.truffle.api.frame.FrameSlot;
import com.oracle.truffle.api.frame.VirtualFrame; | package org.hummingbirdlang.nodes.frames;
public abstract class GetBindingsNode extends HBNode {
@Specialization | // Path: src/main/java/org/hummingbirdlang/nodes/HBNode.java
// @NodeInfo(language = "HB")
// public abstract class HBNode extends Node {
// // Execute with a generic unspecialized return value.
// public abstract Object executeGeneric(VirtualFrame frame);
//
// // Execute without a return value.
// public void executeVoid(VirtualFrame frame) {
// executeGeneric(frame);
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/runtime/bindings/Bindings.java
// public final class Bindings {
// private Map<String, Binding> bindings;
//
// public Bindings() {
// this.bindings = new HashMap<>();
// }
//
// public Bindings(BuiltinScope builtinScope) throws NameNotFoundException {
// this();
// // Bootstrap builtins into frame.
// for (String name : builtinScope) {
// Type type = builtinScope.get(name);
// if (type instanceof FunctionType) {
// Object function = new Function((FunctionType)type, null);
// this.bindings.put(name, new BuiltinBinding(name, function));
// } else {
// System.out.println("Skipping bootstrap of builtin " + name + ": " + type.toString());
// }
// }
// }
//
// public boolean contains(String name) {
// return this.bindings.containsKey(name);
// }
//
// public Binding get(String name) {
// return this.bindings.get(name);
// }
//
// public Object getValue(String name) {
// Binding binding = this.get(name);
// return binding.get();
// }
//
// public void add(String name, Binding binding) {
// this.bindings.put(name, binding);
// }
//
// public static final BindingsIdentifier IDENTIFIER = new BindingsIdentifier();
//
// private static final class BindingsIdentifier {
// private BindingsIdentifier() {
// }
// }
// }
// Path: src/main/java/org/hummingbirdlang/nodes/frames/GetBindingsNode.java
import org.hummingbirdlang.nodes.HBNode;
import org.hummingbirdlang.runtime.bindings.Bindings;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.FrameDescriptor;
import com.oracle.truffle.api.frame.FrameSlot;
import com.oracle.truffle.api.frame.VirtualFrame;
package org.hummingbirdlang.nodes.frames;
public abstract class GetBindingsNode extends HBNode {
@Specialization | public Bindings executeGetBindings(VirtualFrame frame) { |
dirk/hummingbird2 | src/main/java/org/hummingbirdlang/nodes/frames/GetNonLocalNode.java | // Path: src/main/java/org/hummingbirdlang/nodes/HBNode.java
// @NodeInfo(language = "HB")
// public abstract class HBNode extends Node {
// // Execute with a generic unspecialized return value.
// public abstract Object executeGeneric(VirtualFrame frame);
//
// // Execute without a return value.
// public void executeVoid(VirtualFrame frame) {
// executeGeneric(frame);
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/runtime/bindings/Bindings.java
// public final class Bindings {
// private Map<String, Binding> bindings;
//
// public Bindings() {
// this.bindings = new HashMap<>();
// }
//
// public Bindings(BuiltinScope builtinScope) throws NameNotFoundException {
// this();
// // Bootstrap builtins into frame.
// for (String name : builtinScope) {
// Type type = builtinScope.get(name);
// if (type instanceof FunctionType) {
// Object function = new Function((FunctionType)type, null);
// this.bindings.put(name, new BuiltinBinding(name, function));
// } else {
// System.out.println("Skipping bootstrap of builtin " + name + ": " + type.toString());
// }
// }
// }
//
// public boolean contains(String name) {
// return this.bindings.containsKey(name);
// }
//
// public Binding get(String name) {
// return this.bindings.get(name);
// }
//
// public Object getValue(String name) {
// Binding binding = this.get(name);
// return binding.get();
// }
//
// public void add(String name, Binding binding) {
// this.bindings.put(name, binding);
// }
//
// public static final BindingsIdentifier IDENTIFIER = new BindingsIdentifier();
//
// private static final class BindingsIdentifier {
// private BindingsIdentifier() {
// }
// }
// }
| import org.hummingbirdlang.nodes.HBNode;
import org.hummingbirdlang.runtime.bindings.Bindings;
import com.oracle.truffle.api.dsl.Cached;
import com.oracle.truffle.api.dsl.NodeField;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.VirtualFrame; | package org.hummingbirdlang.nodes.frames;
@NodeField(name = "name", type = String.class)
public abstract class GetNonLocalNode extends HBNode {
protected abstract String getName();
@Specialization
public Object getObject(
VirtualFrame frame,
@Cached("createGetBindingsNode()") GetBindingsNode getBindingsNode
) { | // Path: src/main/java/org/hummingbirdlang/nodes/HBNode.java
// @NodeInfo(language = "HB")
// public abstract class HBNode extends Node {
// // Execute with a generic unspecialized return value.
// public abstract Object executeGeneric(VirtualFrame frame);
//
// // Execute without a return value.
// public void executeVoid(VirtualFrame frame) {
// executeGeneric(frame);
// }
// }
//
// Path: src/main/java/org/hummingbirdlang/runtime/bindings/Bindings.java
// public final class Bindings {
// private Map<String, Binding> bindings;
//
// public Bindings() {
// this.bindings = new HashMap<>();
// }
//
// public Bindings(BuiltinScope builtinScope) throws NameNotFoundException {
// this();
// // Bootstrap builtins into frame.
// for (String name : builtinScope) {
// Type type = builtinScope.get(name);
// if (type instanceof FunctionType) {
// Object function = new Function((FunctionType)type, null);
// this.bindings.put(name, new BuiltinBinding(name, function));
// } else {
// System.out.println("Skipping bootstrap of builtin " + name + ": " + type.toString());
// }
// }
// }
//
// public boolean contains(String name) {
// return this.bindings.containsKey(name);
// }
//
// public Binding get(String name) {
// return this.bindings.get(name);
// }
//
// public Object getValue(String name) {
// Binding binding = this.get(name);
// return binding.get();
// }
//
// public void add(String name, Binding binding) {
// this.bindings.put(name, binding);
// }
//
// public static final BindingsIdentifier IDENTIFIER = new BindingsIdentifier();
//
// private static final class BindingsIdentifier {
// private BindingsIdentifier() {
// }
// }
// }
// Path: src/main/java/org/hummingbirdlang/nodes/frames/GetNonLocalNode.java
import org.hummingbirdlang.nodes.HBNode;
import org.hummingbirdlang.runtime.bindings.Bindings;
import com.oracle.truffle.api.dsl.Cached;
import com.oracle.truffle.api.dsl.NodeField;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.VirtualFrame;
package org.hummingbirdlang.nodes.frames;
@NodeField(name = "name", type = String.class)
public abstract class GetNonLocalNode extends HBNode {
protected abstract String getName();
@Specialization
public Object getObject(
VirtualFrame frame,
@Cached("createGetBindingsNode()") GetBindingsNode getBindingsNode
) { | Bindings bindings = (Bindings)getBindingsNode.executeGeneric(frame); |