answer
stringlengths 17
10.2M
|
|---|
package com.x1unix.avi;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PorterDuff.Mode;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.appcompat.*;
import android.support.v7.appcompat.BuildConfig;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.os.Bundle;
import android.view.Menu;
import android.support.v7.widget.SearchView;
import android.view.MenuItem;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.net.NetworkInfo;
import com.x1unix.avi.rest.*;
import com.x1unix.avi.model.*;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import com.x1unix.avi.adapter.MoviesAdapter;
import com.x1unix.avi.updateManager.OTAStateListener;
import com.x1unix.avi.updateManager.OTAUpdateChecker;
public class DashboardActivity extends AppCompatActivity {
private static final String TAG = DashboardActivity.class.getSimpleName();
private RecyclerView moviesSearchResultsView;
private KPApiInterface searchService = null;
private MenuItem searchItem;
private List<KPMovieItem> movies = new ArrayList<KPMovieItem>();
// Menu items
private MenuItem menuItemSettings;
private MenuItem menuItemHelp;
private Button connectionRefreshBtn;
// Activity states
private final int STATE_NO_INTERNET = 0;
private final int STATE_WELCOME = 1;
private final int STATE_ERROR = 2;
private final int STATE_LIST = 3;
// Views
private ProgressBar progress;
private LinearLayout[] states = {null, null, null, null};
private int views[] = new int[4];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Collect views
progress = (ProgressBar) findViewById(R.id.progressBar);
registerViews();
// Set progress color
progress.getIndeterminateDrawable().setColorFilter(getResources().getColor(R.color.colorAccentDark), Mode.MULTIPLY);
setProgressVisibility(true);
moviesSearchResultsView = (RecyclerView) findViewById(R.id.movies_recycler_view);
moviesSearchResultsView.setLayoutManager(new LinearLayoutManager(this));
// Set timer to try to check updates
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
String keyPropAutoUpdate = getResources()
.getString(R.string.avi_prop_autocheck_updates);
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
boolean allowAutoUpdateCheck = preferences.getBoolean(keyPropAutoUpdate, true);
if (allowAutoUpdateCheck) {
tryFindUpdates();
}
}
}, 1000);
}
private void registerViews() {
views[0] = R.id.no_internet_screen;
views[1] = R.id.wellcome_screen;
views[2] = R.id.error_message_screen;
views[3] = R.id.movies_results_screen;;
}
private LinearLayout getStateView(int stateId) {
if (states[stateId] == null) {
states[stateId] = (LinearLayout) findViewById(views[stateId]);
}
return states[stateId];
}
private void prepareView() {
setProgressVisibility(false);
boolean hasInet = isNetworkAvailable();
// For test purposes
if (BuildConfig.DEBUG) {
((ImageView) findViewById(R.id.testBtn)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent wmIntent = new Intent(getApplicationContext(), MoviePlayerActivity.class);
// Put id and title
wmIntent.putExtra("movieId", "770");
wmIntent.putExtra("movieTitle", "Ocean's Eleven");
// Kickstart player
startActivity(wmIntent);
}
});
}
setSearchVisibility(hasInet);
if (isNetworkAvailable()) {
setStateVisibility(true, STATE_WELCOME);
// Register RecyclerView event listener
moviesSearchResultsView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(),
moviesSearchResultsView,
new ClickListener() {
@Override
public void onClick(View view, int position) {
KPMovieItem movie = movies.get(position);
openMovie(movie);
}
@Override
public void onLongClick(View view, int position) {
}
}));
} else {
setStateVisibility(true, STATE_NO_INTERNET);
if (connectionRefreshBtn == null) {
connectionRefreshBtn = (Button) findViewById(R.id.connection_refresh_button);
connectionRefreshBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setStateVisibility(false, STATE_NO_INTERNET);
setProgressVisibility(true);
prepareView();
}
});
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
// Import menu items
menuItemSettings = (MenuItem) menu.findItem(R.id.menu_action_settings);
menuItemHelp = (MenuItem) menu.findItem(R.id.menu_action_help);
registerMenuItemsClickListeners();
// Retrieve the SearchView and plug it into SearchManager
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchItem = menu.findItem(R.id.action_search);
searchView.setQueryHint(getResources().getString(R.string.avi_search_hint));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener( ) {
@Override
public boolean onQueryTextChange( String newText ) {
// your text view here
// textView.setText(newText);
return false;
}
@Override
public boolean onQueryTextSubmit(String query) {
performSearch(query);
return false;
}
});
prepareView();
return true;
}
/**
* Load event handlers for menu buttons in paralel thread
*/
private void registerMenuItemsClickListeners() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
menuItemSettings.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Intent i = new Intent(getBaseContext(), SettingsActivity.class);
startActivity(i);
return false;
}
});
menuItemHelp.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Intent i = new Intent(getBaseContext(), SupportActivity.class);
startActivity(i);
return false;
}
});
}
}, 100);
}
private void setProgressVisibility(boolean ifVisible) {
progress.setVisibility(ifVisible ? View.VISIBLE : View.GONE);
}
private void setSearchVisibility(boolean ifVisible) {
searchItem.setVisible(ifVisible);
}
private void setStateVisibility(boolean ifVisible, int stateId) {
getStateView(stateId).setVisibility(ifVisible ? View.VISIBLE : View.GONE);
}
/**
* Is network available
* @return {boolean} Result
*/
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/**
* Search results response handler
*/
private Callback<KPSearchResponse> searchResultHandler = new Callback<KPSearchResponse>() {
@Override
public void onResponse(Call<KPSearchResponse>call, Response<KPSearchResponse> response) {
setProgressVisibility(false);
int statusCode = response.code();
KPSearchResponse resp = response.body();
if (resp != null) {
KPMovieSearchResult result = resp.getData();
if (result != null) {
movies = result.getResults();
MoviesAdapter adapter = new MoviesAdapter(movies,
R.layout.list_item_movie,
getApplicationContext(),
getResources().getConfiguration().locale);
if (adapter.getItemCount() > 0) {
setStateVisibility(true, STATE_LIST);
moviesSearchResultsView.setAdapter(adapter);
} else {
setStateVisibility(false, STATE_LIST);
setStateVisibility(true, STATE_WELCOME);
}
} else {
showNoItems();
}
} else {
showNoItems();
}
}
private void showNoItems() {
setStateVisibility(false, STATE_LIST);
setStateVisibility(true, STATE_WELCOME);
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.avi_no_items_msg), Toast.LENGTH_LONG)
.show();
}
@Override
public void onFailure(Call<KPSearchResponse>call, Throwable t) {
// Log error here since request failed
setProgressVisibility(false);
setStateVisibility(true, STATE_ERROR);
Log.e(TAG, "Failed to get items: " + t.toString());
Toast.makeText(getApplicationContext(), "Failed to perform search: " + t.toString(),
Toast.LENGTH_LONG).show();
}
};
/**
* Perform search
* @param query {String} Search query
*/
private void performSearch(String query) {
if (searchService == null) {
searchService = KPRestClient.getClient().create(KPApiInterface.class);
}
setStateVisibility(false, STATE_LIST);
setStateVisibility(false, STATE_NO_INTERNET);
setStateVisibility(false, STATE_ERROR);
setStateVisibility(false, STATE_WELCOME);
setProgressVisibility(true);
Call<KPSearchResponse> call = searchService.findMovies(query);
call.enqueue(searchResultHandler);
}
/**
* Open movie in player
* @param movie {KPMovieItem} movie instance
*/
private void openMovie(KPMovieItem movie) {
Intent mIntent = new Intent(this, MovieDetailsActivity.class);
// Put id and title
mIntent.putExtra("movieId", movie.getId());
mIntent.putExtra("movieTitle", movie.getTitle());
mIntent.putExtra("movieGenre", movie.getGenre());
mIntent.putExtra("movieRating", movie.getRating());
mIntent.putExtra("movieDescription", movie.getDescription());
// Kickstart player
Log.i("KPMovieOpen", "Trying to play movie [" + movie.getId() + "]");
startActivity(mIntent);
}
private void tryFindUpdates() {
if (isNetworkAvailable()) {
OTAUpdateChecker.checkForUpdates(new OTAStateListener() {
@Override
protected void onUpdateAvailable(AviSemVersion availableVersion, AviSemVersion currentVersion) {
showUpdateDialog(availableVersion);
}
});
}
}
private void showUpdateDialog(final AviSemVersion newVer) {
AlertDialog.Builder dialInstallUpdate = new AlertDialog.Builder(this);
String modConfimText = getResources().getString(R.string.upd_confirm);
modConfimText = modConfimText.replace("@version", newVer.toString());
dialInstallUpdate.setMessage(modConfimText);
dialInstallUpdate.setTitle(getResources().getString(R.string.upd_new_available))
.setCancelable(false)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(newVer.getApkUrl()));
startActivity(browserIntent);
dialog.cancel();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
dialInstallUpdate.show();
}
}
|
package de.bitshares_munich.utils;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Currency;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.TimeZone;
import de.bitshares_munich.smartcoinswallet.R;
public class Helper {
Gson gson;
private final static String TAG = "Helper";
public static final String MD5 = "MD5";
public static final String SHA256 = "SHA-256";
public static final ArrayList<String> languages = new ArrayList<>();
public static Map<String, String> countriesISOMap = new HashMap<String, String>();
public static void setLanguages() {
languages.clear();
languages.add("sq");
languages.add("ar");
languages.add("hy");
languages.add("bn");
languages.add("bs");
languages.add("bg");
languages.add("ca");
languages.add("zh-rCN");
languages.add("zh-rTW");
languages.add("hr");
languages.add("cs");
languages.add("da");
languages.add("nl");
languages.add("en");
languages.add("et");
languages.add("fa");
languages.add("fi");
languages.add("fr");
languages.add("de");
languages.add("el");
languages.add("he");
languages.add("hi");
languages.add("hu");
languages.add("id");
languages.add("it");
languages.add("ja");
languages.add("ko");
languages.add("lv");
languages.add("lt");
languages.add("ms");
languages.add("no");
languages.add("pl");
languages.add("pt-rPT");
languages.add("pt-rBR");
languages.add("ro");
languages.add("ru");
languages.add("sr");
languages.add("sk");
languages.add("sl");
languages.add("es");
languages.add("sv");
languages.add("th");
languages.add("tr");
languages.add("uk");
languages.add("vi");
}
public static ArrayList<String> getLanguages() {
setLanguages();
return languages;
}
public static final String hash(final String s, final String algorithm) {
try {
// Create MD5 or SHA-256 Hash
MessageDigest digest = MessageDigest
.getInstance(algorithm);
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuilder hexString = new StringBuilder();
for (byte aMessageDigest : messageDigest) {
String h = Integer.toHexString(0xFF & aMessageDigest);
while (h.length() < 2)
h = "0" + h;
hexString.append(h);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
/*
* Checks whether the preferences contains a preference.
*/
public static Boolean checkSharedPref(Context context, String key) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.contains(key);
}
public static void storeStringSharePref(Context context, String key, String value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value);
editor.apply();
}
public static int fetchIntSharePref(Context context, String key) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getInt(key, 0);
}
public static void storeIntSharePref(Context context, String key, int value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(key, value);
editor.apply();
}
public static String fetchStringSharePref(Context context, String key, String defaultValue) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, defaultValue);
}
public static String fetchStringSharePref(Context context, String key) {
return fetchStringSharePref(context, key, "");
}
public static void storeObjectSharePref(Context context, String key, Object object) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor prefsEditor = preferences.edit();
Gson gson = new Gson();
String json = gson.toJson(object);
prefsEditor.putString(key, json);
prefsEditor.commit();
}
public static String fetchObjectSharePref(Context context, String key) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor prefsEditor = preferences.edit();
return preferences.getString(key, "");
}
public static void storeBoolianSharePref(Context context, String key, Boolean value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.apply();
}
public static Boolean fetchBoolianSharePref(Context context, String key) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor prefsEditor = preferences.edit();
return preferences.getBoolean(key, false);
}
public static void storeLongSharePref(Context context, String key, long value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putLong(key, value);
editor.apply();
}
public static long fetchLongSharePref(Context context, String key) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor prefsEditor = preferences.edit();
return preferences.getLong(key, -1);
}
public static Boolean containKeySharePref(Context context, String key) {
Boolean isContainer = false;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (preferences.contains(key)) {
isContainer = true;
} else {
isContainer = false;
}
return isContainer;
}
public static String saveToInternalStorage(Context context, Bitmap bitmapImage) {
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath = new File(directory, "gravatar.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return directory.getAbsolutePath();
}
public static Bitmap loadImageFromStorage(Context context) {
Bitmap bitmap = null;
try {
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File f = new File(directory, "gravatar.jpg");
bitmap = BitmapFactory.decodeStream(new FileInputStream(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bitmap;
}
public static void initImageLoader(Context context) {
ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
config.threadPriority(Thread.NORM_PRIORITY - 2);
config.denyCacheImageMultipleSizesInMemory();
config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
config.tasksProcessingOrder(QueueProcessingType.LIFO);
config.writeDebugLogs(); // Remove for release app
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config.build());
}
public static ArrayList<String> getCountriesArray1() {
Locale[] locales = Locale.getAvailableLocales();
ArrayList<String> countries = new ArrayList<String>();
for (Locale locale : locales) {
String country = locale.getDisplayCountry();
Currency currency = Currency.getInstance(locale);
if (country.trim().length() > 0 && !countries.contains(country) && !country.trim().equals("World")) {
countries.add(country + " (" + currency + ")");
}
}
Collections.sort(countries);
setCountriesISOMap();
return countries;
}
public static ArrayList<String> getCountriesArray() {
String[] locales = Locale.getISOCountries();
ArrayList<String> countries = new ArrayList<String>();
for (String countryCode : locales) {
Locale locale = new Locale("", countryCode);
try {
Currency currency = Currency.getInstance(locale);
countries.add(locale.getDisplayCountry() + " (" + currency.getCurrencyCode() + ")");
} catch (Exception e) {
}
}
Collections.sort(countries);
return countries;
}
public static String getCountryCode(String spinnerText) {
String[] locales = Locale.getISOCountries();
ArrayList<String> countries = new ArrayList<>();
for (String countryCode : locales) {
Locale locale = new Locale("", countryCode);
try {
Currency currency = Currency.getInstance(locale);
String proposedSpinnerText = locale.getDisplayCountry() + " (" + currency.getCurrencyCode() + ")";
if (proposedSpinnerText.equals(spinnerText)) {
return countryCode;
}
} catch (Exception e) {
}
}
return "";
}
public static String getSpinnertextCountry(String countryCode) {
Locale locale = new Locale("", countryCode);
try {
Currency currency = Currency.getInstance(locale);
return locale.getDisplayCountry() + " (" + currency.getCurrencyCode() + ")";
} catch (Exception e) {
}
return "";
}
public static void setCountriesISOMap() {
String[] isoCountryCodes = Locale.getISOCountries();
for (int i = 0; i < isoCountryCodes.length; i++) {
Locale locale = new Locale("", isoCountryCodes[i]);
countriesISOMap.put(locale.getDisplayCountry(), isoCountryCodes[i]);
}
}
/*
* Setup app locale based on the language
*/
public static void setLocale(String lang, Resources res) {
Locale myLocale;
if (lang.equalsIgnoreCase("zh-rTW")) {
myLocale = Locale.TRADITIONAL_CHINESE;
} else if (lang.equalsIgnoreCase("zh-rCN") || lang.equalsIgnoreCase("zh")) {
myLocale = Locale.SIMPLIFIED_CHINESE;
} else if (lang.equalsIgnoreCase("pt-rBR") || lang.equalsIgnoreCase("pt")) {
myLocale = new Locale("pt", "BR");
} else if (lang.equalsIgnoreCase("pt-rPT")) {
myLocale = new Locale("pt", "PT");
} else {
myLocale = new Locale(lang);
}
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
}
/*
* Setup app Language LOCALE and app Language PREFERENCES.
*/
public static void setLanguage(Context context, String language) {
//Setup locale
Helper.setLocale(language, context.getResources());
//Setup Preferences
Helper.storeStringSharePref(context, context.getString(R.string.pref_language), language);
}
/*
* Setup app Country LOCALE and app Contry PREFERENCES.
*/
public static void setCountry(Context context, String country) {
//Setup locale
Locale myLocale;
myLocale = new Locale.Builder().setRegion(country).build();
DisplayMetrics dm = context.getResources().getDisplayMetrics();
Configuration conf = context.getResources().getConfiguration();
conf.locale = myLocale;
context.getResources().updateConfiguration(conf, dm);
//Setup Preferences
Helper.storeStringSharePref(context, context.getString(R.string.pref_country), country);
}
/**
* Get ISO 3166-1 alpha-2 country code for this device (or null if not available)
*
* @param context Context reference to get the TelephonyManager instance from
* @return country code or null
*/
public static String getDeviceCountry(Context context) {
try {
final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
final String simCountry = tm.getSimCountryIso();
if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
return simCountry.toLowerCase(Locale.US);
} else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
String networkCountry = tm.getNetworkCountryIso();
if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
return networkCountry.toLowerCase(Locale.US);
}
}
} catch (Exception e) {
}
return null;
}
public static String setLocaleNumberFormat(Locale locale, Number number) {
NumberFormat formatter = NumberFormat.getInstance(locale);
formatter.setMaximumFractionDigits(4);
String localeFormattedNumber = formatter.format(number);
return localeFormattedNumber;
}
public static char setDecimalSeparator(Locale locale) {
DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(locale);
return decimalFormatSymbols.getDecimalSeparator();
}
public static String convertDateToGMT(Date date, Context context) {
if (Helper.containKeySharePref(context, context.getString(R.string.date_time_zone))) {
String dtz = Helper.fetchStringSharePref(context, context.getString(R.string.date_time_zone));
TimeZone tz = TimeZone.getTimeZone(dtz);
SimpleDateFormat destFormat = new SimpleDateFormat("dd MMM");
destFormat.setTimeZone(tz);
String result = destFormat.format(date);
return result;
} else {
SimpleDateFormat destFormat = new SimpleDateFormat("dd MMM");
String result = destFormat.format(date);
return result;
}
}
public static String convertDateToGMTWithYear(Date date, Context context) {
if (Helper.containKeySharePref(context, context.getString(R.string.date_time_zone))) {
String dtz = Helper.fetchStringSharePref(context, context.getString(R.string.date_time_zone));
TimeZone tz = TimeZone.getTimeZone(dtz);
SimpleDateFormat destFormat = new SimpleDateFormat("dd MMM yy");
destFormat.setTimeZone(tz);
String result = destFormat.format(date);
return result;
} else {
SimpleDateFormat destFormat = new SimpleDateFormat("dd MMM yyy");
String result = destFormat.format(date);
return result;
}
}
public static String convertTimeToGMT(Date date, Context context) {
if (Helper.containKeySharePref(context, context.getString(R.string.date_time_zone))) {
String dtz = Helper.fetchStringSharePref(context, context.getString(R.string.date_time_zone));
TimeZone tz = TimeZone.getTimeZone(dtz);
SimpleDateFormat destFormat = new SimpleDateFormat("HH:mm");
destFormat.setTimeZone(tz);
String result = destFormat.format(date);
return result;
} else {
SimpleDateFormat destFormat = new SimpleDateFormat("HH:mm");
String result = destFormat.format(date);
return result;
}
}
public static String convertTimeZoneToGMT(Date date, Context context) {
if (Helper.containKeySharePref(context, context.getString(R.string.date_time_zone))) {
String dtz = Helper.fetchStringSharePref(context, context.getString(R.string.date_time_zone));
TimeZone tz = TimeZone.getTimeZone(dtz);
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(tz);
return calendar.getTimeZone().getDisplayName(false, TimeZone.SHORT);
} else {
return "UTC";
}
}
public static String convertTimeZoneToRegion(Date date, Context context) {
if (Helper.containKeySharePref(context, context.getString(R.string.date_time_zone))) {
String dtz = Helper.fetchStringSharePref(context, context.getString(R.string.date_time_zone));
TimeZone tz = TimeZone.getTimeZone(dtz);
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(tz);
String region = calendar.getTimeZone().getID();
String[] arr = region.split("/");
for (String ss : arr) {
if (ss.equals("Europe")) {
region = "CET";
}
}
return region;
} else {
return "UTC";
}
}
public static String getFadeCurrency(Context context) {
Boolean isFade = Helper.containKeySharePref(context, context.getString(R.string.pref_fade_currency));
if (isFade) {
String currency[] = Helper.fetchStringSharePref(context, context.getString(R.string.pref_fade_currency)).split(" ");
return currency[currency.length - 1].replace("(", "").replace(")", "");
} else {
return "EUR";
}
}
public static String getFadeCurrencySymbol(Context context) {
String currrencyCode = getFadeCurrency(context);
return Currency.getInstance(currrencyCode).getSymbol(Locale.ENGLISH);
}
public static String padString(String str) {
if (str == null || str.isEmpty()) {
return "0";
} else if (str.equals(".")) {
return "0.";
} else {
try {
return String.format(Locale.ENGLISH, "%.4f", Double.parseDouble(str));
} catch (Exception e) {
return null;
}
}
}
public static int convertDOubleToInt(Double value) {
String valueString = Double.toString(value);
for (int i = 0; i < valueString.length(); i++) {
if (valueString.charAt(i) == '.') {
valueString = valueString.substring(0, i);
break;
}
}
int valueInteger = Integer.parseInt(valueString);
return valueInteger;
}
public static boolean isRTL(Locale locale, String symbol) {
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(locale);
// We then tell our formatter to use this symbol.
DecimalFormatSymbols decimalFormatSymbols = ((java.text.DecimalFormat) currencyFormat).getDecimalFormatSymbols();
decimalFormatSymbols.setCurrencySymbol(symbol);
((java.text.DecimalFormat) currencyFormat).setDecimalFormatSymbols(decimalFormatSymbols);
String formattedtext = currencyFormat.format(100.0);
if (formattedtext.startsWith(symbol)) {
return false;
} else {
return true;
}
}
public static final String md5(final String s) {
final String MD5 = "MD5";
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest
.getInstance(MD5);
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuilder hexString = new StringBuilder();
for (byte aMessageDigest : messageDigest) {
String h = Integer.toHexString(0xFF & aMessageDigest);
while (h.length() < 2)
h = "0" + h;
hexString.append(h);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
public static NumberFormat newCurrencyFormat(Context context, Currency currency, Locale displayLocale) {
Log.d(TAG, "newCurrencyFormat");
NumberFormat retVal = NumberFormat.getCurrencyInstance(displayLocale);
retVal.setCurrency(currency);
//The default JDK handles situations well when the currency is the default currency for the locale
// if (currency.equals(Currency.getInstance(displayLocale))) {
// Log.d(TAG, "Let the JDK handle this");
// return retVal;
//otherwise we need to "fix things up" when displaying a non-native currency
if (retVal instanceof DecimalFormat) {
DecimalFormat decimalFormat = (DecimalFormat) retVal;
String correctedI18NSymbol = getCorrectedInternationalCurrencySymbol(context, currency, displayLocale);
if (correctedI18NSymbol != null) {
DecimalFormatSymbols dfs = decimalFormat.getDecimalFormatSymbols(); //this returns a clone of DFS
dfs.setInternationalCurrencySymbol(correctedI18NSymbol);
dfs.setCurrencySymbol(correctedI18NSymbol);
decimalFormat.setDecimalFormatSymbols(dfs);
}
}
return retVal;
}
private static String getCorrectedInternationalCurrencySymbol(Context context, Currency currency, Locale displayLocale) {
AssetsPropertyReader assetsReader = new AssetsPropertyReader(context);
Properties properties = assetsReader.getProperties("correctedI18nCurrencySymbols.properties");
if (properties.containsKey(currency.getCurrencyCode())) {
return properties.getProperty(currency.getCurrencyCode());
} else {
return currency.getCurrencyCode();
}
}
}
|
package edu.deanza.calendar.models;
import org.joda.time.LocalTime;
import org.json.JSONException;
import org.json.JSONObject;
public class Event {
protected String name, description, location;
protected LocalTime startTime, endTime;
// TODO: implement `categories` field
public Event() {}
public Event(String name, String description, String location, String startTime,
String endTime) {
this.name = name;
this.description = description;
this.location = location;
this.startTime = LocalTime.parse(startTime);
this.endTime = LocalTime.parse(endTime);
}
public static Event fromJson(JSONObject eventJson) {
Event e = new Event();
try {
e.name = eventJson.getString("name");
e.description = eventJson.getString("description");
e.location = eventJson.getString("location");
e.startTime = LocalTime.parse(eventJson.getString("start_time"));
e.endTime = LocalTime.parse(eventJson.getString("end_time"));
}
catch (JSONException ex) {
ex.printStackTrace();
return null;
}
return e;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getLocation() {
return location;
}
public LocalTime getStartTime() {
return startTime;
}
public LocalTime getEndTime() {
return endTime;
}
}
|
package org.stepic.droid.util;
import android.os.Build;
import android.support.annotation.ColorInt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.stepic.droid.configuration.Config;
import org.stepic.droid.notifications.model.Notification;
import java.util.List;
import java.util.Locale;
import kotlin.collections.CollectionsKt;
import timber.log.Timber;
public class HtmlHelper {
/**
* Trims trailing whitespace. Removes any of these characters:
* 0009, HORIZONTAL TABULATION
* 000A, LINE FEED
* 000B, VERTICAL TABULATION
* 000C, FORM FEED
* 000D, CARRIAGE RETURN
* 001C, FILE SEPARATOR
* 001D, GROUP SEPARATOR
* 001E, RECORD SEPARATOR
* 001F, UNIT SEPARATOR
*
* @return "" if source is null, otherwise string with all trailing whitespace removed
*/
public static CharSequence trimTrailingWhitespace(CharSequence source) {
if (source == null)
return "";
int i = source.length();
// loop back to the first non-whitespace character
while (--i >= 0 && Character.isWhitespace(source.charAt(i))) {
}
return source.subSequence(0, i + 1);
}
public static boolean isForWebView(@NotNull String text) {
//FIXME REMOVE <img>??? and make ImageGetter with simple textview
//TODO: REGEXP IS SLOWER
return text.contains("$")
|| text.contains("wysiwyg-")
|| text.contains("<h")
|| text.contains("\\[")
|| text.contains("<pre><code")
|| text.contains("kotlin-runnable")
|| text.contains("<img")
|| text.contains("<iframe")
|| text.contains("<audio");
}
public static boolean hasLaTeX(String textString) {
return textString.contains("$") || textString.contains("\\[");
}
private static boolean hasKotlinRunnableSample(String text) {
return text.contains("kotlin-runnable");
}
/**
* get meta value
*
* @param htmlText with meta tags
* @param metaKey meta key of 'name' attribute in meta tag
* @return value of 'content' attribute in tag meta with 'name' == metaKey
*/
@Nullable
public static String getValueOfMetaOrNull(String htmlText, String metaKey) {
Document document = Jsoup.parse(htmlText);
Elements elements = document.select("meta");
try {
return elements.attr("name", metaKey).last().attr("content"); //WTF? first is csrf param, but jsoup can't handle
} catch (Exception ex) {
return "";
}
}
@Nullable
public static Long parseCourseIdFromNotification(@NotNull Notification notification) {
String htmlRaw = notification.getHtmlText();
if (htmlRaw == null) return null;
return parseCourseIdFromNotification(htmlRaw);
}
@Nullable
public static Long parseIdFromSlug(String slug) {
Long id = null;
try {
id = Long.parseLong(slug);
} catch (NumberFormatException ignored) {
//often it is not number then it is "Some-Name-idNum" or just "-idNum"
}
if (id != null) {
//if, for example, -432 -> 432
return Math.abs(id);
}
int indexOfLastDash = slug.lastIndexOf("-");
if (indexOfLastDash < 0)
return null;
try {
String number = slug.substring(indexOfLastDash + 1, slug.length());
id = Long.parseLong(number);
} catch (NumberFormatException | IndexOutOfBoundsException ignored) {
}
return id;
}
private final static String syllabusModulePrefix = "syllabus?module=";
public static Integer parseModulePositionFromNotification(String htmlRaw) {
int indexOfStart = htmlRaw.indexOf(syllabusModulePrefix);
if (indexOfStart < 0) return null;
String begin = htmlRaw.substring(indexOfStart + syllabusModulePrefix.length());
int end = begin.indexOf("\"");
String substring = begin.substring(0, end);
try {
return Integer.parseInt(substring);
} catch (Exception exception) {
return null;
}
}
private static Long parseCourseIdFromNotification(String htmlRaw) {
int start = htmlRaw.indexOf('<');
int end = htmlRaw.indexOf('>');
if (start == -1 || end == -1) return null;
String substring = htmlRaw.substring(start, end);
String[] resultOfSplit = substring.split("-");
if (resultOfSplit.length > 0) {
String numb = resultOfSplit[resultOfSplit.length - 1];
StringBuilder n = new StringBuilder();
for (int i = 0; i < numb.length(); i++) {
if (Character.isDigit(numb.charAt(i))) {
n.append(numb.charAt(i));
}
}
if (n.length() > 0)
return Long.parseLong(n.toString());
return null;
}
return null;
}
private static String getStyle(float fontSize, @Nullable String fontPath, @ColorInt int textColorHighlight) {
final String fontStyle;
if (fontPath == null) {
fontStyle = String.format(Locale.US, DefaultFontStyle, fontSize); // US locale to format floats with '.' instead of ','
} else {
fontStyle = String.format(Locale.US, CustomFontStyle, fontPath, fontSize);
}
final String selectionColorStyle = String.format(Locale.getDefault(), SelectionColorStyle, 0xFFFFFF & textColorHighlight);
return fontStyle + selectionColorStyle;
}
private static String buildPage(CharSequence body, List<String> additionalScripts, float fontSize, String fontPath, @ColorInt int textColorHighlight, int widthPx, String baseUrl) {
if (hasKotlinRunnableSample(body.toString())) {
additionalScripts.add(KotlinRunnableSamplesScript);
}
String scripts = CollectionsKt.joinToString(additionalScripts, "", "", "", -1, "", null);
String preBody = String.format(Locale.getDefault(), PRE_BODY, scripts, getStyle(fontSize, fontPath, textColorHighlight), widthPx, baseUrl);
return preBody + body + POST_BODY;
}
public static String buildMathPage(CharSequence body, @ColorInt int textColorHighlight, int widthPx, String baseUrl) {
return buildPage(body, CollectionsKt.arrayListOf(MathJaxScript), DefaultFontSize, null, textColorHighlight, widthPx, baseUrl);
}
public static String buildPageWithAdjustingTextAndImage(CharSequence body, @ColorInt int textColorHighlight, int widthPx, String baseUrl) {
return buildPage(body, CollectionsKt.mutableListOf(), DefaultFontSize, null, textColorHighlight, widthPx, baseUrl);
}
public static String buildPageWithCustomFont(CharSequence body, float fontSize, String fontPath, @ColorInt int textColorHighlight, int widthPx, String baseUrl) {
return buildPage(body, CollectionsKt.mutableListOf(), fontSize, fontPath, textColorHighlight, widthPx, baseUrl);
}
public static final String HORIZONTAL_SCROLL_LISTENER = "scrollListener";
private static final String HORIZONTAL_SCROLL_STYLE;
// this block is needed to force render of WebView
private static final String MIN_RENDERED_BLOCK =
"<div style=\"height: 1px; overflow: hidden; width: 1px; background-color: rgba(0,0,0,0.001); pointer-events: none; user-select: none; -webkit-user-select: none;\"></div>";
static {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
HORIZONTAL_SCROLL_STYLE =
"<style>\n" +
"body > * {\n" +
" max-width: 100%%;\n" +
" overflow-x: scroll;\n" +
" vertical-align: middle;\n" +
"}\n" +
"body > .no-scroll {\n" +
" overflow: visible !important;\n" +
"}" +
"</style>\n";
} else {
HORIZONTAL_SCROLL_STYLE = "";
}
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
POST_BODY =
MIN_RENDERED_BLOCK +
"</body>\n" +
"</html>";
} else {
POST_BODY =
"</body>\n" +
"</html>";
}
}
private static final String KotlinRunnableSamplesScript =
"<script src=\"https://unpkg.com/kotlin-playground@1\"></script>" +
"<script>\n" +
"document.addEventListener('DOMContentLoaded', function() {\n" +
" KotlinPlayground('kotlin-runnable', { \n" +
" callback: function(targetNode, mountNode) {\n" +
" mountNode.classList.add('no-scroll');\n" + // disable overflow for pg divs in order to disable overflow and show expand button
" }\n" +
" });\n" +
"});\n" +
"</script>";
private static final String KOTLIN_PLAYGROUND_SCROLL_RULE =
"elem.className !== 'CodeMirror-scroll' && elem.className !== 'code-output'";
private static final String DEFAULT_SCROLL_RULE =
"elem.parentElement.tagName !== 'BODY' && elem.parentElement.tagName !== 'HTML'";
private static final String HORIZONTAL_SCROLL_SCRIPT =
"<script type=\"text/javascript\">\n" +
"function measureScroll(x, y) {" +
"var elem = document.elementFromPoint(x, y);" +
"while(" + DEFAULT_SCROLL_RULE + " && " + KOTLIN_PLAYGROUND_SCROLL_RULE + ") {" +
"elem = elem.parentElement;" +
"}" +
HORIZONTAL_SCROLL_LISTENER + ".onScroll(elem.offsetWidth, elem.scrollWidth, elem.scrollLeft);" +
"}" +
"</script>\n";
//string with 2 format args
private static final String PRE_BODY = "<html>\n" +
"<head>\n" +
"<title>Step</title>\n" +
"%s" +
"%s" +
"<meta name=\"viewport\" content=\"width=" +
"%d" +
", user-scalable=no" +
", target-densitydpi=medium-dpi" +
"\" />" +
"<link rel=\"stylesheet\" type=\"text/css\" href=\"wysiwyg.css\"/>" +
HORIZONTAL_SCROLL_SCRIPT +
HORIZONTAL_SCROLL_STYLE +
"<base href=\"%s\">" +
"</head>\n"
+ "<body style='margin:0;padding:0;'>";
private static final String SelectionColorStyle =
"<style>\n"
+ "::selection { background: #%06X; }\n"
+ "</style>";
private static final float DefaultFontSize = 14f;
private static final String DefaultFontStyle =
"<style>\n"
+ "\nhtml{-webkit-text-size-adjust: 100%%;}"
+ "\nbody{font-size: %.1fpt; font-family:Arial, Helvetica, sans-serif; line-height:1.6em;}"
+ "\nh1{font-size: 20pt; font-family:Arial, Helvetica, sans-serif; line-height:1.6em;text-align: center;}"
+ "\nh2{font-size: 17pt; font-family:Arial, Helvetica, sans-serif; line-height:1.6em;text-align: center;}"
+ "\nh3{font-size: 14pt; font-family:Arial, Helvetica, sans-serif; line-height:1.6em;text-align: center;}"
+ "\nimg { max-width: 100%%; }"
+ "</style>\n";
private static final String CustomFontStyle =
"<style>\n" +
"@font-face {" +
" font-family: 'Roboto';\n" +
" src: url(\"%s\")\n" +
"}"
+ "\nhtml{-webkit-text-size-adjust: 100%%;}"
+ "\nbody{font-size: %.1fpx; font-family:'Roboto', Helvetica, sans-serif; line-height:1.6em;}"
+ "\nh1{font-size: 22px; font-family:'Roboto', Helvetica, sans-serif; line-height:1.6em;text-align: center;}"
+ "\nh2{font-size: 19px; font-family:'Roboto', Helvetica, sans-serif; line-height:1.6em;text-align: center;}"
+ "\nh3{font-size: 16px; font-family:'Roboto', Helvetica, sans-serif; line-height:1.6em;text-align: center;}"
+ "\nimg { max-width: 100%%; }"
+ "</style>\n";
private static final String POST_BODY;
private static final String MathJaxScript =
"<script type=\"text/x-mathjax-config\">\n" +
" MathJax.Hub.Config({" +
"showMathMenu: false, " +
"messageStyle: \"none\", " +
"TeX: {extensions: [ \"color.js\"]}, " +
"tex2jax: {preview: \"none\", inlineMath: [['$','$'], ['\\\\(','\\\\)']]}});\n" +
"displayMath: [ ['$$','$$'], ['\\[','\\]'] ]" +
"</script>\n" +
"<script type=\"text/javascript\"\n" +
" src=\"file:///android_asset/MathJax/MathJax.js?config=TeX-AMS_HTML\">\n" +
"</script>\n";
public static String getUserPath(Config config, int userId) {
return new StringBuilder()
.append(config.getBaseUrl())
.append(AppConstants.WEB_URI_SEPARATOR)
.append("users")
.append(AppConstants.WEB_URI_SEPARATOR)
.append(userId)
.append("/?from_mobile_app=true")
.toString();
}
@Nullable
public static String parseNLinkInText(@NotNull String htmlText, String baseUrl, int position) {
try {
Document document = Jsoup.parse(htmlText);
document.setBaseUri(baseUrl);
Elements elements = document.getElementsByTag("a");
Element our = elements.get(position);
String absolute = our.absUrl("href");
Timber.d(absolute);
return absolute;
} catch (Exception exception) {
return null;
}
}
}
|
package org.commcare.android.util;
import org.commcare.android.database.TableBuilder;
import org.commcare.android.database.cache.GeocodeCacheModel;
import org.commcare.android.javarosa.AndroidLogEntry;
import org.commcare.android.javarosa.DeviceReportRecord;
import org.commcare.android.models.FormRecord;
import org.commcare.android.models.SessionStateDescriptor;
import org.commcare.resources.model.Resource;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
/**
*
* This class exists in order to handle all of the logic associated with upgrading from one version
* of CommCare ODK to another. It is going to get big and annoying.
*
* @author ctsims
*/
public class CommCareUpgrader {
Context context;
public CommCareUpgrader(Context c) {
this.context = c;
}
public boolean doUpgrade(SQLiteDatabase database, int from, int to) {
if(from == 1) {
if(upgradeOneTwo(database)) {
from = 2;
} else { return false;}
}
if(from == 26) {
if(upgradeTwoSixtoTwoSeven(database)) {
from = 27;
} else { return false;}
}
if(from == 27) {
if(upgradeTwoSeventoTwoEight(database)) {
from = 28;
} else { return false;}
}
if(from == 28) {
if(upgradeTwoEighttoTwoNine(database)) {
from = 29;
} else { return false; }
}
return from == to;
}
public boolean upgradeOneTwo(SQLiteDatabase database) {
database.beginTransaction();
TableBuilder builder = new TableBuilder("UPGRADE_RESOURCE_TABLE");
builder.addData(new Resource());
database.execSQL(builder.getTableCreateString());
database.setVersion(2);
database.setTransactionSuccessful();
database.endTransaction();
return true;
}
/**
* Due a to a bug in Android 2.2 that is present on ~all of our
* production phones, upgrading from database versions
* before v. TOBEDECIDED is going to toast all of the app data. As such
* we need to remove all of the relevant records to ensure that
* the app doesn't crash and burn.
*
* @param database
*/
public void upgradeBeforeTwentyFour(SQLiteDatabase database) {
//NOTE: We'll do this cleanly when appropriate, but for
//right now we're just going to live with the bug.
database.beginTransaction();
database.execSQL("delete from GLOBAL_RESOURCE_TABLE");
database.execSQL("delete from UPGRADE_RESOURCE_TABLE");
database.execSQL("delete from " + FormRecord.STORAGE_KEY);
database.setTransactionSuccessful();
database.endTransaction();
}
/**
* Previous FormRecord entries were lacking, we're going to
* wipe them out.
*
* @param database
* @return
*/
private boolean upgradeTwoSixtoTwoSeven(SQLiteDatabase database) {
database.beginTransaction();
//wipe out old Form Record table
database.execSQL("drop table " + FormRecord.STORAGE_KEY);
//Build us a new one with the new structure
TableBuilder builder = new TableBuilder(FormRecord.STORAGE_KEY);
builder.addData(new FormRecord());
database.execSQL(builder.getTableCreateString());
database.setTransactionSuccessful();
database.endTransaction();
return true;
}
private boolean upgradeTwoSeventoTwoEight(SQLiteDatabase database) {
database.beginTransaction();
TableBuilder builder = new TableBuilder(GeocodeCacheModel.STORAGE_KEY);
builder.addData(new GeocodeCacheModel());
database.execSQL(builder.getTableCreateString());
database.setTransactionSuccessful();
database.endTransaction();
return true;
}
private boolean upgradeTwoEighttoTwoNine(SQLiteDatabase database) {
try {
database.beginTransaction();
TableBuilder builder = new TableBuilder(AndroidLogEntry.STORAGE_KEY);
builder.addData(new AndroidLogEntry());
database.execSQL(builder.getTableCreateString());
builder = new TableBuilder(DeviceReportRecord.STORAGE_KEY);
builder.addData(new DeviceReportRecord());
database.execSQL(builder.getTableCreateString());
//SQLite can't add column constraints. You've gotta make a new table, copy everything over, and
//wipe the old one
String table = TableBuilder.scrubName(SessionStateDescriptor.STORAGE_KEY);
String tempTable = TableBuilder.scrubName(SessionStateDescriptor.STORAGE_KEY + "temp");
database.execSQL(String.format("ALTER TABLE %s RENAME TO %s;", table, tempTable));
builder = new TableBuilder(SessionStateDescriptor.STORAGE_KEY);
builder.setUnique(SessionStateDescriptor.META_FORM_RECORD_ID);
builder.addData(new SessionStateDescriptor());
database.execSQL(builder.getTableCreateString());
String cols = builder.getColumns();
database.execSQL(String.format("INSERT OR REPLACE INTO %s (%s) " +
"SELECT %s " +
"FROM %s;", table, cols, cols, tempTable));
database.execSQL(String.format("DROP TABLE %s;", tempTable));
database.setTransactionSuccessful();
return true;
} finally {
database.endTransaction();
}
}
}
|
package org.commcare.android.view;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
import java.util.regex.Pattern;
import org.odk.collect.android.views.media.AudioButton;
import org.odk.collect.android.views.media.ViewId;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.model.XYValueSeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.commcare.android.javarosa.AndroidLogger;
import org.commcare.android.models.Entity;
import org.commcare.android.util.DetailCalloutListener;
import org.commcare.android.util.FileUtil;
import org.commcare.android.util.MediaUtil;
import org.commcare.dalvik.R;
import org.commcare.suite.model.Detail;
import org.commcare.suite.model.graph.AnnotationData;
import org.commcare.suite.model.graph.BubblePointData;
import org.commcare.suite.model.graph.ConfigurableData;
import org.commcare.suite.model.graph.GraphData;
import org.commcare.suite.model.graph.Graph;
import org.commcare.suite.model.graph.XYPointData;
import org.commcare.suite.model.graph.SeriesData;
import org.commcare.util.CommCareSession;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.services.Logger;
import org.odk.collect.android.views.media.AudioController;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
/**
* @author ctsims
*
*/
public class EntityDetailView extends FrameLayout {
private TextView label;
private TextView data;
private TextView spacer;
private Button callout;
private View addressView;
private Button addressButton;
private TextView addressText;
private ImageView imageView;
private LinearLayout graphLayout;
private ImageButton videoButton;
private AudioButton audioButton;
private View valuePane;
private View currentView;
private AudioController controller;
private LinearLayout detailRow;
private LinearLayout.LayoutParams origValue;
private LinearLayout.LayoutParams origLabel;
private LinearLayout.LayoutParams fill;
private static final String FORM_VIDEO = "video";
private static final String FORM_AUDIO = "audio";
private static final String FORM_PHONE = "phone";
private static final String FORM_ADDRESS = "address";
private static final String FORM_IMAGE = "image";
private static final String FORM_GRAPH = "graph";
private static final int TEXT = 0;
private static final int PHONE = 1;
private static final int ADDRESS = 2;
private static final int IMAGE = 3;
private static final int VIDEO = 4;
private static final int AUDIO = 5;
private static final int GRAPH = 6;
private static final int GRAPH_TEXT_SIZE = 21;
int current = TEXT;
DetailCalloutListener listener;
public EntityDetailView(Context context, CommCareSession session, Detail d, Entity e, int index,
AudioController controller, int detailNumber) {
super(context);
this.controller = controller;
detailRow = (LinearLayout)View.inflate(context, R.layout.component_entity_detail_item, null);
label = (TextView)detailRow.findViewById(R.id.detail_type_text);
spacer = (TextView)detailRow.findViewById(R.id.entity_detail_spacer);
data = (TextView)detailRow.findViewById(R.id.detail_value_text);
currentView = data;
valuePane = detailRow.findViewById(R.id.detail_value_pane);
videoButton = (ImageButton)detailRow.findViewById(R.id.detail_video_button);
ViewId uniqueId = new ViewId(detailNumber, index, true);
String audioText = e.getFieldString(index);
audioButton = new AudioButton(context, audioText, uniqueId, controller, false);
detailRow.addView(audioButton);
audioButton.setVisibility(View.GONE);
callout = (Button)detailRow.findViewById(R.id.detail_value_phone);
//TODO: Still useful?
//callout.setInputType(InputType.TYPE_CLASS_PHONE);
addressView = (View)detailRow.findViewById(R.id.detail_address_view);
addressText = (TextView)addressView.findViewById(R.id.detail_address_text);
addressButton = (Button)addressView.findViewById(R.id.detail_address_button);
imageView = (ImageView)detailRow.findViewById(R.id.detail_value_image);
graphLayout = (LinearLayout)detailRow.findViewById(R.id.graph_layout);
origLabel = (LinearLayout.LayoutParams)label.getLayoutParams();
origValue = (LinearLayout.LayoutParams)valuePane.getLayoutParams();
fill = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
this.addView(detailRow, FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
setParams(session, d, e, index, detailNumber);
}
public void setCallListener(final DetailCalloutListener listener) {
this.listener = listener;
}
public void setParams(CommCareSession session, Detail d, Entity e, int index, int detailNumber) {
String labelText = d.getFields()[index].getHeader().evaluate();
label.setText(labelText);
spacer.setText(labelText);
Object field = e.getField(index);
String textField = e.getFieldString(index);
boolean veryLong = false;
String form = d.getTemplateForms()[index];
if(FORM_PHONE.equals(form)) {
callout.setText(textField);
if(current != PHONE) {
callout.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
listener.callRequested(callout.getText().toString());
}
});
currentView.setVisibility(View.GONE);
callout.setVisibility(View.VISIBLE);
this.removeView(currentView);
currentView = callout;
current = PHONE;
}
} else if(FORM_ADDRESS.equals(form)) {
final String address = textField;
addressText.setText(address);
if(current != ADDRESS) {
addressButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
listener.addressRequested(MediaUtil.getGeoIntentURI(address));
}
});
currentView.setVisibility(View.GONE);
addressView.setVisibility(View.VISIBLE);
currentView = addressView;
current = ADDRESS;
}
} else if(FORM_IMAGE.equals(form)) {
String imageLocation = textField;
Bitmap b = MediaUtil.getScaledImageFromReference(this.getContext(),imageLocation);
if(b == null) {
imageView.setImageDrawable(null);
} else {
//Ok, so. We should figure out whether our image is large or small.
if(b.getWidth() > (getScreenWidth() / 2)) {
veryLong = true;
}
imageView.setPadding(10, 10, 10, 10);
imageView.setAdjustViewBounds(true);
imageView.setImageBitmap(b);
imageView.setId(23422634);
}
if(current != IMAGE) {
currentView.setVisibility(View.GONE);
imageView.setVisibility(View.VISIBLE);
currentView = imageView;
current = IMAGE;
}
} else if (FORM_GRAPH.equals(form)) {
GraphData graphData = (GraphData) field;
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
renderer.setInScroll(true);
Iterator<SeriesData> seriesIterator = graphData.getSeriesIterator();
boolean isBubble = graphData.getType().equals(Graph.TYPE_BUBBLE);
while (seriesIterator.hasNext()) {
SeriesData s = seriesIterator.next();
XYSeries series = isBubble ? new XYValueSeries("") : new XYSeries("");
dataset.addSeries(series);
XYSeriesRenderer currentRenderer = new XYSeriesRenderer();
renderer.addSeriesRenderer(currentRenderer);
String showPoints = s.getConfiguration("show-points");
if (showPoints == null || !Boolean.valueOf(showPoints).equals(Boolean.FALSE)) {
currentRenderer.setPointStyle(PointStyle.CIRCLE);
currentRenderer.setFillPoints(true);
}
String lineColor = s.getConfiguration("line-color");
if (lineColor != null) {
currentRenderer.setColor(Color.parseColor(lineColor));
}
else {
currentRenderer.setColor(getContext().getResources().getColor(R.drawable.black));
}
String[] fillProperties = new String[]{"fill-above", "fill-below"};
XYSeriesRenderer.FillOutsideLine.Type[] fillTypes = new XYSeriesRenderer.FillOutsideLine.Type[]{
XYSeriesRenderer.FillOutsideLine.Type.ABOVE,
XYSeriesRenderer.FillOutsideLine.Type.BELOW
};
for (int i = 0; i < fillProperties.length; i++) {
String fillProperty = s.getConfiguration(fillProperties[i]);
if (fillProperty != null) {
XYSeriesRenderer.FillOutsideLine fill = new XYSeriesRenderer.FillOutsideLine(fillTypes[i]);
fill.setColor(Color.parseColor(fillProperty));
currentRenderer.addFillOutsideLine(fill);
}
}
// achartengine won't render a bubble chart with its points out of order
Vector<XYPointData> sortedPoints = new Vector<XYPointData>(s.size());
Iterator<XYPointData> pointsIterator = s.getPointsIterator();
while (pointsIterator.hasNext()) {
sortedPoints.add(pointsIterator.next());
}
Collections.sort(sortedPoints, new PointComparator());
for (XYPointData p : sortedPoints) {
if (isBubble) {
BubblePointData b = (BubblePointData) p;
((XYValueSeries) series).add(b.getX(), b.getY(), b.getRadius());
}
else {
series.add(p.getX(), p.getY());
}
}
}
// Annotations
Iterator<AnnotationData> i = graphData.getAnnotationIterator();
if (i.hasNext()) {
XYSeries series = new XYSeries("");
while (i.hasNext()) {
AnnotationData a = i.next();
series.addAnnotation(a.getAnnotation(), a.getX(), a.getY());
}
series.add(0.0, 0.0);
dataset.addSeries(series);
XYSeriesRenderer currentRenderer = new XYSeriesRenderer();
currentRenderer.setAnnotationsTextSize(GRAPH_TEXT_SIZE);
currentRenderer.setAnnotationsColor(getContext().getResources().getColor(R.drawable.black));
renderer.addSeriesRenderer(currentRenderer);
}
configureGraph(graphData, renderer);
renderer.setChartTitle(labelText);
renderer.setChartTitleTextSize(GRAPH_TEXT_SIZE);
int topMargin = labelText.equals("") ? 0 : 30;
int leftMargin = renderer.getYTitle().equals("") ? 20 : 70;
renderer.setMargins(new int[]{topMargin, leftMargin, 0, 20}); // top, left, bottom, right
GraphicalView graph = isBubble
? ChartFactory.getBubbleChartView(getContext(), dataset, renderer)
: ChartFactory.getLineChartView(getContext(), dataset, renderer)
;
int width = getScreenWidth();
int height = width / 2;
reduceLabels(true, renderer, width);
reduceLabels(false, renderer, height);
graphLayout.addView(graph, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, height));
if (current != GRAPH) {
label.setVisibility(View.GONE);
LinearLayout.LayoutParams graphValueLayout = new LinearLayout.LayoutParams(origValue);
graphValueLayout.weight = 10;
valuePane.setLayoutParams(graphValueLayout);
data.setVisibility(View.GONE);
currentView.setVisibility(View.GONE);
graphLayout.setVisibility(View.VISIBLE);
currentView = graphLayout;
current = GRAPH;
}
} else if (FORM_AUDIO.equals(form)) {
ViewId uniqueId = new ViewId(detailNumber, index, true);
audioButton.modifyButtonForNewView(uniqueId, textField, true);
if (current != AUDIO) {
currentView.setVisibility(View.GONE);
audioButton.setVisibility(View.VISIBLE);
currentView = audioButton;
current = AUDIO;
}
} else if(FORM_VIDEO.equals(form)) { //TODO: Why is this given a special string?
String videoLocation = textField;
String localLocation = null;
try{
localLocation = ReferenceManager._().DeriveReference(videoLocation).getLocalURI();
if(localLocation.startsWith("/")) {
//TODO: This should likely actually be happening with the getLocalURI _anyway_.
localLocation = FileUtil.getGlobalStringUri(localLocation);
}
} catch(InvalidReferenceException ire) {
Logger.log(AndroidLogger.TYPE_ERROR_CONFIG_STRUCTURE, "Couldn't understand video reference format: " + localLocation + ". Error: " + ire.getMessage());
}
final String location = localLocation;
videoButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
listener.playVideo(location);
}
});
if(location == null) {
videoButton.setEnabled(false);
Logger.log(AndroidLogger.TYPE_ERROR_CONFIG_STRUCTURE, "No local video reference available for ref: " + videoLocation);
} else {
videoButton.setEnabled(true);
}
if(current != VIDEO) {
currentView.setVisibility(View.GONE);
videoButton.setVisibility(View.VISIBLE);
currentView = videoButton;
current = VIDEO;
}
} else {
String text = textField;
data.setText(text);
if(text != null && text.length() > this.getContext().getResources().getInteger(R.integer.detail_size_cutoff)) {
veryLong = true;
}
if(current != TEXT) {
currentView.setVisibility(View.GONE);
data.setVisibility(View.VISIBLE);
currentView = data;
current = TEXT;
}
}
if (!FORM_GRAPH.equals(form)) {
label.setVisibility(View.VISIBLE);
LinearLayout.LayoutParams graphValueLayout = new LinearLayout.LayoutParams(origValue);
graphValueLayout.weight = 10;
valuePane.setLayoutParams(origValue);
data.setVisibility(View.VISIBLE);
}
if(veryLong) {
detailRow.setOrientation(LinearLayout.VERTICAL);
spacer.setVisibility(View.GONE);
label.setLayoutParams(fill);
valuePane.setLayoutParams(fill);
} else {
if(detailRow.getOrientation() != LinearLayout.HORIZONTAL) {
detailRow.setOrientation(LinearLayout.HORIZONTAL);
spacer.setVisibility(View.INVISIBLE);
label.setLayoutParams(origLabel);
valuePane.setLayoutParams(origValue);
}
}
}
private int getScreenWidth() {
Display display = ((WindowManager) this.getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
return display.getWidth();
}
private void reduceLabels(boolean isX, XYMultipleSeriesRenderer renderer, int dimension) {
int count = isX ? renderer.getXLabels() : renderer.getYLabels();
while (count * GRAPH_TEXT_SIZE > dimension) {
count = count % 2 != 0 && count % 3 == 0 ? count / 3 : count / 2;
if (isX) {
renderer.setXLabels(count);
}
else {
renderer.setYLabels(count);
}
}
}
private void configureGraph(GraphData data, XYMultipleSeriesRenderer renderer) {
Context context = getContext();
// Default options
renderer.setBackgroundColor(context.getResources().getColor(R.drawable.white));
renderer.setMarginsColor(context.getResources().getColor(R.drawable.white));
renderer.setLabelsColor(getContext().getResources().getColor(R.drawable.black));
renderer.setXLabelsColor(context.getResources().getColor(R.drawable.black));
renderer.setYLabelsColor(0, context.getResources().getColor(R.drawable.black));
renderer.setYLabelsAlign(Paint.Align.RIGHT);
renderer.setYLabelsPadding(10);
renderer.setAxesColor(context.getResources().getColor(R.drawable.black));
renderer.setLabelsTextSize(GRAPH_TEXT_SIZE);
renderer.setAxisTitleTextSize(GRAPH_TEXT_SIZE);
renderer.setShowLabels(true);
renderer.setApplyBackgroundColor(true);
renderer.setShowLegend(false);
renderer.setShowGrid(true);
renderer.setPanEnabled(false, false);
// User-configurable options
if (data.getConfiguration("x-label-count") != null) {
renderer.setXLabels(Integer.valueOf(data.getConfiguration("x-label-count")));
}
if (data.getConfiguration("y-label-count") != null) {
renderer.setYLabels(Integer.valueOf(data.getConfiguration("y-label-count")));
}
if (data.getConfiguration("x-axis-title") != null) {
renderer.setXTitle(data.getConfiguration("x-axis-title"));
}
if (data.getConfiguration("y-axis-title") != null) {
renderer.setYTitle(data.getConfiguration("y-axis-title"));
}
if (data.getConfiguration("x-axis-min") != null) {
renderer.setXAxisMin(Double.valueOf(data.getConfiguration("x-axis-min")));
}
if (data.getConfiguration("y-axis-min") != null) {
renderer.setYAxisMin(Double.valueOf(data.getConfiguration("y-axis-min")));
}
if (data.getConfiguration("x-axis-max") != null) {
renderer.setXAxisMax(Double.valueOf(data.getConfiguration("x-axis-max")));
}
if (data.getConfiguration("y-axis-max") != null) {
renderer.setYAxisMax(Double.valueOf(data.getConfiguration("y-axis-max")));
}
}
/**
* Comparator to sort PointData objects by x value.
* @author jschweers
*
*/
private class PointComparator implements Comparator<XYPointData> {
@Override
public int compare(XYPointData lhs, XYPointData rhs) {
if (lhs.getX() > rhs.getX()) {
return 1;
}
if (lhs.getX() < rhs.getX()) {
return -1;
}
return 0;
}
}
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Period;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.time.temporal.WeekFields;
import java.util.Locale;
import java.util.Objects;
import javax.swing.*;
public final class MainPanel extends JPanel {
public final Dimension size = new Dimension(40, 26);
public final JLabel yearMonthLabel = new JLabel("", SwingConstants.CENTER);
public final JList<LocalDate> monthList = new JList<LocalDate>() {
@Override public void updateUI() {
setCellRenderer(null);
super.updateUI();
setLayoutOrientation(JList.HORIZONTAL_WRAP);
setVisibleRowCount(CalendarViewListModel.ROW_COUNT); // ensure 6 rows in the list
setFixedCellWidth(size.width);
setFixedCellHeight(size.height);
setCellRenderer(new CalendarListRenderer());
getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
}
};
public final LocalDate realLocalDate = LocalDate.now(ZoneId.systemDefault());
private LocalDate currentLocalDate;
public LocalDate getCurrentLocalDate() {
return currentLocalDate;
}
private MainPanel() {
super();
installActions();
Locale l = Locale.getDefault();
DefaultListModel<DayOfWeek> weekModel = new DefaultListModel<>();
DayOfWeek firstDayOfWeek = WeekFields.of(l).getFirstDayOfWeek();
for (int i = 0; i < DayOfWeek.values().length; i++) {
weekModel.add(i, firstDayOfWeek.plus(i));
}
JList<DayOfWeek> header = new JList<>(weekModel);
header.setLayoutOrientation(JList.HORIZONTAL_WRAP);
header.setVisibleRowCount(0);
header.setFixedCellWidth(size.width);
header.setFixedCellHeight(size.height);
header.setCellRenderer(new DefaultListCellRenderer() {
@Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, false, false);
setHorizontalAlignment(SwingConstants.CENTER);
if (value instanceof DayOfWeek) {
DayOfWeek dow = (DayOfWeek) value;
// String s = dow.getDisplayName(TextStyle.SHORT_STANDALONE, l);
// setText(s.substring(0, Math.min(2, s.length())));
setText(dow.getDisplayName(TextStyle.SHORT_STANDALONE, l));
setBackground(new Color(0xDC_DC_DC));
}
return this;
}
});
updateMonthView(realLocalDate);
JButton prev = new JButton("<");
prev.addActionListener(e -> updateMonthView(getCurrentLocalDate().minusMonths(1)));
JButton next = new JButton(">");
next.addActionListener(e -> updateMonthView(getCurrentLocalDate().plusMonths(1)));
JPanel yearMonthPanel = new JPanel(new BorderLayout());
yearMonthPanel.add(yearMonthLabel);
yearMonthPanel.add(prev, BorderLayout.WEST);
yearMonthPanel.add(next, BorderLayout.EAST);
JScrollPane scroll = new JScrollPane(monthList);
scroll.setColumnHeaderView(header);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
JLabel label = new JLabel(" ", SwingConstants.CENTER);
monthList.getSelectionModel().addListSelectionListener(e -> {
ListSelectionModel lsm = (ListSelectionModel) e.getSource();
if (lsm.isSelectionEmpty()) {
label.setText(" ");
} else {
ListModel<LocalDate> model = monthList.getModel();
LocalDate from = model.getElementAt(lsm.getMinSelectionIndex());
LocalDate to = model.getElementAt(lsm.getMaxSelectionIndex());
label.setText(Period.between(from, to).toString());
}
});
Box box = Box.createVerticalBox();
box.add(yearMonthPanel);
box.add(Box.createVerticalStrut(2));
box.add(scroll);
box.add(label);
add(box);
setPreferredSize(new Dimension(320, 240));
}
private void installActions() {
InputMap im = monthList.getInputMap(JComponent.WHEN_FOCUSED);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "selectNextIndex");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "selectPreviousIndex");
ActionMap am = monthList.getActionMap();
am.put("selectPreviousIndex", new AbstractAction() {
@Override public void actionPerformed(ActionEvent e) {
int index = monthList.getLeadSelectionIndex();
if (index > 0) {
monthList.setSelectedIndex(index - 1);
} else {
LocalDate d = monthList.getModel().getElementAt(0).minusDays(1);
updateMonthView(getCurrentLocalDate().minusMonths(1));
monthList.setSelectedValue(d, false);
}
}
});
am.put("selectNextIndex", new AbstractAction() {
@Override public void actionPerformed(ActionEvent e) {
int index = monthList.getLeadSelectionIndex();
if (index < monthList.getModel().getSize() - 1) {
monthList.setSelectedIndex(index + 1);
} else {
LocalDate d = monthList.getModel().getElementAt(monthList.getModel().getSize() - 1).plusDays(1);
updateMonthView(getCurrentLocalDate().plusMonths(1));
monthList.setSelectedValue(d, false);
}
}
});
Action selectPreviousRow = am.get("selectPreviousRow");
am.put("selectPreviousRow", new AbstractAction() {
@Override public void actionPerformed(ActionEvent e) {
int index = monthList.getLeadSelectionIndex();
int weekLength = DayOfWeek.values().length;
if (index < weekLength) {
LocalDate d = monthList.getModel().getElementAt(index).minusDays(weekLength);
updateMonthView(getCurrentLocalDate().minusMonths(1));
monthList.setSelectedValue(d, false);
} else {
selectPreviousRow.actionPerformed(e);
}
}
});
Action selectNextRow = am.get("selectNextRow");
am.put("selectNextRow", new AbstractAction() {
@Override public void actionPerformed(ActionEvent e) {
int index = monthList.getLeadSelectionIndex();
int weekLength = DayOfWeek.values().length;
if (index > monthList.getModel().getSize() - weekLength) {
LocalDate d = monthList.getModel().getElementAt(index).plusDays(weekLength);
updateMonthView(getCurrentLocalDate().plusMonths(1));
monthList.setSelectedValue(d, false);
} else {
selectNextRow.actionPerformed(e);
}
}
});
}
public void updateMonthView(LocalDate localDate) {
currentLocalDate = localDate;
yearMonthLabel.setText(localDate.format(DateTimeFormatter.ofPattern("yyyy / MM").withLocale(Locale.getDefault())));
monthList.setModel(new CalendarViewListModel(localDate));
}
private class CalendarListRenderer implements ListCellRenderer<LocalDate> {
private final ListCellRenderer<? super LocalDate> renderer = new DefaultListCellRenderer();
@Override public Component getListCellRendererComponent(JList<? extends LocalDate> list, LocalDate value, int index, boolean isSelected, boolean cellHasFocus) {
JLabel l = (JLabel) renderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
l.setOpaque(true);
l.setHorizontalAlignment(SwingConstants.CENTER);
l.setText(Objects.toString(value.getDayOfMonth()));
Color fgc = l.getForeground();
if (YearMonth.from(value).equals(YearMonth.from(getCurrentLocalDate()))) {
DayOfWeek dow = value.getDayOfWeek();
if (value.isEqual(realLocalDate)) {
fgc = new Color(0x64_FF_64);
} else if (dow == DayOfWeek.SUNDAY) {
fgc = new Color(0xFF_64_64);
} else if (dow == DayOfWeek.SATURDAY) {
fgc = new Color(0x64_64_FF);
}
} else {
fgc = Color.GRAY;
}
l.setForeground(isSelected ? l.getForeground() : fgc);
return l;
}
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class CalendarViewListModel extends AbstractListModel<LocalDate> {
public static final int ROW_COUNT = 6;
private final LocalDate startDate;
protected CalendarViewListModel(LocalDate date) {
super();
LocalDate firstDayOfMonth = YearMonth.from(date).atDay(1);
WeekFields weekFields = WeekFields.of(Locale.getDefault());
int fdmDow = firstDayOfMonth.get(weekFields.dayOfWeek()) - 1;
startDate = firstDayOfMonth.minusDays(fdmDow);
}
@Override public int getSize() {
return DayOfWeek.values().length * ROW_COUNT;
}
@Override public LocalDate getElementAt(int index) {
return startDate.plusDays(index);
}
}
|
package application;
import java.io.InputStream;
import java.util.*;
import javax.faces.application.*;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import beans.scripts.*;
import beans.graph.Graph;
import beans.scoring.PeerContainer;
import controller.IllnessScriptController;
import controller.JsonCreator;
import controller.MeshImporter;
import controller.PeerSyncController;
import database.DBClinReason;
import database.HibernateUtil;
import util.CRTLogger;
import util.StringUtilities;
import properties.IntlConfiguration;
//import test.TextSimilarityComparing;
/**
* We init here some application stuff, like hibernate,....
* TODO: we could remove the scripts if no parent VP is open.
* @author ingahege
*
*/
@ManagedBean(name = "crtInit", eager = true)
@ApplicationScoped
public class AppBean extends ApplicationWrapper implements HttpSessionListener{
public static final String DEFAULT_LOCALE="en"; //TODO get from properties!
public static final String[] ACCEPTED_LOCALES = new String[]{"en", "de"}; //TODO get from properties!
public static List<Graph> graphs;
public static final String APP_KEY = "AppBean";
public static IntlConfiguration intlConf;
/**
* Any application-wide properties, file is in WEB-INF/classes/globalsettings.properties
*/
private static final Properties properties = new Properties();
/**
* we dynamically load the experts' scripts into the map if a learner opens a VP that has not been
* opened before by a learner.
*
*/
public static Map<String, PatientIllnessScript> expertPatIllScripts;
/**
* we dynamically load the illness scripts into the map if a learner opens a VP that has not been
* opened before by a learner.
*
*/
public static Map<Long, List<IllnessScript>> ilnessScripts;
public static Map<Long, Graph> graph;
private static PeerContainer peers = new PeerContainer();
private static Map<String, VPScriptRef> vpScriptRefs;
/**
* called when the application is started... We init Hibernate and a ViewHandler (for Locale handling)
* We also put this AppBean into the ServletContext for later access to the applicationScoped scripts
* Loading any
*/
public AppBean(){
HibernateUtil.initHibernate();
intlConf = new IntlConfiguration();
//setViewHandler(new CRTViewHandler(FacesContext.getCurrentInstance().getApplication().getViewHandler()));
ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
context.setAttribute(APP_KEY, this);
try{
//load properties for the application(file is in WEB-INF/classes:
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("properties/globalsettings.properties");
properties.load(input);
}
catch(Exception e){}
//does not have to be done on every restart:
//new JsonCreator().initJsonExport();
//MeshImporter.main("en");
// new TextSimilarityComparing().compareTestData();
peers.initPeerContainer();
vpScriptRefs = IllnessScriptController.getInstance().initVpScriptRefs();
CRTLogger.out("Init done", CRTLogger.LEVEL_PROD);
try{
new PeerSyncController(peers).sync();
}
catch(Exception e){
CRTLogger.out("AppBean(): " + StringUtilities.stackTraceToString(e), CRTLogger.LEVEL_ERROR);
}
}
//public static Monitor getMonitor() {return monitor;}
/**
* We have one experts' patientIllnessScript per parentId (=VPId). If it has not yet been loaded (by another
* learner working on the same VP, we load it and put it into the expertPatIllScripts Map.
* @param parentId
*/
public synchronized PatientIllnessScript addExpertPatIllnessScriptForVpId(String vpId){
if(expertPatIllScripts==null) expertPatIllScripts = new HashMap<String, PatientIllnessScript>();
if(vpId!=null && !expertPatIllScripts.containsKey(vpId)){
PatientIllnessScript expScript = (PatientIllnessScript) new DBClinReason().selectExpertPatIllScriptByVPId(vpId);
if(expScript!=null) expertPatIllScripts.put(vpId, expScript);
return expScript;
//if(graphs!=null && graphs.get(new Long(parentId)!=null)) return
//todo init graphs?
}
if(vpId!=null && expertPatIllScripts.containsKey(vpId)) return expertPatIllScripts.get(vpId);
return null;
}
public synchronized void addIllnessScriptForDiagnoses(List diagnoses, String vpId){
}
public static PatientIllnessScript getExpertPatIllScript(String vpId) {
if(expertPatIllScripts!=null)
return expertPatIllScripts.get(vpId);
return null;
}
public static List<IllnessScript> getIlnessScripts(String vpId) {
if(ilnessScripts==null) return null;
return ilnessScripts.get(vpId);
}
public static PeerContainer getPeers() {return peers;}
/* (non-Javadoc)
* @see javax.faces.application.ApplicationWrapper#getWrapped()
*/
public Application getWrapped() {
return FacesContext.getCurrentInstance().getApplication();
}
@Override
public void sessionCreated(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
}
/**
* @return the sharedSecret of the application as defined in the globalsettings.properties file.
*/
public static String getSharedSecret(){
if(properties==null) return null;
return properties.getProperty("SharedSecret");
}
public static String getVPNameByParentId(String id){
if(vpScriptRefs==null || vpScriptRefs.get(id)==null) return "";
return vpScriptRefs.get(id).getVpName();
}
}
|
// About.java
package loci.plugins;
import javax.swing.JOptionPane;
/** Displays a small information dialog about this package. */
public abstract class About {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null,
"LOCI Plugins for ImageJ\n" +
"Built @date@\n\n" +
"The 4D Data Browser is LOCI software written by\n" +
"Francis Wong, Curtis Rueden and Melissa Linkert.\n" +
"http://www.loci.wisc.edu/4d/#browser\n\n" +
"The Bio-Formats Importer and Exporter are LOCI software\n" +
"written by Melissa Linkert and Curtis Rueden.\n" +
"http:
"The OME Plugin for ImageJ is LOCI software written by\n" +
"Philip Huettl and Melissa Linkert.\n" +
"http:
"LOCI Plugins for ImageJ", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
|
package vcap.service;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.annotate.JsonProperty;
import vcap.common.JsonObject;
/**
* @author Mike Heath <elcapo@gmail.com>
*/
public class CreateResponse extends JsonObject {
private final String serviceInstanceId;
private final JsonNode configuration; // TODO Figure out what this is used for, it shows up in CC REST services but nowhere else
private final JsonNode credentials;
public CreateResponse(
@JsonProperty("service_id") String serviceInstanceId,
@JsonProperty("configuration") JsonNode configuration,
@JsonProperty("credentials") JsonNode credentials) {
this.serviceInstanceId = serviceInstanceId;
this.configuration = configuration;
this.credentials = credentials;
}
@JsonProperty("service_id")
public String getServiceInstanceId() {
return serviceInstanceId;
}
public JsonNode getConfiguration() {
return configuration;
}
public JsonNode getCredentials() {
return credentials;
}
}
|
package org.archive.wayback.replay;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.archive.wayback.ResultURIConverter;
import org.archive.wayback.core.Resource;
import org.archive.wayback.core.SearchResult;
import org.archive.wayback.core.SearchResults;
import org.archive.wayback.core.WaybackRequest;
import org.archive.wayback.query.UIQueryResults;
import org.mozilla.universalchardet.UniversalDetector;
/**
* Class which wraps functionality for converting a Resource(InputStream +
* HTTP headers) into a StringBuilder, performing several common URL
* resolution methods against that StringBuilder, inserting arbitrary Strings
* into the page, and then converting the page back to a byte array.
*
* @author brad
* @version $Date$, $Revision$
*/
public class HTMLPage {
// hand off this many bytes to the chardet library
private final static int MAX_CHARSET_READAHEAD = 65536;
// ...if it also includes "charset="
private final static String CHARSET_TOKEN = "charset=";
// ...and if the chardet library fails, use the Content-Type header
private final static String HTTP_CONTENT_TYPE_HEADER = "Content-Type";
// if documents are marked up before sending to clients, the data is
// decoded into a String in chunks. This is how big a chunk to decode with.
private final static int C_BUFFER_SIZE = 4096;
private Resource resource = null;
private SearchResult result = null;
private ResultURIConverter uriConverter = null;
/**
* the internal StringBuilder
*/
public StringBuilder sb = null;
private String charSet = null;
private byte[] resultBytes = null;
/**
* @param resource
* @param result
* @param uriConverter
*/
public HTMLPage(Resource resource, SearchResult result,
ResultURIConverter uriConverter) {
this.resource = resource;
this.result = result;
this.uriConverter = uriConverter;
}
private String contentTypeToCharset(final String contentType) {
int offset = contentType.indexOf(CHARSET_TOKEN);
if (offset != -1) {
return contentType.substring(offset + CHARSET_TOKEN.length());
}
return null;
}
/**
* Attempt to divine the character encoding of the document from the
* Content-Type HTTP header (with a "charset=")
*
* @param resource
* @return String character set found or null if the header was not present
* @throws IOException
*/
protected String getCharsetFromHeaders(Resource resource)
throws IOException {
String charsetName = null;
Map<String,String> httpHeaders = resource.getHttpHeaders();
String ctype = httpHeaders.get(HTTP_CONTENT_TYPE_HEADER);
if (ctype != null) {
charsetName = contentTypeToCharset(ctype);
}
return charsetName;
}
/**
* Attempt to find a META tag in the HTML that hints at the character set
* used to write the document.
*
* @param resource
* @return String character set found from META tags in the HTML
* @throws IOException
*/
protected String getCharsetFromMeta(Resource resource) throws IOException {
String charsetName = null;
byte[] bbuffer = new byte[MAX_CHARSET_READAHEAD];
resource.mark(MAX_CHARSET_READAHEAD);
resource.read(bbuffer, 0, MAX_CHARSET_READAHEAD);
resource.reset();
// convert to UTF-8 String -- which hopefully will not mess up the
// characters we're interested in...
StringBuilder sb = new StringBuilder(new String(bbuffer,"UTF-8"));
String metaContentType = TagMagix.getTagAttrWhere(sb, "META",
"content", "http-equiv", "Content-Type");
if(metaContentType != null) {
charsetName = contentTypeToCharset(metaContentType);
}
return charsetName;
}
/**
* Attempts to figure out the character set of the document using
* the excellent juniversalchardet library.
*
* @param resource
* @return String character encoding found, or null if nothing looked good.
* @throws IOException
*/
protected String getCharsetFromBytes(Resource resource) throws IOException {
String charsetName = null;
byte[] bbuffer = new byte[MAX_CHARSET_READAHEAD];
UniversalDetector detector = new UniversalDetector(null);
resource.mark(MAX_CHARSET_READAHEAD);
int len = resource.read(bbuffer, 0, MAX_CHARSET_READAHEAD);
resource.reset();
detector.handleData(bbuffer, 0, len);
detector.dataEnd();
charsetName = detector.getDetectedCharset();
detector.reset();
return charsetName;
}
/**
* Use META tags, byte-character-detection, HTTP headers, hope, and prayer
* to figure out what character encoding is being used for the document.
* If nothing else works, assumes UTF-8 for now.
*
* @param resource
* @return String charset for Resource
* @throws IOException
*/
protected String guessCharset() throws IOException {
String charSet = getCharsetFromMeta(resource);
if(charSet == null) {
charSet = getCharsetFromBytes(resource);
if(charSet == null) {
charSet = getCharsetFromHeaders(resource);
if(charSet == null) {
charSet = "UTF-8";
}
}
}
return charSet;
}
/**
* Update URLs inside the page, so those URLs which must be correct at
* page load time resolve correctly to absolute URLs.
*
* This means ensuring there is a BASE HREF tag, adding one if missing,
* and then resolving:
* FRAME-SRC, META-URL, LINK-HREF, SCRIPT-SRC
* tag-attribute pairs against either the existing BASE-HREF, or the
* page's absolute URL if it was missing.
*/
public void resolvePageUrls() {
// TODO: get url from Resource instead of SearchResult?
String pageUrl = result.getAbsoluteUrl();
String captureDate = result.getCaptureDate();
String existingBaseHref = TagMagix.getBaseHref(sb);
if (existingBaseHref == null) {
insertAtStartOfHead("<base href=\"" + pageUrl + "\" />");
} else {
pageUrl = existingBaseHref;
}
String markups[][] = {
{"FRAME","SRC"},
{"META","URL"},
{"LINK","HREF"},
{"SCRIPT","SRC"}
};
// TODO: The classic WM added a js_ to the datespec, so NotInArchives
// can return an valid javascript doc, and not cause Javascript errors.
for(String tagAttr[] : markups) {
TagMagix.markupTagREURIC(sb, uriConverter, captureDate, pageUrl,
tagAttr[0], tagAttr[1]);
}
TagMagix.markupCSSImports(sb,uriConverter, captureDate, pageUrl);
TagMagix.markupStyleUrls(sb,uriConverter,captureDate,pageUrl);
}
/**
* Update all URLs inside the page, so they resolve correctly to absolute
* URLs within the Wayback service.
*/
public void resolveAllPageUrls() {
// TODO: get url from Resource instead of SearchResult?
String pageUrl = result.getAbsoluteUrl();
String captureDate = result.getCaptureDate();
String existingBaseHref = TagMagix.getBaseHref(sb);
if (existingBaseHref != null) {
pageUrl = existingBaseHref;
}
ResultURIConverter ruc = new SpecialResultURIConverter(uriConverter);
// TODO: forms...?
String markups[][] = {
{"FRAME","SRC"},
{"META","URL"},
{"LINK","HREF"},
{"SCRIPT","SRC"},
{"IMG","SRC"},
{"A","HREF"},
{"AREA","HREF"},
{"OBJECT","CODEBASE"},
{"OBJECT","CDATA"},
{"APPLET","CODEBASE"},
{"APPLET","ARCHIVE"},
{"EMBED","SRC"},
{"IFRAME","SRC"},
{"BODY","BACKGROUND"},
};
for(String tagAttr[] : markups) {
TagMagix.markupTagREURIC(sb, ruc, captureDate, pageUrl,
tagAttr[0], tagAttr[1]);
}
TagMagix.markupCSSImports(sb,uriConverter, captureDate, pageUrl);
TagMagix.markupStyleUrls(sb,uriConverter,captureDate,pageUrl);
}
public void resolveCSSUrls() {
// TODO: get url from Resource instead of SearchResult?
String pageUrl = result.getAbsoluteUrl();
String captureDate = result.getCaptureDate();
TagMagix.markupCSSImports(sb,uriConverter, captureDate, pageUrl);
}
/**
* @param charSet
* @throws IOException
*/
public void readFully(String charSet) throws IOException {
if(charSet == null) {
charSet = guessCharset();
}
this.charSet = charSet;
int recordLength = (int) resource.getRecordLength();
// convert bytes to characters for charset:
InputStreamReader isr = new InputStreamReader(resource, charSet);
char[] cbuffer = new char[C_BUFFER_SIZE];
// slurp the whole thing into RAM:
sb = new StringBuilder(recordLength);
for (int r = -1; (r = isr.read(cbuffer, 0, C_BUFFER_SIZE)) != -1;) {
sb.append(cbuffer, 0, r);
}
}
/**
* Read bytes from input stream, using best-guess for character encoding
* @throws IOException
*/
public void readFully() throws IOException {
readFully(null);
}
/**
* @return raw bytes contained in internal StringBuilder
* @throws UnsupportedEncodingException
*/
public byte[] getBytes() throws UnsupportedEncodingException {
if(sb == null) {
throw new IllegalStateException("No interal StringBuffer");
}
if(resultBytes == null) {
resultBytes = sb.toString().getBytes(charSet);
}
return resultBytes;
}
/**
* Write the contents of the page to the client.
*
* @param os
* @throws IOException
*/
public void writeToOutputStream(OutputStream os) throws IOException {
if(sb == null) {
throw new IllegalStateException("No interal StringBuffer");
}
byte[] b;
try {
b = getBytes();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
os.write(b);
}
/**
* @param toInsert
*/
public void insertAtStartOfHead(String toInsert) {
int insertPoint = TagMagix.getEndOfFirstTag(sb,"head");
if (-1 == insertPoint) {
insertPoint = 0;
}
sb.insert(insertPoint,toInsert);
}
/**
* @param toInsert
*/
public void insertAtEndOfBody(String toInsert) {
int insertPoint = sb.lastIndexOf("</body>");
if (-1 == insertPoint) {
insertPoint = sb.lastIndexOf("</BODY>");
}
if (-1 == insertPoint) {
insertPoint = sb.length();
}
sb.insert(insertPoint,toInsert);
}
/**
* @param toInsert
*/
public void insertAtStartOfBody(String toInsert) {
int insertPoint = TagMagix.getEndOfFirstTag(sb,"body");
if (-1 == insertPoint) {
insertPoint = 0;
}
sb.insert(insertPoint,toInsert);
}
/**
* @param jspPath
* @param httpRequest
* @param httpResponse
* @param wbRequest
* @param results
* @return
* @throws IOException
* @throws ServletException
* @throws ParseException
*/
public String includeJspString(String jspPath,
HttpServletRequest httpRequest, HttpServletResponse httpResponse,
WaybackRequest wbRequest, SearchResults results, SearchResult result)
throws ServletException, IOException {
UIQueryResults uiResults = new UIQueryResults(httpRequest, wbRequest,
results, uriConverter);
uiResults.setResult(result);
StringHttpServletResponseWrapper wrappedResponse =
new StringHttpServletResponseWrapper(httpResponse);
uiResults.storeInRequest(httpRequest,jspPath);
RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(jspPath);
dispatcher.forward(httpRequest, wrappedResponse);
return wrappedResponse.getStringResponse();
}
/**
* @param jsUrl
* @return
*/
public String getJSIncludeString(final String jsUrl) {
return "<script type=\"text/javascript\" src=\""
+ jsUrl + "\" ></script>\n";
}
/**
* @return the charSet
*/
public String getCharSet() {
return charSet;
}
/**
* @param charSet the charSet to set
*/
public void setCharSet(String charSet) {
this.charSet = charSet;
}
private class SpecialResultURIConverter implements ResultURIConverter {
private static final String EMAIL_PROTOCOL_PREFIX = "mailto:";
private static final String JAVASCRIPT_PROTOCOL_PREFIX = "javascript:";
private ResultURIConverter base = null;
public SpecialResultURIConverter(ResultURIConverter base) {
this.base = base;
}
public String makeReplayURI(String datespec, String url) {
if(url.startsWith(EMAIL_PROTOCOL_PREFIX)) {
return url;
}
if(url.startsWith(JAVASCRIPT_PROTOCOL_PREFIX)) {
return url;
}
return base.makeReplayURI(datespec, url);
}
}
}
|
package jpt.app01.session;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import jpt.app01.user.User;
/**
*
* @author avm
*/
public class Session {
private final User user;
private final String id;
private final Map<String, Object> attributesMap;
public Session(User user) {
this.id = UUID.randomUUID().toString();
this.user = user;
this.attributesMap = new ConcurrentHashMap<>();
}
public void setAttribute(String name, Object attribute) {
synchronized(attributesMap) {
attributesMap.put(name, attribute);
}
}
public Object getAttribute(String name) {
return attributesMap.get(name);
}
public String getId() {
return id;
}
public User getUser() {
return user;
}
public <T> T getOrCreateAttribute(String attributeName, Supplier<? extends T> supplier) {
T result;
synchronized (attributesMap) {
result = (T) attributesMap.get(attributeName);
if (null == result) {
result = supplier.get();
attributesMap.put(attributeName, result);
}
}
return result;
}
@Override
public String toString() {
return String.format("%s:%s", user.getUserid(), id);
}
}
|
package btcsim;
import java.util.ArrayList;
import btcsim.Block.BlockType;
/**
* Node class
*
* @author 7u83 <7u83@mail.ru>
*/
public class Node {
BlockChain chain;
Block distrib;
protected int id;
protected Net net;
String name = null;
int rejected = 0;
public Node() {
chain = new BlockChain();
distrib = null;
}
public Node(String name) {
this();
setName(name);
}
public final void setNetAndId(Net net, int id) {
this.net = net;
this.id = id;
}
/**
* Set the name of the node
*
* @param name name to set
*/
public final void setName(String name) {
this.name = name;
}
/**
* Verfiy a block Override this method to implement own verfifying such as
* UASF
*
* @param block
* @return true: accept the block, false: reject block
*/
boolean checkBlock(Block block) {
return true;
}
boolean addBlock(Block block) {
if (chain.addBlock(block)) {
return true;
}
// Block couldn't be added, means there was no previous
// block in chain
// try to get the previous block from our connected nodes
Block prevblock = null;
for (Node n : connections) {
prevblock = n.getBlock(block.prevhash);
if (prevblock == null)
continue;
if (!checkBlock(prevblock))
return false;
else
break;
}
if (prevblock ==null)
return false;
if (!addBlock(prevblock)){
return false;
}
return chain.addBlock(block);
}
/**
* Receive a (mined) block, frowarded from another node
*
* @param block the block sent to this node
*/
public void receiveBlock(Block block) {
if (!checkBlock(block)) {
rejected++;
return;
}
if (chain.getBlock(block.hash) != null) {
return;
}
if (addBlock(block)) {
distrib = block;
}
}
public Block getBlock(int hash) {
return chain.getBlock(hash);
}
/**
* Check if a block is in nodes data base
*
* @param hash Hash of block
* @return true if block is in database, false if not.
*/
public boolean hasBlock(int hash) {
Block b = getBlock(hash);
return b != null;
}
/**
* Distribute a block to other nodes, to which this node is connected to.
*
* The block to distribute is taken from {@link this.distrib} If
* this.distrib
*
* @return
*/
boolean distributeBlock() {
if (distrib == null) {
return false;
}
for (Node node : connections) {
node.receiveBlock(distrib);
}
distrib = null;
return true;
}
Block mineBlock() {
Block b = net.mineBlock(BlockType.Std, chain.front_block);
// receiveBlock(b);
return b;
}
// We store "connections" to other nodes here
private ArrayList<Node> connections;
/**
* Connect this node to other nodes
*
* @param n Number of connectoins to create
*/
public void connect(int n) {
connections = new ArrayList();
for (int i = 0; i < n; i++) {
int cid = net.random.nextInt(net.nodes.size());
if (cid == id) {
continue;
}
connections.add(net.nodes.get(cid));
}
}
}
|
package com.exedio.cope;
import com.exedio.cope.util.Day;
public class QueryTest extends AbstractRuntimeTest
{
private static final Condition TRUE = Condition.TRUE;
private static final Condition FALSE = Condition.FALSE;
public QueryTest()
{
super(DayFieldTest.MODEL);
}
static final Day d1 = new Day(2006, 02, 19);
static final Day d2 = new Day(2006, 02, 20);
static final Day d3 = new Day(2006, 02, 21);
public void testIt()
{
final Query q = DayItem.TYPE.newQuery(null);
assertEquals(DayItem.TYPE, q.getType());
assertEquals(null, q.getCondition());
assertEqualsUnmodifiable(list(), q.getJoins());
q.narrow(DayItem.day.less(d1));
assertEquals(DayItem.TYPE, q.getType());
assertEquals(DayItem.day.less(d1), q.getCondition());
assertEqualsUnmodifiable(list(), q.getJoins());
q.narrow(DayItem.day.greater(d1));
assertEquals(DayItem.TYPE, q.getType());
assertEquals(DayItem.day.less(d1).and(DayItem.day.greater(d1)), q.getCondition());
assertEqualsUnmodifiable(list(), q.getJoins());
final Condition c1 = DayItem.day.equal(d1);
final Condition c2 = DayItem.day.equal(d2);
assertEquals(c1, DayItem.day.equal(d1));
assertFalse(c1.equals(c2));
assertEquals(c1.and(c2), DayItem.day.equal(d1).and(DayItem.day.equal(d2)));
assertFalse(c1.and(c2).equals(c2.and(c1)));
}
public void testLiterals()
{
final Condition c1 = DayItem.day.equal(d1);
final Condition c2 = DayItem.day.equal(d2);
{
final Query q = DayItem.TYPE.newQuery(TRUE);
assertSame(null, q.getCondition());
model.getCurrentTransaction().setQueryInfoEnabled(true);
assertContains(q.search());
assertTrue(model.getCurrentTransaction().getQueryInfos().get(0).getText().startsWith("select "));
q.narrow(c1);
assertSame(c1, q.getCondition());
q.narrow(c2);
assertEquals(c1.and(c2), q.getCondition());
q.narrow(FALSE);
assertSame(FALSE, q.getCondition());
q.narrow(c1);
assertSame(FALSE, q.getCondition());
}
{
final Query q = DayItem.TYPE.newQuery(FALSE);
assertSame(FALSE, q.getCondition());
model.getCurrentTransaction().setQueryInfoEnabled(true);
assertContains(q.search());
assertEquals("skipped search because condition==false", model.getCurrentTransaction().getQueryInfos().get(0).getText());
q.setCondition(TRUE);
assertSame(null, q.getCondition());
q.setCondition(c1);
assertSame(c1, q.getCondition());
q.setCondition(FALSE);
assertSame(FALSE, q.getCondition());
}
}
public void testResult()
{
assertEquals(list(), Query.emptyResult().getData());
assertEquals(0, Query.emptyResult().getTotal());
assertEquals(0, Query.emptyResult().getOffset());
assertEquals(-1, Query.emptyResult().getLimit());
assertNotSame(Query.emptyResult(), Query.emptyResult());
assertEquals(Query.emptyResult(), Query.emptyResult());
assertEquals(Query.emptyResult().hashCode(), Query.emptyResult().hashCode());
deleteOnTearDown(new DayItem(d1));
deleteOnTearDown(new DayItem(d2));
deleteOnTearDown(new DayItem(d3));
deleteOnTearDown(new DayItem(d1));
deleteOnTearDown(new DayItem(d2));
deleteOnTearDown(new DayItem(d3));
assertEquals(list(d2, d3, d1, d2), r(1, 4).getData());
assertEquals(6, r(1, 4).getTotal());
assertEquals(1, r(1, 4).getOffset());
assertEquals(4, r(1, 4).getLimit());
assertEqualsResult(r(0, 3), r(0, 3));
assertEqualsResult(r(1, 3), r(1, 3));
assertNotEqualsResult(r(0, 3), r(1, 3));
assertNotEqualsResult(r(0, 3), r(1, 4));
assertNotEqualsResult(r(0, 3), r(2, 3));
assertEqualsResult(r(0, 3), r(3, 3)); // TODO
}
private static Query.Result<Day> r(final int offset, final int limit)
{
final Query<Day> q = new Query<Day>(DayItem.day);
q.setOrderBy(DayItem.TYPE.getThis(), true);
q.setLimit(offset, limit);
return q.searchAndTotal();
}
private static void assertEqualsResult(final Query.Result<Day> expected, final Query.Result<Day> actual)
{
assertEquals(expected, actual);
assertEquals(actual, expected);
assertEquals(actual.hashCode(), expected.hashCode());
}
private static void assertNotEqualsResult(final Query.Result<Day> expected, final Query.Result<Day> actual)
{
assertFalse(expected.equals(actual));
assertFalse(actual.equals(expected));
assertFalse(actual.hashCode()==expected.hashCode());
}
}
|
package com.github.devicehive.websocket;
import com.github.devicehive.websocket.api.ConfigurationWS;
import com.github.devicehive.websocket.api.WebSocketClient;
import com.github.devicehive.websocket.listener.ConfigurationListener;
import com.github.devicehive.websocket.model.repsonse.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
class Helper {
private static final String URL = "ws://playground.dev.devicehive.com/api/websocket";
private static final String ACCESS_TOKEN = "***REMOVED***";
private static final String REFRESH_TOKEN = "***REMOVED***";
int awaitTimeout = 30;
TimeUnit awaitTimeUnit = TimeUnit.SECONDS;
WebSocketClient client = new WebSocketClient
.Builder()
.url(URL)
.build();
void authenticate() {
client.authenticate(ACCESS_TOKEN);
}
boolean deleteConfigurations(String name) throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final Counter counter = new Counter();
ConfigurationWS configurationWS = client.createConfigurationWS(new ConfigurationListener() {
@Override
public void onGet(ConfigurationGetResponse response) {
}
@Override
public void onPut(ConfigurationInsertResponse response) {
}
@Override
public void onDelete(ResponseAction response) {
if (response.getStatus().equals(ResponseAction.SUCCESS)) {
counter.increment();
}
latch.countDown();
}
@Override
public void onError(ErrorResponse error) {
}
});
configurationWS.delete(null, name);
latch.await(awaitTimeout, awaitTimeUnit);
return counter.getCount() == 1;
}
}
|
package model.leveleditor;
import model.Matrix;
import model.drawables.Point;
public class Coordinates {
private final double x;
private final double y;
// Position des Punktes
private double posx;
private double posy;
private int angle;
// Faktor, um den skaliert wird
private static int factor = 10;
public Coordinates(double x, double y){
this.x = x;
this.posx = x;
this.y = y;
this.posy = y;
this.angle = 0;
}
/**
* Copy-Konstruktor
*/
public Coordinates(Coordinates toCopy) {
this.x = toCopy.getX();
this.posx = toCopy.getPosx();
this.y = toCopy.getPosy();
this.posy = toCopy.getPosy();
this.angle = toCopy.getAngle();
}
public Point getScaledIntCoordinates() {
// Basis Trafo der Koordinatensysteme
int x = (int) ((factor * this.posx) + 0.5);
int y = (int) ((factor * this.posy) + 0.5);
return new Point(x,y);
}
/**
* Nimmt einen Punkt mit int-Koordinaten und setzt damit die Position neu
* @param point Neue Position
*/
public void setScaledIntCoordinates(Point point) {
double x = point.x / factor;
double y = point.y / factor;
this.posx = x;
this.posy = y;
}
/**
* Umrechnung von Punkt zu Vektor
* @param c Punkt, der Vektor werden soll
* @return berechneter Vektor
*/
public Coordinates getVector(Coordinates c) {
Coordinates v = new Coordinates(0, 0);
v.setPosx(c.getX());
v.setPosy(c.getY());
return v;
}
/**
* Rotiert den Punkt um eine Winkel um einen Punkt
* @param angle Winkel, un den rotiert wird
* @param point Punkt, um den Rotiert wird
*/
public void rotation(int angle, Coordinates point){
double[][] translate = {{1, 0, -point.getPosx()},
{0, 1, -point.getPosy()},{0,0,1}};
Matrix translateTo = new Matrix(translate);
translate[0][2] = point.getPosx();
translate[1][3] = point.getPosy();
Matrix translateFrom = new Matrix(translate);
double[][] rotate = {{Math.cos(angle), -Math.sin(angle), 0},
{Math.sin(angle), Math.cos(angle), 0},{0,0,1}};
Matrix rotation = new Matrix(rotate);
double[][] arrPoint = {{this.posx},
{this.posy},{1}};
Matrix matPoint = new Matrix(arrPoint);
matPoint = translateTo.multiply(matPoint);
matPoint = rotation.multiply(matPoint);
matPoint = translateFrom.multiply(matPoint);
this.posx = matPoint.getValue(0, 0);
this.posy = matPoint.getValue(1, 0);
this.angle = this.angle + angle % 360;
}
public void translate(Coordinates point) {
double[][] translate = {{1, 0, point.getPosx()},
{0, 1, point.getPosy()},{0,0,1}};
Matrix translateTo = new Matrix(translate);
double[][] arrPoint = {{this.posx},
{this.posy},{1}};
Matrix matPoint = new Matrix(arrPoint);
matPoint = translateTo.multiply(matPoint);
this.posx = matPoint.getValue(0, 0);
this.posy = matPoint.getValue(1, 0);
}
/**
* Berechnet die Distanz zu einem anderen Punkt
* @param point Punkt, zu dem die Distanz berechnet wird
* @return Distanz
*/
public double distanceTo(Coordinates point) {
double newX = Math.pow(this.posx - point.getPosx(), 2);
double newY = Math.pow(this.posy - point.getPosy(), 2);
double distance = Math.sqrt(newX + newY);
return distance;
}
public Coordinates getInvert() {
double newX = -1 * this.x;
double newY = -1 * this.y;
double newPosx = -1 * this.posx;
double newPosy = -1 * this.posy;
int angle = (this.angle + 180) % 360;
Coordinates v = new Coordinates(newX, newY);
v.setPosx(newPosx);
v.setPosy(newPosy);
v.setAngle(angle);
return v;
}
/**
* Addiert einen Punkt auf den aktuellen Punkt
* Nur bzgl Pos, x&y werden jeweils auf 0 gesetzt
* @param point Punkt, der addiert wird
* @return Summe der Punkte
*/
public Coordinates addCoordinats(Coordinates point) {
double newPosX = this.posx + point.getPosx();
double newPosY = this.posy + point.getPosy();
Coordinates v = new Coordinates(0, 0);
v.setPosx(newPosX);
v.setPosy(newPosY);
return v;
}
/**
* Gibt die Koordinaten, die bzgl des Double-Koordinatensystems gegeben sind,
* in Koordinaten bzgl des Int-Koordinatensystem um
* @param c unzurechnende Koordinaten
* @return umgerechnete Koordinaten
*/
public static Point basisChangeDoubleInt(Coordinates c) {
int width = 800;
int heigth = 640;
int newX = c.getScaledIntCoordinates().x - (width / 2);
int newY = c.getScaledIntCoordinates().y - (heigth / 2);
return new Point(newX, newY);
}
/**
* Gibt die Koordinaten, die bzgl des Int-Koordinatensystems gegeben sind,
* in Koordinaten bzgl des Double-Koordinatensystem um
* @param c unzurechnende Koordinaten
* @return umgerechnete Koordinaten
*/
public static Coordinates basisChangeIntDouble(Point p) {
int width = 800;
int heigth = 640;
double newX = (p.x / factor) + (width / 2);
double newY = (p.y / factor) + (heigth / 2);
return new Coordinates(newX, newY);
}
public double getPosx() {
return posx;
}
public void setPosx(double posx) {
this.posx = posx;
}
public double getPosy() {
return posy;
}
public void setPosy(double posy) {
this.posy = posy;
}
public void setPos(Coordinates pos) {
this.posx = pos.getPosx();
this.posy = pos.getPosy();
}
public int getAngle() {
return angle;
}
public void setAngle(int angle) {
this.angle = angle;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public static int getFactor() {
return factor;
}
public static void setFactor(int factorNew) {
factor = factorNew;
}
}
|
package etomica.data.types;
import etomica.data.Data;
import etomica.data.DataFactory;
import etomica.data.DataGroupExtractor;
import etomica.data.DataInfo;
import etomica.data.DataJudge;
import etomica.data.DataProcessor;
import etomica.space.Tensor;
import etomica.space.Vector;
import etomica.units.Dimension;
/**
* A DataProcessor that converts a homogeneous DataGroup into a multidimensional DataDoubleArray.
* All elements in group must be of the same data type. If the group contains only one element,
* the effect is the same as applying CastToDoubleArray to the element. Otherwise, if <tt>d</tt>
* is the dimension of each grouped element, the resulting DataDoubleArray will be of
* dimension <tt>d+1</tt>. The added dimension corresponds to the different elements of the group.
* <p>
* For example:
* <ul>
* <li>if the DataGroup contains 8 DataDouble instances (thus d = 0), the cast gives a
* one-dimensional DataDoubleArray of length 8.
* <li>if the DataGroup contains 4 Vector3D instances (thus d = 1), the cast gives a two-dimensional DataDoubleArray
* of dimensions (4, 3).
* <li>if the DataGroup contains 5 two-dimensional (d = 2) DataDoubleArray of shape (7,80), the cast gives a
* three-dimensional DataDoubleArray of shape (5, 7, 80).
* </ul>
* etc.
*
* @author David Kofke
*
*/
public class CastGroupToDoubleArray extends DataProcessor {
/**
* Sole constructor.
*/
public CastGroupToDoubleArray() {
}
protected DataInfo processDataInfo(DataInfo inputDataInfo) {
if (inputDataInfo.getDataClass() != DataGroup.class) {
throw new IllegalArgumentException("can only cast from DataGroup");
}
String label = inputDataInfo.getLabel();
Dimension dimension = inputDataInfo.getDimension();
DataFactory factory = inputDataInfo.getDataFactory();
Data[] data = ((DataGroup.Factory)inputDataInfo.getDataFactory()).data;
if (data.length == 0) {
inputType = 0;
outputData = new DataDoubleArray(label,dimension,0);
return outputData.getDataInfo();
}
Class innerDataClass = data[0].getClass();
for (int i = 1; i<data.length; i++) {
if (data[i].getClass() != innerDataClass) {
throw new IllegalArgumentException("CastGroupToDoubleArray can only handle homogeneous groups");
}
}
if (innerDataClass == DataDoubleArray.class) {
DataDoubleArray dataArray = (DataDoubleArray)data[0];
int D = dataArray.getArrayDimension();
int[] size;
if (data.length == 1) {
inputType = 1;
outputData = dataArray;
}
else {
size = new int[++D];
size[0] = data.length;
for (int i=1; i<D; i++) {
size[i] = dataArray.getArrayShape(i-1);
}
inputType = 2;
outputData = new DataDoubleArray(label, dimension, size);
}
} else if (innerDataClass == DataDouble.class) {
inputType = 3;
outputData = new DataDoubleArray(label, dimension, data.length);
} else if (innerDataClass == DataInteger.class) {
inputType = 4;
outputData = new DataDoubleArray(label, dimension, data.length);
} else if (innerDataClass == DataVector.class) {
int D = ((DataVector.Factory)factory).getSpace().D();
if (data.length == 1) {
inputType = 5;
outputData = new DataDoubleArray(label, dimension, D);
}
else {
inputType = 6;
outputData = new DataDoubleArray(label, dimension, new int[]{data.length,D});
}
} else if (innerDataClass == DataTensor.class) {
int D = ((DataTensor.Factory)factory).getSpace().D();
if (data.length == 1) {
inputType = 7;
outputData = new DataDoubleArray(label, dimension, new int[] {D, D});
}
else {
inputType = 8;
outputData = new DataDoubleArray(label, dimension, new int[] {data.length, D, D});
}
} else if(innerDataClass == DataFunction.class) {
int[] sizes = ((DataFunction.Factory)factory).getIndependentDataSizes();
inputType = 9;
if (data.length != 1) {
inputType = 10;
int[] newSizes = new int[sizes.length+1];
newSizes[0] = data.length;
System.arraycopy(sizes,0,newSizes,1,sizes.length);
sizes = newSizes;
}
outputData = new DataDoubleArray(label, dimension, sizes);
} else if(innerDataClass == DataGroup.class) {
inputType = 11;
DataGroupExtractor extractor = new DataGroupExtractor(new DataJudge.ByClass(DataDoubleArray.class, true));
extractor.putDataInfo(inputDataInfo);
outputData = (DataDoubleArray)extractor.processData(null);
} else {
throw new IllegalArgumentException("Cannot cast to DataDoubleArray from "
+ innerDataClass + "in DataGroup");
}
return outputData.getDataInfo();
}
/**
* Converts data in given group to a DataDoubleArray as described in the
* general comments for this class.
*
* @throws ClassCastException
* if the given Data is not a DataGroup with Data elements of
* the type indicated by the most recent call to
* processDataInfo.
*/
protected Data processData(Data data) {
DataGroup group = (DataGroup)data;
switch (inputType) {
case 0: // empty group
return outputData;
case 1: // a single DataDoubleArray
return outputData;
case 2: // multiple DataDoubleArrays
for (int i=0; i<group.getNData(); i++) {
outputData.assignColumnFrom(i,((DataDoubleArray)group.getData(i)).getData());
}
return outputData;
case 3: // DataDouble(s)
for (int i=0; i<group.getNData(); i++) {
outputData.getData()[i] = ((DataDouble)group.getData(i)).x;
}
return outputData;
case 4: // DataInteger(s)
for (int i=0; i<group.getNData(); i++) {
outputData.getData()[i] = ((DataInteger)group.getData(i)).x;
}
return outputData;
case 5: // a single DataVector
((DataVector)group.getData(0)).assignTo(outputData.getData());
return outputData;
case 6: // multiple DataVectors
double[] x = outputData.getData();
int k=0;
for (int i=0; i<group.getNData(); i++) {
Vector v = ((DataVector)group.getData(i)).x;
for (int j=0; j<v.D(); j++) {
x[k++] = v.x(j);
}
}
return outputData;
case 7: // a single DataTensor
((DataTensor)group.getData(0)).assignTo(outputData.getData());
return outputData;
case 8: // multiple DataTensors
x = outputData.getData();
k=0;
for (int i=0; i<group.getNData(); i++) {
Tensor t = ((DataTensor)group.getData(i)).x;
for (int j=0; j<t.length(); j++) {
for (int l=0; l<t.length(); l++) {
x[k++] = t.component(j,l);
}
}
}
return outputData;
case 9:
outputData.E(((DataFunction)group.getData(0)).getYData());
return outputData;
case 10:
for (int i=0; i<group.getNData(); i++) {
outputData.assignColumnFrom(i,((DataFunction)group.getData(0)).getYData().getData());
}
return outputData;
case 11:
return outputData;
default:
throw new Error("Assertion error. Input type out of range: "+inputType);
}
}
/**
* Returns null.
*/
public DataProcessor getDataCaster(DataInfo info) {
return null;
}
private DataDoubleArray outputData;
private int inputType;
}
|
package etomica.phase;
import etomica.atom.AtomAgentManager;
import etomica.atom.AtomAgentManager.AgentSource;
import etomica.phase.PhaseAgentManager.PhaseAgentSource;
public class PhaseAgentSourceAtomManager implements PhaseAgentSource, java.io.Serializable {
public PhaseAgentSourceAtomManager(AgentSource atomAgentSource) {
super();
this.atomAgentSource = atomAgentSource;
}
public Class getAgentClass() {
return AtomAgentManager.class;
}
public Object makeAgent(Phase phase) {
return new AtomAgentManager(atomAgentSource,phase);
}
public void releaseAgent(Object agent) {
((AtomAgentManager)agent).dispose();
}
private static final long serialVersionUID = 1L;
private final AgentSource atomAgentSource;
}
|
package foam.nanos.pm;
import foam.core.ContextAwareSupport;
import foam.dao.DAO;
public class DAOPMLogger
extends ContextAwareSupport
implements PMLogger
{
public final static String SERVICE_NAME = "pmLogger";
public final static String DAO_NAME = "pmInfoDAO";
protected final Object[] locks_ = new Object[128];
public DAOPMLogger() {
for ( int i = 0 ; i < locks_.length ; i++ ) locks_[i] = new Object();
}
protected Object getLock(PMInfo pmi) {
int hash = pmi.getClsName().hashCode() * 31 + pmi.getPmName().hashCode();
return locks_[(int) (Math.abs(hash) % locks_.length)];
}
@Override
public void log(PM pm) {
if ( pm.getClassType().getName().indexOf("PM") != -1 ) return;
if ( pm.getName().indexOf("PM") != -1 ) return;
if ( pm.getClassType().getName().indexOf("pm") != -1 ) return;
if ( pm.getName().indexOf("pm") != -1 ) return;
PMInfo pmi = new PMInfo();
pmi.setClsName(pm.getClassType().getName());
pmi.setPmName(pm.getName());
DAO pmd = (DAO) getX().get(DAO_NAME);
synchronized ( getLock(pmi) ) {
PMInfo dpmi = (PMInfo) pmd.find(pmi);
if ( dpmi == null ) {
pmi.setMinTime(pm.getTime());
pmi.setMaxTime(pm.getTime());
pmi.setTotalTime(pm.getTime());
pmi.setCount(1);
pmd.put(pmi);
} else {
if ( pm.getTime() < dpmi.getMinTime() )
dpmi.setMinTime(pm.getTime());
if ( pm.getTime() > dpmi.getMaxTime() )
dpmi.setMaxTime(pm.getTime());
dpmi.setCount(dpmi.getCount() + 1);
dpmi.setTotalTime(dpmi.getTotalTime() + pm.getTime());
pmd.put(dpmi);
}
}
}
}
|
package wyc.builder;
import static wybs.lang.SyntaxError.internalFailure;
import static wybs.lang.SyntaxError.syntaxError;
import static wyc.lang.WhileyFile.internalFailure;
import static wyc.lang.WhileyFile.syntaxError;
import static wyil.util.ErrorMessages.*;
import java.math.BigDecimal;
import java.util.*;
import wyautl_old.lang.Automata;
import wyautl_old.lang.Automaton;
import wybs.lang.*;
import wybs.util.*;
import wyc.lang.Expr;
import wyc.lang.Exprs;
import wyc.lang.Stmt;
import wyc.lang.SyntacticType;
import wyc.lang.TypePattern;
import wyc.lang.WhileyFile;
import wyc.lang.WhileyFile.Context;
import wyc.lang.WhileyFile.Declaration;
import wyil.lang.Constant;
import wyil.lang.Type;
import wyil.lang.WyilFile;
/**
* Propagates type information in a flow-sensitive fashion from declared
* parameter and return types through assigned expressions, to determine types
* for all intermediate expressions and variables. For example:
*
* <pre>
* function sum([int] data) => int:
* int r = 0 // declared int type for r
* for v in data: // infers int type for v, based on type of data
* r = r + v // infers int type for r + v, based on type of operands
* return r // infers int type for return expression
* </pre>
*
* Loops present an interesting challenge for type propagation. Consider this
* example:
*
* <pre>
* function loopy(int max) => real:
* var i = 0
* while i < max:
* i = i + 0.5
* return i
* </pre>
*
* On the first pass through the loop, variable <code>i</code> is inferred to
* have type <code>int</code> (based on the type of the constant <code>0</code>
* ). However, the add expression is inferred to have type <code>real</code>
* (based on the type of the rhs) and, hence, the resulting type inferred for
* <code>i</code> is <code>real</code>. At this point, the loop must be
* reconsidered taking into account this updated type for <code>i</code>.
*
* <h3>References</h3>
* <ul>
* <li>
* <p>
* David J. Pearce and James Noble. Structural and Flow-Sensitive Types for
* Whiley. Technical Report, Victoria University of Wellington, 2010.
* </p>
* </li>
* </ul>
*
* @author David J. Pearce
*
*/
public class FlowTypeChecker {
private WhileyBuilder builder;
private ArrayList<Scope> scopes = new ArrayList<Scope>();
private String filename;
private WhileyFile.FunctionOrMethod current;
/**
* The constant cache contains a cache of expanded constant values.
*/
private final HashMap<NameID, Constant> constantCache = new HashMap();
// Type Declarations
// Constrant Declarations
// Function Declarations
// Blocks & Statements
private Environment propagate(ArrayList<Stmt> body, Environment environment) {
for (int i = 0; i != body.size(); ++i) {
Stmt stmt = body.get(i);
if (stmt instanceof Expr) {
body.set(i, (Stmt) resolve((Expr) stmt, environment, current));
} else {
environment = propagate(stmt, environment);
}
}
return environment;
}
private Environment propagate(Stmt stmt,
Environment environment) {
try {
if(stmt instanceof Stmt.VariableDeclaration) {
return propagate((Stmt.VariableDeclaration) stmt,environment);
} else if(stmt instanceof Stmt.Assign) {
return propagate((Stmt.Assign) stmt,environment);
} else if(stmt instanceof Stmt.Return) {
return propagate((Stmt.Return) stmt,environment);
} else if(stmt instanceof Stmt.IfElse) {
return propagate((Stmt.IfElse) stmt,environment);
} else if(stmt instanceof Stmt.While) {
return propagate((Stmt.While) stmt,environment);
} else if(stmt instanceof Stmt.ForAll) {
return propagate((Stmt.ForAll) stmt,environment);
} else if(stmt instanceof Stmt.Switch) {
return propagate((Stmt.Switch) stmt,environment);
} else if(stmt instanceof Stmt.DoWhile) {
return propagate((Stmt.DoWhile) stmt,environment);
} else if(stmt instanceof Stmt.Break) {
return propagate((Stmt.Break) stmt,environment);
} else if(stmt instanceof Stmt.Throw) {
return propagate((Stmt.Throw) stmt,environment);
} else if(stmt instanceof Stmt.TryCatch) {
return propagate((Stmt.TryCatch) stmt,environment);
} else if(stmt instanceof Stmt.Assert) {
return propagate((Stmt.Assert) stmt,environment);
} else if(stmt instanceof Stmt.Assume) {
return propagate((Stmt.Assume) stmt,environment);
} else if(stmt instanceof Stmt.Debug) {
return propagate((Stmt.Debug) stmt,environment);
} else if(stmt instanceof Stmt.Skip) {
return propagate((Stmt.Skip) stmt,environment);
} else {
internalFailure("unknown statement: " + stmt.getClass().getName(),filename,stmt);
return null; // deadcode
}
} catch(ResolveError e) {
syntaxError(errorMessage(RESOLUTION_ERROR,e.getMessage()),filename,stmt,e);
return null; // dead code
} catch(SyntaxError e) {
throw e;
} catch(Throwable e) {
internalFailure(e.getMessage(),filename,stmt,e);
return null; // dead code
}
}
private Environment propagate(Stmt.Assert stmt,
Environment environment) {
stmt.expr = resolve(stmt.expr,environment,current);
checkIsSubtype(Type.T_BOOL,stmt.expr);
return environment;
}
private Environment propagate(Stmt.Assume stmt,
Environment environment) {
stmt.expr = resolve(stmt.expr,environment,current);
checkIsSubtype(Type.T_BOOL,stmt.expr);
return environment;
}
private Environment propagate(Stmt.VariableDeclaration stmt,
Environment environment) throws Exception {
// First, resolve declared type
Nominal type = resolveAsType(stmt.type,current);
// First, resolve type of initialiser
if(stmt.expr != null) {
stmt.expr = resolve(stmt.expr,environment,current);
checkIsSubtype(type,stmt.expr);
}
// Second, update environment accordingly. Observe that we can safely
// assume the variable is not already declared in the enclosing scope
// because the parser checks this for us.
environment = environment.put(stmt.name, type);
// Done.
return environment;
}
private Environment propagate(Stmt.Assign stmt,
Environment environment) throws Exception {
Expr.LVal lhs = propagate(stmt.lhs,environment);
Expr rhs = resolve(stmt.rhs,environment,current);
if(lhs instanceof Expr.RationalLVal) {
// represents a destructuring assignment
Expr.RationalLVal tv = (Expr.RationalLVal) lhs;
if(!Type.isImplicitCoerciveSubtype(Type.T_REAL, rhs.result().raw())) {
syntaxError("real value expected, got " + rhs.result(),filename,rhs);
}
if (tv.numerator instanceof Expr.AssignedVariable
&& tv.denominator instanceof Expr.AssignedVariable) {
Expr.AssignedVariable lv = (Expr.AssignedVariable) tv.numerator;
Expr.AssignedVariable rv = (Expr.AssignedVariable) tv.denominator;
lv.type = Nominal.T_VOID;
rv.type = Nominal.T_VOID;
lv.afterType = Nominal.T_INT;
rv.afterType = Nominal.T_INT;
environment = environment.put(lv.var, Nominal.T_INT);
environment = environment.put(rv.var, Nominal.T_INT);
} else {
syntaxError(errorMessage(INVALID_TUPLE_LVAL),filename,lhs);
}
} else if(lhs instanceof Expr.Tuple) {
// represents a destructuring assignment
Expr.Tuple tv = (Expr.Tuple) lhs;
ArrayList<Expr> tvFields = tv.fields;
// FIXME: loss of nominal information here
Type rawRhs = rhs.result().raw();
Nominal.EffectiveTuple tupleRhs = expandAsEffectiveTuple(rhs.result());
// FIXME: the following is something of a kludge. It would also be
// nice to support more expressive destructuring assignment
// operations.
if(tupleRhs == null) {
syntaxError("tuple value expected, got " + rhs.result().nominal(),filename,rhs);
return null; // deadcode
}
List<Nominal> rhsElements = tupleRhs.elements();
if(rhsElements.size() != tvFields.size()) {
syntaxError("incompatible tuple assignment",filename,rhs);
}
for(int i=0;i!=tvFields.size();++i) {
Expr f = tvFields.get(i);
Nominal t = rhsElements.get(i);
if(f instanceof Expr.AbstractVariable) {
Expr.AbstractVariable av = (Expr.AbstractVariable) f;
Expr.AssignedVariable lv;
if(lhs instanceof Expr.AssignedVariable) {
// this case just avoids creating another object everytime we
// visit this statement.
lv = (Expr.AssignedVariable) lhs;
} else {
lv = new Expr.AssignedVariable(av.var, av.attributes());
}
lv.type = Nominal.T_VOID;
lv.afterType = t;
environment = environment.put(lv.var, t);
tvFields.set(i, lv);
} else {
syntaxError(errorMessage(INVALID_TUPLE_LVAL),filename,f);
}
}
} else {
Expr.AssignedVariable av = inferAfterType(lhs, rhs.result());
environment = environment.put(av.var, av.afterType);
}
stmt.lhs = (Expr.LVal) lhs;
stmt.rhs = rhs;
return environment;
}
private Expr.AssignedVariable inferAfterType(Expr.LVal lv,
Nominal afterType) {
if (lv instanceof Expr.AssignedVariable) {
Expr.AssignedVariable v = (Expr.AssignedVariable) lv;
v.afterType = afterType;
return v;
} else if (lv instanceof Expr.Dereference) {
Expr.Dereference pa = (Expr.Dereference) lv;
// NOTE: the before and after types are the same since an assignment
// through a reference does not change its type.
checkIsSubtype(pa.srcType,Nominal.Reference(afterType),lv);
return inferAfterType((Expr.LVal) pa.src, pa.srcType);
} else if (lv instanceof Expr.IndexOf) {
Expr.IndexOf la = (Expr.IndexOf) lv;
Nominal.EffectiveIndexible srcType = la.srcType;
afterType = (Nominal) srcType.update(la.index.result(), afterType);
return inferAfterType((Expr.LVal) la.src,
afterType);
} else if(lv instanceof Expr.FieldAccess) {
Expr.FieldAccess la = (Expr.FieldAccess) lv;
Nominal.EffectiveRecord srcType = la.srcType;
// NOTE: I know I can modify this hash map, since it's created fresh
// in Nominal.Record.fields().
afterType = (Nominal) srcType.update(la.name, afterType);
return inferAfterType((Expr.LVal) la.src, afterType);
} else {
internalFailure("unknown lval: "
+ lv.getClass().getName(), filename, lv);
return null; //deadcode
}
}
private Environment propagate(Stmt.Break stmt,
Environment environment) {
// FIXME: need to propagate environment to the break destination
return BOTTOM;
}
private Environment propagate(Stmt.Debug stmt,
Environment environment) {
stmt.expr = resolve(stmt.expr,environment,current);
checkIsSubtype(Type.T_STRING,stmt.expr);
return environment;
}
private Environment propagate(Stmt.DoWhile stmt,
Environment environment) {
// Iterate to a fixed point
Environment old = null;
Environment tmp = null;
Environment orig = environment.clone();
boolean firstTime=true;
do {
old = environment.clone();
if(!firstTime) {
// don't do this on the first go around, to mimick how the
// do-while loop works.
tmp = resolve(stmt.condition,true,old.clone(),current).second();
environment = join(orig.clone(),propagate(stmt.body,tmp));
} else {
firstTime=false;
environment = join(orig.clone(),propagate(stmt.body,old));
}
old.free(); // hacky, but safe
} while(!environment.equals(old));
List<Expr> stmt_invariants = stmt.invariants;
for (int i = 0; i != stmt_invariants.size(); ++i) {
Expr invariant = stmt_invariants.get(i);
invariant = resolve(invariant, environment, current);
stmt_invariants.set(i, invariant);
checkIsSubtype(Type.T_BOOL, invariant);
}
Pair<Expr,Environment> p = resolve(stmt.condition,false,environment,current);
stmt.condition = p.first();
environment = p.second();
return environment;
}
private Environment propagate(Stmt.ForAll stmt,
Environment environment) throws Exception {
stmt.source = resolve(stmt.source,environment,current);
Nominal.EffectiveCollection srcType = expandAsEffectiveCollection(stmt.source.result());
stmt.srcType = srcType;
if(srcType == null) {
syntaxError(errorMessage(INVALID_SET_OR_LIST_EXPRESSION),filename,stmt);
}
// At this point, the major task is to determine what the types for the
// iteration variables declared in the for loop. More than one variable
// is permitted in some cases.
Nominal[] elementTypes = new Nominal[stmt.variables.size()];
if(elementTypes.length == 2 && srcType instanceof Nominal.EffectiveMap) {
Nominal.EffectiveMap dt = (Nominal.EffectiveMap) srcType;
elementTypes[0] = dt.key();
elementTypes[1] = dt.value();
} else {
if(elementTypes.length == 1) {
elementTypes[0] = srcType.element();
} else {
syntaxError(errorMessage(VARIABLE_POSSIBLY_UNITIALISED),filename,stmt);
}
}
// Now, update the environment to include those declared variables
ArrayList<String> stmtVariables = stmt.variables;
for(int i=0;i!=elementTypes.length;++i) {
String var = stmtVariables.get(i);
if (environment.containsKey(var)) {
syntaxError(errorMessage(VARIABLE_ALREADY_DEFINED,var),
filename, stmt);
}
environment = environment.put(var, elementTypes[i]);
}
// Iterate to a fixed point
Environment old = null;
Environment orig = environment.clone();
do {
old = environment.clone();
environment = join(orig.clone(),propagate(stmt.body,old));
old.free(); // hacky, but safe
} while(!environment.equals(old));
// Remove loop variables from the environment, since they are only
// declared for the duration of the body but not beyond.
for(int i=0;i!=elementTypes.length;++i) {
String var = stmtVariables.get(i);
environment = environment.remove(var);
}
if (stmt.invariant != null) {
stmt.invariant = resolve(stmt.invariant, environment, current);
checkIsSubtype(Type.T_BOOL,stmt.invariant);
}
return environment;
}
private Environment propagate(Stmt.IfElse stmt,
Environment environment) {
// First, check condition and apply variable retypings.
Pair<Expr,Environment> p1,p2;
p1 = resolve(stmt.condition,true,environment.clone(),current);
p2 = resolve(stmt.condition,false,environment,current);
stmt.condition = p1.first();
Environment trueEnvironment = p1.second();
Environment falseEnvironment = p2.second();
// Second, update environments for true and false branches
if(stmt.trueBranch != null && stmt.falseBranch != null) {
trueEnvironment = propagate(stmt.trueBranch,trueEnvironment);
falseEnvironment = propagate(stmt.falseBranch,falseEnvironment);
} else if(stmt.trueBranch != null) {
trueEnvironment = propagate(stmt.trueBranch,trueEnvironment);
} else if(stmt.falseBranch != null){
trueEnvironment = environment;
falseEnvironment = propagate(stmt.falseBranch,falseEnvironment);
}
// Finally, join results back together
return join(trueEnvironment,falseEnvironment);
}
private Environment propagate(
Stmt.Return stmt,
Environment environment) throws Exception {
if (stmt.expr != null) {
stmt.expr = resolve(stmt.expr, environment,current);
Nominal rhs = stmt.expr.result();
checkIsSubtype(current.resolvedType().ret(),rhs, stmt.expr);
}
environment.free();
return BOTTOM;
}
private Environment propagate(Stmt.Skip stmt,
Environment environment) {
return environment;
}
private Environment propagate(Stmt.Switch stmt,
Environment environment) throws Exception {
stmt.expr = resolve(stmt.expr,environment,current);
Environment finalEnv = null;
boolean hasDefault = false;
for(Stmt.Case c : stmt.cases) {
// first, resolve the constants
ArrayList<Constant> values = new ArrayList<Constant>();
for(Expr e : c.expr) {
values.add(resolveAsConstant(e,current));
}
c.constants = values;
// second, propagate through the statements
Environment localEnv = environment.clone();
localEnv = propagate(c.stmts,localEnv);
if(finalEnv == null) {
finalEnv = localEnv;
} else {
finalEnv = join(finalEnv,localEnv);
}
// third, keep track of whether a default
hasDefault |= c.expr.isEmpty();
}
if(!hasDefault) {
// in this case, there is no default case in the switch. We must
// therefore assume that there are values which will fall right
// through the switch statement without hitting a case. Therefore,
// we must include the original environment to accound for this.
finalEnv = join(finalEnv,environment);
} else {
environment.free();
}
return finalEnv;
}
private Environment propagate(Stmt.Throw stmt,
Environment environment) {
stmt.expr = resolve(stmt.expr,environment,current);
return BOTTOM;
}
private Environment propagate(Stmt.TryCatch stmt,
Environment environment) throws Exception {
for(Stmt.Catch handler : stmt.catches) {
// FIXME: need to deal with handler environments properly!
try {
Nominal type = resolveAsType(handler.unresolvedType,current);
handler.type = type;
Environment local = environment.clone();
local = local.put(handler.variable, type);
propagate(handler.stmts,local);
local.free();
} catch(SyntaxError e) {
throw e;
} catch(Throwable t) {
internalFailure(t.getMessage(),filename,handler,t);
}
}
environment = propagate(stmt.body,environment);
// need to do handlers here
return environment;
}
private Environment propagate(Stmt.While stmt,
Environment environment) {
// Iterate to a fixed point
Environment old = null;
Environment tmp = null;
Environment orig = environment.clone();
do {
old = environment.clone();
tmp = resolve(stmt.condition,true,old.clone(),current).second();
environment = join(orig.clone(),propagate(stmt.body,tmp));
old.free(); // hacky, but safe
} while(!environment.equals(old));
List<Expr> stmt_invariants = stmt.invariants;
for (int i = 0; i != stmt_invariants.size(); ++i) {
Expr invariant = stmt_invariants.get(i);
invariant = resolve(invariant, environment, current);
stmt_invariants.set(i, invariant);
checkIsSubtype(Type.T_BOOL, invariant);
}
Pair<Expr,Environment> p = resolve(stmt.condition,false,environment,current);
stmt.condition = p.first();
environment = p.second();
return environment;
}
private Expr.LVal propagate(Expr.LVal lval,
Environment environment) {
try {
if(lval instanceof Expr.AbstractVariable) {
Expr.AbstractVariable av = (Expr.AbstractVariable) lval;
Nominal p = environment.get(av.var);
if(p == null) {
syntaxError(errorMessage(UNKNOWN_VARIABLE),filename,lval);
}
Expr.AssignedVariable lv = new Expr.AssignedVariable(av.var, av.attributes());
lv.type = p;
return lv;
} else if(lval instanceof Expr.RationalLVal) {
Expr.RationalLVal av = (Expr.RationalLVal) lval;
av.numerator = propagate(av.numerator,environment);
av.denominator = propagate(av.numerator,environment);
return av;
} else if(lval instanceof Expr.Dereference) {
Expr.Dereference pa = (Expr.Dereference) lval;
Expr.LVal src = propagate((Expr.LVal) pa.src,environment);
pa.src = src;
pa.srcType = expandAsReference(src.result());
return pa;
} else if(lval instanceof Expr.IndexOf) {
// this indicates either a list, string or dictionary update
Expr.IndexOf ai = (Expr.IndexOf) lval;
Expr.LVal src = propagate((Expr.LVal) ai.src,environment);
Expr index = resolve(ai.index,environment,current);
ai.src = src;
ai.index = index;
Nominal.EffectiveIndexible srcType = expandAsEffectiveMap(src.result());
if(srcType == null) {
syntaxError(errorMessage(INVALID_LVAL_EXPRESSION),filename,lval);
}
ai.srcType = srcType;
return ai;
} else if(lval instanceof Expr.AbstractDotAccess) {
// this indicates a record update
Expr.AbstractDotAccess ad = (Expr.AbstractDotAccess) lval;
Expr.LVal src = propagate((Expr.LVal) ad.src,environment);
Expr.FieldAccess ra = new Expr.FieldAccess(src, ad.name, ad.attributes());
Nominal.EffectiveRecord srcType = expandAsEffectiveRecord(src.result());
if(srcType == null) {
syntaxError(errorMessage(INVALID_LVAL_EXPRESSION),filename,lval);
} else if(srcType.field(ra.name) == null) {
syntaxError(errorMessage(RECORD_MISSING_FIELD,ra.name),filename,lval);
}
ra.srcType = srcType;
return ra;
}
} catch(SyntaxError e) {
throw e;
} catch(Throwable e) {
internalFailure(e.getMessage(),filename,lval,e);
return null; // dead code
}
internalFailure("unknown lval: " + lval.getClass().getName(),filename,lval);
return null; // dead code
}
// Check t1 :> t2
private void checkIsSubtype(Nominal t1, Nominal t2,
SyntacticElement elem) {
if (!Type.isImplicitCoerciveSubtype(t1.raw(), t2.raw())) {
syntaxError(
errorMessage(SUBTYPE_ERROR, t1.nominal(), t2.nominal()),
filename, elem);
}
}
private void checkIsSubtype(Nominal t1, Expr t2) {
if (!Type.isImplicitCoerciveSubtype(t1.raw(), t2.result().raw())) {
// We use the nominal type for error reporting, since this includes
// more helpful names.
syntaxError(
errorMessage(SUBTYPE_ERROR, t1.nominal(), t2.result()
.nominal()), filename, t2);
}
}
private void checkIsSubtype(Type t1, Expr t2) {
if (!Type.isImplicitCoerciveSubtype(t1, t2.result().raw())) {
// We use the nominal type for error reporting, since this includes
// more helpful names.
syntaxError(errorMessage(SUBTYPE_ERROR, t1, t2.result().nominal()),
filename, t2);
}
}
/**
* The purpose of this method is to add variable names declared within a
* type pattern. For example, as follows:
*
* <pre>
* define tup as {int x, int y} where x < y
* </pre>
*
* In this case, <code>x</code> and <code>y</code> are variable names
* declared as part of the pattern.
*
* @param src
* @param t
* @param environment
*/
private Environment addDeclaredVariables(TypePattern pattern,
Environment environment, WhileyFile.Context context) {
if(pattern instanceof TypePattern.Leaf) {
// do nout!
} else if(pattern instanceof TypePattern.Union) {
// FIXME: in principle, we can do better here. However, I leave this
// unusual case for the future.
} else if(pattern instanceof TypePattern.Intersection) {
// FIXME: in principle, we can do better here. However, I leave this
// unusual case for the future.
} else if(pattern instanceof TypePattern.Record) {
TypePattern.Record tp = (TypePattern.Record) pattern;
for(TypePattern element : tp.elements) {
addDeclaredVariables(element,environment,context);
}
} else {
TypePattern.Tuple tp = (TypePattern.Tuple) pattern;
for(TypePattern element : tp.elements) {
addDeclaredVariables(element,environment,context);
}
}
if (pattern.var != null) {
Nominal type = resolveAsType(pattern.toSyntacticType(),
context);
environment = environment.put(pattern.var, type);
}
return environment;
}
// Expressions
public Pair<Expr, Environment> resolve(Expr expr, boolean sign,
Environment environment, Context context) {
if(expr instanceof Expr.UnOp) {
return resolve((Expr.UnOp)expr,sign,environment,context);
} else if(expr instanceof Expr.BinOp) {
return resolve((Expr.BinOp)expr,sign,environment,context);
} else {
// for all others just default back to the base rules for expressions.
expr = resolve(expr,environment,context);
checkIsSubtype(Type.T_BOOL,expr,context);
return new Pair(expr,environment);
}
}
private Pair<Expr, Environment> resolve(Expr.UnOp expr, boolean sign,
Environment environment, Context context) {
Expr.UnOp uop = (Expr.UnOp) expr;
if(uop.op == Expr.UOp.NOT) {
Pair<Expr,Environment> p = resolve(uop.mhs,!sign,environment,context);
uop.mhs = p.first();
checkIsSubtype(Type.T_BOOL,uop.mhs,context);
uop.type = Nominal.T_BOOL;
return new Pair(uop,p.second());
} else {
syntaxError(errorMessage(INVALID_BOOLEAN_EXPRESSION),context,expr);
return null; // deadcode
}
}
private Pair<Expr, Environment> resolve(Expr.BinOp bop, boolean sign,
Environment environment, Context context) {
Expr.BOp op = bop.op;
switch (op) {
case AND:
case OR:
case XOR:
return resolveNonLeafCondition(bop,sign,environment,context);
case EQ:
case NEQ:
case LT:
case LTEQ:
case GT:
case GTEQ:
case ELEMENTOF:
case SUBSET:
case SUBSETEQ:
case IS:
return resolveLeafCondition(bop,sign,environment,context);
default:
syntaxError(errorMessage(INVALID_BOOLEAN_EXPRESSION), context, bop);
return null; // dead code
}
}
private Pair<Expr, Environment> resolveNonLeafCondition(
Expr.BinOp bop,
boolean sign,
Environment environment, Context context) {
Expr.BOp op = bop.op;
Pair<Expr,Environment> p;
boolean followOn = (sign && op == Expr.BOp.AND) || (!sign && op == Expr.BOp.OR);
if(followOn) {
p = resolve(bop.lhs,sign,environment.clone(),context);
bop.lhs = p.first();
p = resolve(bop.rhs,sign,p.second(),context);
bop.rhs = p.first();
environment = p.second();
} else {
// We could do better here
p = resolve(bop.lhs,sign,environment.clone(),context);
bop.lhs = p.first();
Environment local = p.second();
// Recompue the lhs assuming that it is false. This is necessary to
// generate the right environment going into the rhs, which is only
// evaluated if the lhs is false. For example:
// if(e is int && e > 0):
// else:
// In the false branch, we're determing the environment for
// !(e is int && e > 0). This becomes !(e is int) || (e > 0) where
// on the rhs we require (e is int).
p = resolve(bop.lhs,!sign,environment.clone(),context);
p = resolve(bop.rhs,sign,p.second(),context);
bop.rhs = p.first();
environment = join(local,p.second());
}
checkIsSubtype(Type.T_BOOL,bop.lhs,context);
checkIsSubtype(Type.T_BOOL,bop.rhs,context);
bop.srcType = Nominal.T_BOOL;
return new Pair<Expr,Environment>(bop,environment);
}
private Pair<Expr, Environment> resolveLeafCondition(Expr.BinOp bop,
boolean sign, Environment environment, Context context) {
Expr.BOp op = bop.op;
Expr lhs = resolve(bop.lhs,environment,context);
Expr rhs = resolve(bop.rhs,environment,context);
bop.lhs = lhs;
bop.rhs = rhs;
Type lhsRawType = lhs.result().raw();
Type rhsRawType = rhs.result().raw();
switch(op) {
case IS:
// this one is slightly more difficult. In the special case that
// we have a type constant on the right-hand side then we want
// to check that it makes sense. Otherwise, we just check that
// it has type meta.
if(rhs instanceof Expr.TypeVal) {
// yes, right-hand side is a constant
Expr.TypeVal tv = (Expr.TypeVal) rhs;
Nominal unconstrainedTestType = resolveAsUnconstrainedType(tv.unresolvedType,context);
/**
* Determine the types guaranteed to hold on the true and false
* branches respectively. We have to use the negated
* unconstrainedTestType for the false branch because only that
* is guaranteed if the test fails. For example:
*
* <pre>
* define nat as int where $ >= 0
* define listnat as [int]|nat
*
* int f([int]|int x):
* if x if listnat:
* x : [int]|int
* ...
* else:
* x : int
* </pre>
*
* The unconstrained type of listnat is [int], since nat is a
* constrained type.
*/
Nominal glbForFalseBranch = Nominal.intersect(lhs.result(),
Nominal.Negation(unconstrainedTestType));
Nominal glbForTrueBranch = Nominal.intersect(lhs.result(),
tv.type);
if(glbForFalseBranch.raw() == Type.T_VOID) {
// DEFINITE TRUE CASE
syntaxError(errorMessage(BRANCH_ALWAYS_TAKEN), context, bop);
} else if (glbForTrueBranch.raw() == Type.T_VOID) {
// DEFINITE FALSE CASE
syntaxError(errorMessage(INCOMPARABLE_OPERANDS, lhsRawType, tv.type.raw()),
context, bop);
}
// Finally, if the lhs is local variable then update its
// type in the resulting environment.
if(lhs instanceof Expr.LocalVariable) {
Expr.LocalVariable lv = (Expr.LocalVariable) lhs;
Nominal newType;
if(sign) {
newType = glbForTrueBranch;
} else {
newType = glbForFalseBranch;
}
environment = environment.put(lv.var,newType);
}
} else {
// In this case, we can't update the type of the lhs since
// we don't know anything about the rhs. It may be possible
// to support bounds here in order to do that, but frankly
// that's future work :)
checkIsSubtype(Type.T_META,rhs,context);
}
bop.srcType = lhs.result();
break;
case ELEMENTOF:
Type.EffectiveList listType = rhsRawType instanceof Type.EffectiveList ? (Type.EffectiveList) rhsRawType : null;
Type.EffectiveSet setType = rhsRawType instanceof Type.EffectiveSet ? (Type.EffectiveSet) rhsRawType : null;
if (listType != null && !Type.isImplicitCoerciveSubtype(listType.element(), lhsRawType)) {
syntaxError(errorMessage(INCOMPARABLE_OPERANDS, lhsRawType,listType.element()),
context, bop);
} else if (setType != null && !Type.isImplicitCoerciveSubtype(setType.element(), lhsRawType)) {
syntaxError(errorMessage(INCOMPARABLE_OPERANDS, lhsRawType,setType.element()),
context, bop);
}
bop.srcType = rhs.result();
break;
case SUBSET:
case SUBSETEQ:
case LT:
case LTEQ:
case GTEQ:
case GT:
if(op == Expr.BOp.SUBSET || op == Expr.BOp.SUBSETEQ) {
checkIsSubtype(Type.T_SET_ANY,lhs,context);
checkIsSubtype(Type.T_SET_ANY,rhs,context);
} else {
checkIsSubtype(Type.T_REAL,lhs,context);
checkIsSubtype(Type.T_REAL,rhs,context);
}
if(Type.isImplicitCoerciveSubtype(lhsRawType,rhsRawType)) {
bop.srcType = lhs.result();
} else if(Type.isImplicitCoerciveSubtype(rhsRawType,lhsRawType)) {
bop.srcType = rhs.result();
} else {
syntaxError(errorMessage(INCOMPARABLE_OPERANDS,lhsRawType,rhsRawType),context,bop);
return null; // dead code
}
break;
case NEQ:
// following is a sneaky trick for the special case below
sign = !sign;
case EQ:
// first, check for special case of e.g. x != null. This is then
// treated the same as !(x is null)
if (lhs instanceof Expr.LocalVariable
&& rhs instanceof Expr.Constant
&& ((Expr.Constant) rhs).value == Constant.V_NULL) {
// bingo, special case
Expr.LocalVariable lv = (Expr.LocalVariable) lhs;
Nominal newType;
Nominal glb = Nominal.intersect(lhs.result(), Nominal.T_NULL);
if(glb.raw() == Type.T_VOID) {
syntaxError(errorMessage(INCOMPARABLE_OPERANDS,lhs.result().raw(),Type.T_NULL),context,bop);
return null;
} else if(sign) {
newType = glb;
} else {
newType = Nominal.intersect(lhs.result(), Nominal.T_NOTNULL);
}
bop.srcType = lhs.result();
environment = environment.put(lv.var,newType);
} else {
// handle general case
if(Type.isImplicitCoerciveSubtype(lhsRawType,rhsRawType)) {
bop.srcType = lhs.result();
} else if(Type.isImplicitCoerciveSubtype(rhsRawType,lhsRawType)) {
bop.srcType = rhs.result();
} else {
syntaxError(errorMessage(INCOMPARABLE_OPERANDS,lhsRawType,rhsRawType),context,bop);
return null; // dead code
}
}
}
return new Pair(bop,environment);
}
public Expr resolve(Expr expr, Environment environment, Context context) {
try {
if(expr instanceof Expr.BinOp) {
return resolve((Expr.BinOp) expr,environment,context);
} else if(expr instanceof Expr.UnOp) {
return resolve((Expr.UnOp) expr,environment,context);
} else if(expr instanceof Expr.Comprehension) {
return resolve((Expr.Comprehension) expr,environment,context);
} else if(expr instanceof Expr.Constant) {
return resolve((Expr.Constant) expr,environment,context);
} else if(expr instanceof Expr.Cast) {
return resolve((Expr.Cast) expr,environment,context);
} else if(expr instanceof Expr.Map) {
return resolve((Expr.Map) expr,environment,context);
} else if(expr instanceof Expr.AbstractFunctionOrMethod) {
return resolve((Expr.AbstractFunctionOrMethod) expr,environment,context);
} else if(expr instanceof Expr.AbstractInvoke) {
return resolve((Expr.AbstractInvoke) expr,environment,context);
} else if(expr instanceof Expr.AbstractIndirectInvoke) {
return resolve((Expr.AbstractIndirectInvoke) expr,environment,context);
} else if(expr instanceof Expr.IndexOf) {
return resolve((Expr.IndexOf) expr,environment,context);
} else if(expr instanceof Expr.Lambda) {
return resolve((Expr.Lambda) expr,environment,context);
} else if(expr instanceof Expr.LengthOf) {
return resolve((Expr.LengthOf) expr,environment,context);
} else if(expr instanceof Expr.AbstractVariable) {
return resolve((Expr.AbstractVariable) expr,environment,context);
} else if(expr instanceof Expr.List) {
return resolve((Expr.List) expr,environment,context);
} else if(expr instanceof Expr.Set) {
return resolve((Expr.Set) expr,environment,context);
} else if(expr instanceof Expr.SubList) {
return resolve((Expr.SubList) expr,environment,context);
} else if(expr instanceof Expr.SubString) {
return resolve((Expr.SubString) expr,environment,context);
} else if(expr instanceof Expr.AbstractDotAccess) {
return resolve((Expr.AbstractDotAccess) expr,environment,context);
} else if(expr instanceof Expr.Dereference) {
return resolve((Expr.Dereference) expr,environment,context);
} else if(expr instanceof Expr.Record) {
return resolve((Expr.Record) expr,environment,context);
} else if(expr instanceof Expr.New) {
return resolve((Expr.New) expr,environment,context);
} else if(expr instanceof Expr.Tuple) {
return resolve((Expr.Tuple) expr,environment,context);
} else if(expr instanceof Expr.TypeVal) {
return resolve((Expr.TypeVal) expr,environment,context);
}
} catch(ResolveError e) {
syntaxError(errorMessage(RESOLUTION_ERROR,e.getMessage()),context,expr,e);
} catch(SyntaxError e) {
throw e;
} catch(Throwable e) {
internalFailure(e.getMessage(),context,expr,e);
return null; // dead code
}
internalFailure("unknown expression: " + expr.getClass().getName(),context,expr);
return null; // dead code
}
private Expr resolve(Expr.BinOp expr,
Environment environment, Context context) throws Exception {
// TODO: split binop into arithmetic and conditional operators. This
// would avoid the following case analysis since conditional binary
// operators and arithmetic binary operators actually behave quite
// differently.
switch(expr.op) {
case AND:
case OR:
case XOR:
case EQ:
case NEQ:
case LT:
case LTEQ:
case GT:
case GTEQ:
case ELEMENTOF:
case SUBSET:
case SUBSETEQ:
case IS:
return resolve(expr,true,environment,context).first();
}
Expr lhs = resolve(expr.lhs,environment,context);
Expr rhs = resolve(expr.rhs,environment,context);
expr.lhs = lhs;
expr.rhs = rhs;
Type lhsRawType = lhs.result().raw();
Type rhsRawType = rhs.result().raw();
boolean lhs_set = Type.isImplicitCoerciveSubtype(Type.T_SET_ANY,lhsRawType);
boolean rhs_set = Type.isImplicitCoerciveSubtype(Type.T_SET_ANY,rhsRawType);
boolean lhs_list = Type.isImplicitCoerciveSubtype(Type.T_LIST_ANY,lhsRawType);
boolean rhs_list = Type.isImplicitCoerciveSubtype(Type.T_LIST_ANY,rhsRawType);
boolean lhs_str = Type.isSubtype(Type.T_STRING,lhsRawType);
boolean rhs_str = Type.isSubtype(Type.T_STRING,rhsRawType);
Type srcType;
if(lhs_str || rhs_str) {
switch(expr.op) {
case LISTAPPEND:
expr.op = Expr.BOp.STRINGAPPEND;
case STRINGAPPEND:
break;
default:
syntaxError("Invalid string operation: " + expr.op, context,
expr);
}
srcType = Type.T_STRING;
} else if(lhs_list && rhs_list) {
checkIsSubtype(Type.T_LIST_ANY,lhs,context);
checkIsSubtype(Type.T_LIST_ANY,rhs,context);
Type.EffectiveList lel = (Type.EffectiveList) lhsRawType;
Type.EffectiveList rel = (Type.EffectiveList) rhsRawType;
switch(expr.op) {
case LISTAPPEND:
srcType = Type.List(Type.Union(lel.element(),rel.element()),false);
break;
default:
syntaxError("invalid list operation: " + expr.op,context,expr);
return null; // dead-code
}
} else if(lhs_set && rhs_set) {
checkIsSubtype(Type.T_SET_ANY,lhs,context);
checkIsSubtype(Type.T_SET_ANY,rhs,context);
// FIXME: something tells me there should be a function for doing
// this. Perhaps effectiveSetType?
if(lhs_list) {
Type.EffectiveList tmp = (Type.EffectiveList) lhsRawType;
lhsRawType = Type.Set(tmp.element(),false);
}
if(rhs_list) {
Type.EffectiveList tmp = (Type.EffectiveList) rhsRawType;
rhsRawType = Type.Set(tmp.element(),false);
}
// FIXME: loss of nominal information here
Type.EffectiveSet ls = (Type.EffectiveSet) lhsRawType;
Type.EffectiveSet rs = (Type.EffectiveSet) rhsRawType;
switch(expr.op) {
case ADD:
expr.op = Expr.BOp.UNION;
case UNION:
// TODO: this forces unnecessary coercions, which would be
// good to remove.
srcType = Type.Set(Type.Union(ls.element(),rs.element()),false);
break;
case BITWISEAND:
expr.op = Expr.BOp.INTERSECTION;
case INTERSECTION:
// FIXME: this is just plain wierd.
if(Type.isSubtype(lhsRawType, rhsRawType)) {
srcType = rhsRawType;
} else {
srcType = lhsRawType;
}
break;
case SUB:
expr.op = Expr.BOp.DIFFERENCE;
case DIFFERENCE:
srcType = lhsRawType;
break;
default:
syntaxError("invalid set operation: " + expr.op,context,expr);
return null; // deadcode
}
} else {
switch(expr.op) {
case IS:
case AND:
case OR:
case XOR:
return resolve(expr,true,environment,context).first();
case BITWISEAND:
case BITWISEOR:
case BITWISEXOR:
checkIsSubtype(Type.T_BYTE,lhs,context);
checkIsSubtype(Type.T_BYTE,rhs,context);
srcType = Type.T_BYTE;
break;
case LEFTSHIFT:
case RIGHTSHIFT:
checkIsSubtype(Type.T_BYTE,lhs,context);
checkIsSubtype(Type.T_INT,rhs,context);
srcType = Type.T_BYTE;
break;
case RANGE:
checkIsSubtype(Type.T_INT,lhs,context);
checkIsSubtype(Type.T_INT,rhs,context);
srcType = Type.List(Type.T_INT, false);
break;
case REM:
checkIsSubtype(Type.T_INT,lhs,context);
checkIsSubtype(Type.T_INT,rhs,context);
srcType = Type.T_INT;
break;
default:
// all other operations go through here
if(Type.isImplicitCoerciveSubtype(lhsRawType,rhsRawType)) {
checkIsSubtype(Type.T_REAL,lhs,context);
if(Type.isSubtype(Type.T_CHAR, lhsRawType)) {
srcType = Type.T_INT;
} else if(Type.isSubtype(Type.T_INT, lhsRawType)) {
srcType = Type.T_INT;
} else {
srcType = Type.T_REAL;
}
} else {
checkIsSubtype(Type.T_REAL,lhs,context);
checkIsSubtype(Type.T_REAL,rhs,context);
if(Type.isSubtype(Type.T_CHAR, rhsRawType)) {
srcType = Type.T_INT;
} else if(Type.isSubtype(Type.T_INT, rhsRawType)) {
srcType = Type.T_INT;
} else {
srcType = Type.T_REAL;
}
}
}
}
// FIXME: loss of nominal information
expr.srcType = Nominal.construct(srcType,srcType);
return expr;
}
private Expr resolve(Expr.UnOp expr,
Environment environment, Context context) throws Exception {
if(expr.op == Expr.UOp.NOT) {
// hand off to special method for conditions
return resolve(expr,true,environment,context).first();
}
Expr src = resolve(expr.mhs, environment,context);
expr.mhs = src;
switch(expr.op) {
case NEG:
checkIsSubtype(Type.T_REAL,src,context);
break;
case INVERT:
checkIsSubtype(Type.T_BYTE,src,context);
break;
default:
internalFailure(
"unknown operator: " + expr.op.getClass().getName(),
context, expr);
}
expr.type = src.result();
return expr;
}
private Expr resolve(Expr.Comprehension expr,
Environment environment, Context context) throws Exception {
ArrayList<Pair<String,Expr>> sources = expr.sources;
Environment local = environment.clone();
for(int i=0;i!=sources.size();++i) {
Pair<String,Expr> p = sources.get(i);
Expr e = resolve(p.second(),local,context);
p = new Pair<String,Expr>(p.first(),e);
sources.set(i,p);
Nominal element;
Nominal type = e.result();
Nominal.EffectiveCollection colType = expandAsEffectiveCollection(type);
if(colType == null) {
syntaxError(errorMessage(INVALID_SET_OR_LIST_EXPRESSION),context,e);
return null; // dead code
}
// update environment for subsequent source expressions, the
// condition and the value.
local = local.put(p.first(),colType.element());
}
if(expr.condition != null) {
expr.condition = resolve(expr.condition,local,context);
}
if (expr.cop == Expr.COp.SETCOMP || expr.cop == Expr.COp.LISTCOMP) {
expr.value = resolve(expr.value,local,context);
expr.type = Nominal.Set(expr.value.result(), false);
} else {
expr.type = Nominal.T_BOOL;
}
local.free();
return expr;
}
private Expr resolve(Expr.Constant expr,
Environment environment, Context context) {
return expr;
}
private Expr resolve(Expr.Cast c,
Environment environment, Context context) throws Exception {
c.expr = resolve(c.expr,environment,context);
c.type = resolveAsType(c.unresolvedType, context);
Type from = c.expr.result().raw();
Type to = c.type.raw();
if (!Type.isExplicitCoerciveSubtype(to, from)) {
syntaxError(errorMessage(SUBTYPE_ERROR, to, from), context, c);
}
return c;
}
private Expr resolve(Expr.AbstractFunctionOrMethod expr,
Environment environment, Context context) throws Exception {
if(expr instanceof Expr.FunctionOrMethod) {
return expr;
}
Pair<NameID, Nominal.FunctionOrMethod> p;
if (expr.paramTypes != null) {
ArrayList<Nominal> paramTypes = new ArrayList<Nominal>();
for (SyntacticType t : expr.paramTypes) {
paramTypes.add(resolveAsType(t, context));
}
// FIXME: clearly a bug here in the case of message reference
p = (Pair) resolveAsFunctionOrMethod(expr.name, paramTypes, context);
} else {
p = resolveAsFunctionOrMethod(expr.name, context);
}
expr = new Expr.FunctionOrMethod(p.first(),expr.paramTypes,expr.attributes());
expr.type = p.second();
return expr;
}
private Expr resolve(Expr.Lambda expr,
Environment environment, Context context) throws Exception {
ArrayList<Type> rawTypes = new ArrayList<Type>();
ArrayList<Type> nomTypes = new ArrayList<Type>();
for(WhileyFile.Parameter p : expr.parameters) {
Nominal n = resolveAsType(p.type,context);
rawTypes.add(n.raw());
nomTypes.add(n.nominal());
// Now, update the environment to include those declared variables
String var = p.name();
if (environment.containsKey(var)) {
syntaxError(errorMessage(VARIABLE_ALREADY_DEFINED,var),
context, p);
}
environment = environment.put(var, n);
}
expr.body = resolve(expr.body,environment,context);
Type.FunctionOrMethod rawType;
Type.FunctionOrMethod nomType;
if(Exprs.isPure(expr.body, context)) {
rawType = Type.Function(expr.body.result().raw(),
Type.T_VOID, rawTypes);
nomType = Type.Function(expr.body.result().nominal(),
Type.T_VOID, nomTypes);
} else {
rawType = Type.Method(expr.body.result().raw(),
Type.T_VOID, rawTypes);
nomType = Type.Method(expr.body.result().nominal(),
Type.T_VOID, nomTypes);
}
expr.type = (Nominal.FunctionOrMethod) Nominal.construct(nomType,rawType);
return expr;
}
private Expr resolve(Expr.AbstractIndirectInvoke expr,
Environment environment, Context context) throws Exception {
expr.src = resolve(expr.src, environment, context);
Nominal type = expr.src.result();
if (!(type instanceof Nominal.FunctionOrMethod)) {
syntaxError("function or method type expected", context, expr.src);
}
Nominal.FunctionOrMethod funType = (Nominal.FunctionOrMethod) type;
List<Nominal> paramTypes = funType.params();
ArrayList<Expr> exprArgs = expr.arguments;
for (int i = 0; i != exprArgs.size(); ++i) {
Nominal pt = paramTypes.get(i);
Expr arg = resolve(exprArgs.get(i), environment, context);
checkIsSubtype(pt, arg, context);
exprArgs.set(i, arg);
}
if (funType instanceof Nominal.Function) {
Expr.IndirectFunctionCall ifc = new Expr.IndirectFunctionCall(expr.src, exprArgs,
expr.attributes());
ifc.functionType = (Nominal.Function) funType;
return ifc;
} else {
Expr.IndirectMethodCall imc = new Expr.IndirectMethodCall(expr.src, exprArgs,
expr.attributes());
imc.methodType = (Nominal.Method) funType;
return imc;
}
}
private Expr resolve(Expr.AbstractInvoke expr,
Environment environment, Context context) throws Exception {
// first, resolve through receiver and parameters.
Expr receiver = expr.qualification;
if(receiver != null) {
receiver = resolve(receiver,environment,context);
expr.qualification = receiver;
}
ArrayList<Expr> exprArgs = expr.arguments;
ArrayList<Nominal> paramTypes = new ArrayList<Nominal>();
for(int i=0;i!=exprArgs.size();++i) {
Expr arg = resolve(exprArgs.get(i),environment,context);
exprArgs.set(i, arg);
paramTypes.add(arg.result());
}
// second, determine whether we already have a fully qualified name and
// then lookup the appropriate function.
if(receiver instanceof Expr.ModuleAccess) {
// Yes, this function or method is qualified
Expr.ModuleAccess ma = (Expr.ModuleAccess) receiver;
NameID name = new NameID(ma.mid,expr.name);
Nominal.FunctionOrMethod funType = resolveAsFunctionOrMethod(name, paramTypes, context);
if(funType instanceof Nominal.Function) {
Expr.FunctionCall r = new Expr.FunctionCall(name, ma, exprArgs, expr.attributes());
r.functionType = (Nominal.Function) funType;
return r;
} else {
Expr.MethodCall r = new Expr.MethodCall(name, ma, exprArgs, expr.attributes());
r.methodType = (Nominal.Method) funType;
return r;
}
} else if(receiver != null) {
// function is qualified, so this is used as the scope for resolving
// what the function is.
Nominal.EffectiveRecord recType = expandAsEffectiveRecord(expr.qualification.result());
if(recType != null) {
Nominal fieldType = recType.field(expr.name);
if(fieldType == null) {
syntaxError(errorMessage(RECORD_MISSING_FIELD,expr.name),context,expr);
} else if(!(fieldType instanceof Nominal.FunctionOrMethod)) {
syntaxError("function or method type expected",context,expr);
}
Nominal.FunctionOrMethod funType = (Nominal.FunctionOrMethod) fieldType;
Expr.FieldAccess ra = new Expr.FieldAccess(receiver, expr.name, expr.attributes());
ra.srcType = recType;
if(funType instanceof Nominal.Method) {
Expr.IndirectMethodCall nexpr = new Expr.IndirectMethodCall(ra,expr.arguments,expr.attributes());
// FIXME: loss of nominal information
nexpr.methodType = (Nominal.Method) funType;
return nexpr;
} else {
Expr.IndirectFunctionCall nexpr = new Expr.IndirectFunctionCall(ra,expr.arguments,expr.attributes());
// FIXME: loss of nominal information
nexpr.functionType = (Nominal.Function) funType;
return nexpr;
}
} else {
// In this case, we definitely have an object type.
checkIsSubtype(Type.T_REF_ANY,expr.qualification,context);
Type.Reference procType = (Type.Reference) expr.qualification.result().raw();
exprArgs.add(0,receiver);
paramTypes.add(0,receiver.result());
Pair<NameID, Nominal.FunctionOrMethod> p = resolveAsFunctionOrMethod(
expr.name, paramTypes, context);
// TODO: problem if not Nominal.Method!
Expr.MethodCall r = new Expr.MethodCall(p.first(), null,
exprArgs, expr.attributes());
r.methodType = (Nominal.Method) p.second();
return r;
}
} else {
// no, function is not qualified ... so, it's either a local
// variable or a function call the location of which we need to
// identify.
Nominal type = environment.get(expr.name);
Nominal.FunctionOrMethod funType = type != null ? expandAsFunctionOrMethod(type) : null;
// FIXME: bad idea to use instanceof Nominal.FunctionOrMethod here
if(funType != null) {
// ok, matching local variable of function type.
List<Nominal> funTypeParams = funType.params();
if(paramTypes.size() != funTypeParams.size()) {
syntaxError("insufficient arguments to function call",context,expr);
}
for (int i = 0; i != funTypeParams.size(); ++i) {
Nominal fpt = funTypeParams.get(i);
checkIsSubtype(fpt, paramTypes.get(i), exprArgs.get(i),context);
}
Expr.LocalVariable lv = new Expr.LocalVariable(expr.name,expr.attributes());
lv.type = type;
if(funType instanceof Nominal.Method) {
Expr.IndirectMethodCall nexpr = new Expr.IndirectMethodCall(lv,expr.arguments,expr.attributes());
nexpr.methodType = (Nominal.Method) funType;
return nexpr;
} else {
Expr.IndirectFunctionCall nexpr = new Expr.IndirectFunctionCall(lv,expr.arguments,expr.attributes());
nexpr.functionType = (Nominal.Function) funType;
return nexpr;
}
} else {
// no matching local variable, so attempt to resolve as direct
// call.
Pair<NameID, Nominal.FunctionOrMethod> p = resolveAsFunctionOrMethod(expr.name, paramTypes, context);
funType = p.second();
if(funType instanceof Nominal.Function) {
Expr.FunctionCall mc = new Expr.FunctionCall(p.first(), null, exprArgs, expr.attributes());
mc.functionType = (Nominal.Function) funType;
return mc;
} else {
Expr.MethodCall mc = new Expr.MethodCall(p.first(), null, exprArgs, expr.attributes());
mc.methodType = (Nominal.Method) funType;
return mc;
}
}
}
}
private Expr resolve(Expr.IndexOf expr,
Environment environment, Context context) throws Exception {
expr.src = resolve(expr.src,environment,context);
expr.index = resolve(expr.index,environment,context);
Nominal.EffectiveIndexible srcType = expandAsEffectiveMap(expr.src.result());
if(srcType == null) {
syntaxError(errorMessage(INVALID_SET_OR_LIST_EXPRESSION), context, expr.src);
} else {
expr.srcType = srcType;
}
checkIsSubtype(srcType.key(),expr.index,context);
return expr;
}
private Expr resolve(Expr.LengthOf expr, Environment environment,
Context context) throws Exception {
expr.src = resolve(expr.src,environment, context);
Nominal srcType = expr.src.result();
Type rawSrcType = srcType.raw();
// First, check whether this is still only an abstract access and, in
// such case, upgrade it to the appropriate access expression.
if (rawSrcType instanceof Type.EffectiveCollection) {
expr.srcType = expandAsEffectiveCollection(srcType);
return expr;
} else {
syntaxError("found " + expr.src.result().nominal()
+ ", expected string, set, list or dictionary.", context,
expr.src);
}
// Second, determine the expanded src type for this access expression
// and check the key value.
checkIsSubtype(Type.T_STRING,expr.src,context);
return expr;
}
private Expr resolve(Expr.AbstractVariable expr,
Environment environment, Context context) throws Exception {
Nominal type = environment.get(expr.var);
if (expr instanceof Expr.LocalVariable) {
Expr.LocalVariable lv = (Expr.LocalVariable) expr;
lv.type = type;
return lv;
} else if (type != null) {
// yes, this is a local variable
Expr.LocalVariable lv = new Expr.LocalVariable(expr.var,
expr.attributes());
lv.type = type;
return lv;
} else {
// This variable access may correspond to an external access.
// Therefore, we must determine which module this
// is, and update the tree accordingly.
try {
NameID nid = resolveAsName(expr.var, context);
Expr.ConstantAccess ca = new Expr.ConstantAccess(null, expr.var, nid,
expr.attributes());
ca.value = resolveAsConstant(nid);
return ca;
} catch (ResolveError err) {
}
// In this case, we may still be OK if this corresponds to an
// explicit module or package access.
try {
Path.ID mid = resolveAsModule(expr.var, context);
return new Expr.ModuleAccess(null, expr.var, mid,
expr.attributes());
} catch (ResolveError err) {
}
Path.ID pid = Trie.ROOT.append(expr.var);
if (builder.exists(pid)) {
return new Expr.PackageAccess(null, expr.var, pid,
expr.attributes());
}
// ok, failed.
syntaxError(errorMessage(UNKNOWN_VARIABLE), context, expr);
return null; // deadcode
}
}
private Expr resolve(Expr.Set expr,
Environment environment, Context context) {
Nominal element = Nominal.T_VOID;
ArrayList<Expr> exprs = expr.arguments;
for(int i=0;i!=exprs.size();++i) {
Expr e = resolve(exprs.get(i),environment,context);
Nominal t = e.result();
exprs.set(i,e);
element = Nominal.Union(t,element);
}
expr.type = Nominal.Set(element,false);
return expr;
}
private Expr resolve(Expr.List expr,
Environment environment, Context context) {
Nominal element = Nominal.T_VOID;
ArrayList<Expr> exprs = expr.arguments;
for(int i=0;i!=exprs.size();++i) {
Expr e = resolve(exprs.get(i),environment,context);
Nominal t = e.result();
exprs.set(i,e);
element = Nominal.Union(t,element);
}
expr.type = Nominal.List(element,false);
return expr;
}
private Expr resolve(Expr.Map expr,
Environment environment, Context context) {
Nominal keyType = Nominal.T_VOID;
Nominal valueType = Nominal.T_VOID;
ArrayList<Pair<Expr,Expr>> exprs = expr.pairs;
for(int i=0;i!=exprs.size();++i) {
Pair<Expr,Expr> p = exprs.get(i);
Expr key = resolve(p.first(),environment,context);
Expr value = resolve(p.second(),environment,context);
Nominal kt = key.result();
Nominal vt = value.result();
exprs.set(i,new Pair<Expr,Expr>(key,value));
keyType = Nominal.Union(kt,keyType);
valueType = Nominal.Union(vt,valueType);
}
expr.type = Nominal.Map(keyType,valueType);
return expr;
}
private Expr resolve(Expr.Record expr,
Environment environment, Context context) {
HashMap<String,Expr> exprFields = expr.fields;
HashMap<String,Nominal> fieldTypes = new HashMap<String,Nominal>();
ArrayList<String> fields = new ArrayList<String>(exprFields.keySet());
for(String field : fields) {
Expr e = resolve(exprFields.get(field),environment,context);
Nominal t = e.result();
exprFields.put(field,e);
fieldTypes.put(field,t);
}
expr.type = Nominal.Record(false,fieldTypes);
return expr;
}
private Expr resolve(Expr.Tuple expr,
Environment environment, Context context) {
ArrayList<Expr> exprFields = expr.fields;
ArrayList<Nominal> fieldTypes = new ArrayList<Nominal>();
for(int i=0;i!=exprFields.size();++i) {
Expr e = resolve(exprFields.get(i),environment,context);
Nominal t = e.result();
exprFields.set(i,e);
fieldTypes.add(t);
}
expr.type = Nominal.Tuple(fieldTypes);
return expr;
}
private Expr resolve(Expr.SubList expr,
Environment environment, Context context) throws Exception {
expr.src = resolve(expr.src,environment,context);
expr.start = resolve(expr.start,environment,context);
expr.end = resolve(expr.end,environment,context);
checkIsSubtype(Type.T_LIST_ANY,expr.src,context);
checkIsSubtype(Type.T_INT,expr.start,context);
checkIsSubtype(Type.T_INT,expr.end,context);
expr.type = expandAsEffectiveList(expr.src.result());
if(expr.type == null) {
// must be a substring
return new Expr.SubString(expr.src,expr.start,expr.end,expr.attributes());
}
return expr;
}
private Expr resolve(Expr.SubString expr,
Environment environment, Context context) throws Exception {
expr.src = resolve(expr.src,environment,context);
expr.start = resolve(expr.start,environment,context);
expr.end = resolve(expr.end,environment,context);
checkIsSubtype(Type.T_STRING,expr.src,context);
checkIsSubtype(Type.T_INT,expr.start,context);
checkIsSubtype(Type.T_INT,expr.end,context);
return expr;
}
private Expr resolve(Expr.AbstractDotAccess expr,
Environment environment, Context context) throws Exception {
if (expr instanceof Expr.PackageAccess
|| expr instanceof Expr.ModuleAccess) {
// don't need to do anything in these cases.
return expr;
}
Expr src = expr.src;
if(src != null) {
src = resolve(expr.src,environment,context);
expr.src = src;
}
if(expr instanceof Expr.FieldAccess) {
return resolve((Expr.FieldAccess)expr,environment,context);
} else if(expr instanceof Expr.ConstantAccess) {
return resolve((Expr.ConstantAccess)expr,environment,context);
} else if(src instanceof Expr.PackageAccess) {
// either a package access, module access or constant access
// This variable access may correspond to an external access.
Expr.PackageAccess pa = (Expr.PackageAccess) src;
Path.ID pid = pa.pid.append(expr.name);
if (builder.exists(pid)) {
return new Expr.PackageAccess(pa, expr.name, pid,
expr.attributes());
}
Path.ID mid = pa.pid.append(expr.name);
if (builder.exists(mid)) {
return new Expr.ModuleAccess(pa, expr.name, mid,
expr.attributes());
} else {
syntaxError(errorMessage(INVALID_PACKAGE_ACCESS), context, expr);
return null; // deadcode
}
} else if(src instanceof Expr.ModuleAccess) {
// must be a constant access
Expr.ModuleAccess ma = (Expr.ModuleAccess) src;
NameID nid = new NameID(ma.mid,expr.name);
if (builder.isName(nid)) {
Expr.ConstantAccess ca = new Expr.ConstantAccess(ma,
expr.name, nid, expr.attributes());
ca.value = resolveAsConstant(nid);
return ca;
}
syntaxError(errorMessage(INVALID_MODULE_ACCESS),context,expr);
return null; // deadcode
} else {
// must be a RecordAccess
Expr.FieldAccess ra = new Expr.FieldAccess(src,expr.name,expr.attributes());
return resolve(ra,environment,context);
}
}
private Expr resolve(Expr.FieldAccess ra,
Environment environment, Context context) throws Exception {
ra.src = resolve(ra.src,environment,context);
Nominal srcType = ra.src.result();
Nominal.EffectiveRecord recType = expandAsEffectiveRecord(srcType);
if(recType == null) {
syntaxError(errorMessage(RECORD_TYPE_REQUIRED,srcType.raw()),context,ra);
}
Nominal fieldType = recType.field(ra.name);
if(fieldType == null) {
syntaxError(errorMessage(RECORD_MISSING_FIELD,ra.name),context,ra);
}
ra.srcType = recType;
return ra;
}
private Expr resolve(Expr.ConstantAccess expr,
Environment environment, Context context) throws Exception {
// we don't need to do anything here, since the value is already
// resolved by case for AbstractDotAccess.
return expr;
}
private Expr resolve(Expr.Dereference expr,
Environment environment, Context context) throws Exception {
Expr src = resolve(expr.src,environment,context);
expr.src = src;
Nominal.Reference srcType = expandAsReference(src.result());
if(srcType == null) {
syntaxError("invalid reference expression",context,src);
}
expr.srcType = srcType;
return expr;
}
private Expr resolve(Expr.New expr,
Environment environment, Context context) {
expr.expr = resolve(expr.expr,environment,context);
expr.type = Nominal.Reference(expr.expr.result());
return expr;
}
private Expr resolve(Expr.TypeVal expr,
Environment environment, Context context) throws Exception {
expr.type = resolveAsType(expr.unresolvedType, context);
return expr;
}
/**
* Responsible for determining the true type of a method or function being
* invoked. To do this, it must find the function/method with the most
* precise type that matches the argument types.
*
* @param nid
* @param parameters
* @return
* @throws Exception
*/
private Nominal.FunctionOrMethod resolveAsFunctionOrMethod(NameID nid,
List<Nominal> parameters, Context context) throws Exception {
HashSet<Pair<NameID, Nominal.FunctionOrMethod>> candidates = new HashSet<Pair<NameID, Nominal.FunctionOrMethod>>();
addCandidateFunctionsAndMethods(nid, parameters, candidates, context);
return selectCandidateFunctionOrMethod(nid.name(), parameters,
candidates,context).second();
}
public Pair<NameID,Nominal.FunctionOrMethod> resolveAsFunctionOrMethod(String name,
Context context) throws Exception {
return resolveAsFunctionOrMethod(name,null,context);
}
public Pair<NameID,Nominal.FunctionOrMethod> resolveAsFunctionOrMethod(String name,
List<Nominal> parameters, Context context) throws Exception {
HashSet<Pair<NameID,Nominal.FunctionOrMethod>> candidates = new HashSet<Pair<NameID, Nominal.FunctionOrMethod>>();
// first, try to find the matching message
for (WhileyFile.Import imp : context.imports()) {
String impName = imp.name;
if (impName == null || impName.equals(name) || impName.equals("*")) {
Trie filter = imp.filter;
if(impName == null) {
// import name is null, but it's possible that a module of
// the given name exists, in which case any matching names
// are automatically imported.
filter = filter.parent().append(name);
}
for (Path.ID mid : builder.imports(filter)) {
NameID nid = new NameID(mid,name);
addCandidateFunctionsAndMethods(nid,parameters,candidates,context);
}
}
}
return selectCandidateFunctionOrMethod(name,parameters,candidates,context);
}
private boolean paramSubtypes(Type.FunctionOrMethod f1, Type.FunctionOrMethod f2) {
List<Type> f1_params = f1.params();
List<Type> f2_params = f2.params();
if(f1_params.size() == f2_params.size()) {
for(int i=0;i!=f1_params.size();++i) {
Type f1_param = f1_params.get(i);
Type f2_param = f2_params.get(i);
if(!Type.isImplicitCoerciveSubtype(f1_param,f2_param)) {
return false;
}
}
return true;
}
return false;
}
private boolean paramStrictSubtypes(Type.FunctionOrMethod f1, Type.FunctionOrMethod f2) {
List<Type> f1_params = f1.params();
List<Type> f2_params = f2.params();
if(f1_params.size() == f2_params.size()) {
boolean allEqual = true;
for(int i=0;i!=f1_params.size();++i) {
Type f1_param = f1_params.get(i);
Type f2_param = f2_params.get(i);
if(!Type.isImplicitCoerciveSubtype(f1_param,f2_param)) {
return false;
}
allEqual &= f1_param.equals(f2_param);
}
// This function returns true if the parameters are a strict
// subtype. Therefore, if they are all equal it must return false.
return !allEqual;
}
return false;
}
private String parameterString(List<Nominal> paramTypes) {
String paramStr = "(";
boolean firstTime = true;
if(paramTypes == null) {
paramStr += "...";
} else {
for(Nominal t : paramTypes) {
if(!firstTime) {
paramStr += ",";
}
firstTime=false;
paramStr += t.nominal();
}
}
return paramStr + ")";
}
private Pair<NameID, Nominal.FunctionOrMethod> selectCandidateFunctionOrMethod(
String name, List<Nominal> parameters,
Collection<Pair<NameID, Nominal.FunctionOrMethod>> candidates,
Context context) throws Exception {
List<Type> rawParameters;
Type.Function target;
if (parameters != null) {
rawParameters = stripNominal(parameters);
target = (Type.Function) Type.Function(Type.T_ANY, Type.T_ANY,
rawParameters);
} else {
rawParameters = null;
target = null;
}
NameID candidateID = null;
Nominal.FunctionOrMethod candidateType = null;
for (Pair<NameID,Nominal.FunctionOrMethod> p : candidates) {
Nominal.FunctionOrMethod nft = p.second();
Type.FunctionOrMethod ft = nft.raw();
if (parameters == null || paramSubtypes(ft, target)) {
// this is now a genuine candidate
if(candidateType == null || paramStrictSubtypes(candidateType.raw(), ft)) {
candidateType = nft;
candidateID = p.first();
} else if(!paramStrictSubtypes(ft, candidateType.raw())){
// this is an ambiguous error
String msg = name + parameterString(parameters) + " is ambiguous";
// FIXME: should report all ambiguous matches here
msg += "\n\tfound: " + candidateID + " : " + candidateType.nominal();
msg += "\n\tfound: " + p.first() + " : " + p.second().nominal();
throw new ResolveError(msg);
}
}
}
if(candidateType == null) {
// second, didn't find matching message so generate error message
String msg = "no match for " + name + parameterString(parameters);
for (Pair<NameID, Nominal.FunctionOrMethod> p : candidates) {
msg += "\n\tfound: " + p.first() + " : " + p.second().nominal();
}
throw new ResolveError(msg);
} else {
// now check protection modified
WhileyFile wf = builder.getSourceFile(candidateID.module());
if(wf != null) {
if(wf != context.file()) {
for (WhileyFile.FunctionOrMethod d : wf.declarations(
WhileyFile.FunctionOrMethod.class, candidateID.name())) {
if(d.parameters.equals(candidateType.params())) {
if(!d.isPublic() && !d.isProtected()) {
String msg = candidateID.module() + "." + name + parameterString(parameters) + " is not visible";
throw new ResolveError(msg);
}
}
}
}
} else {
WyilFile m = builder.getModule(candidateID.module());
WyilFile.MethodDeclaration d = m.method(candidateID.name(),candidateType.raw());
if(!d.isPublic() && !d.isProtected()) {
String msg = candidateID.module() + "." + name + parameterString(parameters) + " is not visible";
throw new ResolveError(msg);
}
}
}
return new Pair<NameID,Nominal.FunctionOrMethod>(candidateID,candidateType);
}
private void addCandidateFunctionsAndMethods(NameID nid,
List<?> parameters,
Collection<Pair<NameID, Nominal.FunctionOrMethod>> candidates, Context context)
throws Exception {
Path.ID mid = nid.module();
int nparams = parameters != null ? parameters.size() : -1;
WhileyFile wf = builder.getSourceFile(mid);
if (wf != null) {
for (WhileyFile.FunctionOrMethod f : wf.declarations(
WhileyFile.FunctionOrMethod.class, nid.name())) {
if (nparams == -1 || f.parameters.size() == nparams) {
Nominal.FunctionOrMethod ft = (Nominal.FunctionOrMethod) resolveAsType(
f.unresolvedType(), f);
candidates.add(new Pair<NameID, Nominal.FunctionOrMethod>(
nid, ft));
}
}
} else {
try {
WyilFile m = builder.getModule(mid);
for (WyilFile.MethodDeclaration mm : m.methods()) {
if ((mm.isFunction() || mm.isMethod())
&& mm.name().equals(nid.name())
&& (nparams == -1 || mm.type().params().size() == nparams)) {
// FIXME: loss of nominal information
Type.FunctionOrMethod t = (Type.FunctionOrMethod) mm
.type();
Nominal.FunctionOrMethod fom;
if (t instanceof Type.Function) {
Type.Function ft = (Type.Function) t;
fom = new Nominal.Function(ft, ft);
} else {
Type.Method mt = (Type.Method) t;
fom = new Nominal.Method(mt, mt);
}
candidates
.add(new Pair<NameID, Nominal.FunctionOrMethod>(
nid, fom));
}
}
} catch (ResolveError e) {
}
}
}
private static List<Type> stripNominal(List<Nominal> types) {
ArrayList<Type> r = new ArrayList<Type>();
for (Nominal t : types) {
r.add(t.raw());
}
return r;
}
// ResolveAsName
public NameID resolveAsName(String name, Context context)
throws Exception {
for (WhileyFile.Import imp : context.imports()) {
String impName = imp.name;
if (impName == null || impName.equals(name) || impName.equals("*")) {
Trie filter = imp.filter;
if (impName == null) {
// import name is null, but it's possible that a module of
// the given name exists, in which case any matching names
// are automatically imported.
filter = filter.parent().append(name);
}
for (Path.ID mid : builder.imports(filter)) {
NameID nid = new NameID(mid, name);
if (builder.isName(nid)) {
// ok, we have found the name in question. But, is it
// visible?
if(isVisible(nid,context)) {
return nid;
} else {
throw new ResolveError(nid + " is not visible");
}
}
}
}
}
throw new ResolveError("name not found: " + name);
}
public NameID resolveAsName(List<String> names, Context context) throws Exception {
if(names.size() == 1) {
return resolveAsName(names.get(0),context);
} else if(names.size() == 2) {
String name = names.get(1);
Path.ID mid = resolveAsModule(names.get(0),context);
NameID nid = new NameID(mid, name);
if (builder.isName(nid)) {
if(isVisible(nid,context)) {
return nid;
} else {
throw new ResolveError(nid + " is not visible");
}
}
} else {
String name = names.get(names.size()-1);
String module = names.get(names.size()-2);
Path.ID pkg = Trie.ROOT;
for(int i=0;i!=names.size()-2;++i) {
pkg = pkg.append(names.get(i));
}
Path.ID mid = pkg.append(module);
NameID nid = new NameID(mid, name);
if (builder.isName(nid)) {
if(isVisible(nid,context)) {
return nid;
} else {
throw new ResolveError(nid + " is not visible");
}
}
}
String name = null;
for(String n : names) {
if(name != null) {
name = name + "." + n;
} else {
name = n;
}
}
throw new ResolveError("name not found: " + name);
}
public Path.ID resolveAsModule(String name, Context context)
throws Exception {
for (WhileyFile.Import imp : context.imports()) {
Trie filter = imp.filter;
String last = filter.last();
if (last.equals("*")) {
// this is generic import, so narrow the filter.
filter = filter.parent().append(name);
} else if(!last.equals(name)) {
continue; // skip as not relevant
}
for(Path.ID mid : builder.imports(filter)) {
return mid;
}
}
throw new ResolveError("module not found: " + name);
}
// ResolveAsType
public Nominal.Function resolveAsType(SyntacticType.Function t,
Context context) {
return (Nominal.Function) resolveAsType((SyntacticType)t,context);
}
public Nominal.Method resolveAsType(SyntacticType.Method t,
Context context) {
return (Nominal.Method) resolveAsType((SyntacticType)t,context);
}
public Nominal resolveAsType(SyntacticType type, Context context) {
Type nominalType = resolveAsType(type, context, true, false);
Type rawType = resolveAsType(type, context, false, false);
return Nominal.construct(nominalType, rawType);
}
public Nominal resolveAsUnconstrainedType(SyntacticType type, Context context) {
Type nominalType = resolveAsType(type, context, true, true);
Type rawType = resolveAsType(type, context, false, true);
return Nominal.construct(nominalType, rawType);
}
private Type resolveAsType(SyntacticType t, Context context,
boolean nominal, boolean unconstrained) {
if(t instanceof SyntacticType.Primitive) {
if (t instanceof SyntacticType.Any) {
return Type.T_ANY;
} else if (t instanceof SyntacticType.Void) {
return Type.T_VOID;
} else if (t instanceof SyntacticType.Null) {
return Type.T_NULL;
} else if (t instanceof SyntacticType.Bool) {
return Type.T_BOOL;
} else if (t instanceof SyntacticType.Byte) {
return Type.T_BYTE;
} else if (t instanceof SyntacticType.Char) {
return Type.T_CHAR;
} else if (t instanceof SyntacticType.Int) {
return Type.T_INT;
} else if (t instanceof SyntacticType.Real) {
return Type.T_REAL;
} else if (t instanceof SyntacticType.Strung) {
return Type.T_STRING;
} else {
internalFailure("unrecognised type encountered ("
+ t.getClass().getName() + ")",context,t);
return null; // deadcode
}
} else {
ArrayList<Automaton.State> states = new ArrayList<Automaton.State>();
HashMap<NameID,Integer> roots = new HashMap<NameID,Integer>();
resolveAsType(t,context,states,roots,nominal,unconstrained);
return Type.construct(new Automaton(states));
}
}
private int resolveAsType(SyntacticType type, Context context,
ArrayList<Automaton.State> states, HashMap<NameID, Integer> roots,
boolean nominal, boolean unconstrained) {
if(type instanceof SyntacticType.Primitive) {
return resolveAsType((SyntacticType.Primitive)type,context,states);
}
int myIndex = states.size();
int myKind;
int[] myChildren;
Object myData = null;
boolean myDeterministic = true;
states.add(null); // reserve space for me
if(type instanceof SyntacticType.List) {
SyntacticType.List lt = (SyntacticType.List) type;
myKind = Type.K_LIST;
myChildren = new int[1];
myChildren[0] = resolveAsType(lt.element,context,states,roots,nominal,unconstrained);
myData = false;
} else if(type instanceof SyntacticType.Set) {
SyntacticType.Set st = (SyntacticType.Set) type;
myKind = Type.K_SET;
myChildren = new int[1];
myChildren[0] = resolveAsType(st.element,context,states,roots,nominal,unconstrained);
myData = false;
} else if(type instanceof SyntacticType.Map) {
SyntacticType.Map st = (SyntacticType.Map) type;
myKind = Type.K_MAP;
myChildren = new int[2];
myChildren[0] = resolveAsType(st.key,context,states,roots,nominal,unconstrained);
myChildren[1] = resolveAsType(st.value,context,states,roots,nominal,unconstrained);
} else if(type instanceof SyntacticType.Record) {
SyntacticType.Record tt = (SyntacticType.Record) type;
HashMap<String,SyntacticType> ttTypes = tt.types;
Type.Record.State fields = new Type.Record.State(tt.isOpen,ttTypes.keySet());
Collections.sort(fields);
myKind = Type.K_RECORD;
myChildren = new int[fields.size()];
for(int i=0;i!=fields.size();++i) {
String field = fields.get(i);
myChildren[i] = resolveAsType(ttTypes.get(field),context,states,roots,nominal,unconstrained);
}
myData = fields;
} else if(type instanceof SyntacticType.Tuple) {
SyntacticType.Tuple tt = (SyntacticType.Tuple) type;
ArrayList<SyntacticType> ttTypes = tt.types;
myKind = Type.K_TUPLE;
myChildren = new int[ttTypes.size()];
for(int i=0;i!=ttTypes.size();++i) {
myChildren[i] = resolveAsType(ttTypes.get(i),context,states,roots,nominal,unconstrained);
}
} else if(type instanceof SyntacticType.Nominal) {
// This case corresponds to a user-defined type. This will be
// defined in some module (possibly ours), and we need to identify
// what module that is here, and save it for future use.
SyntacticType.Nominal dt = (SyntacticType.Nominal) type;
NameID nid;
try {
nid = resolveAsName(dt.names, context);
if(nominal) {
myKind = Type.K_NOMINAL;
myData = nid;
myChildren = Automaton.NOCHILDREN;
} else {
// At this point, we're going to expand the given nominal type.
// We're going to use resolveAsType(NameID,...) to do this which
// will load the expanded type onto states at the current point.
// Therefore, we need to remove the initial null we loaded on.
states.remove(myIndex);
return resolveAsType(nid,states,roots,unconstrained);
}
} catch(ResolveError e) {
syntaxError(e.getMessage(),context,dt,e);
return 0; // dead-code
} catch(SyntaxError e) {
throw e;
} catch(Throwable e) {
internalFailure(e.getMessage(),context,dt,e);
return 0; // dead-code
}
} else if(type instanceof SyntacticType.Negation) {
SyntacticType.Negation ut = (SyntacticType.Negation) type;
myKind = Type.K_NEGATION;
myChildren = new int[1];
myChildren[0] = resolveAsType(ut.element,context,states,roots,nominal,unconstrained);
} else if(type instanceof SyntacticType.Union) {
SyntacticType.Union ut = (SyntacticType.Union) type;
ArrayList<SyntacticType.NonUnion> utTypes = ut.bounds;
myKind = Type.K_UNION;
myChildren = new int[utTypes.size()];
for(int i=0;i!=utTypes.size();++i) {
myChildren[i] = resolveAsType(utTypes.get(i),context,states,roots,nominal,unconstrained);
}
myDeterministic = false;
} else if(type instanceof SyntacticType.Intersection) {
internalFailure("intersection types not supported yet",context,type);
return 0; // dead-code
} else if(type instanceof SyntacticType.Reference) {
SyntacticType.Reference ut = (SyntacticType.Reference) type;
myKind = Type.K_REFERENCE;
myChildren = new int[1];
myChildren[0] = resolveAsType(ut.element,context,states,roots,nominal,unconstrained);
} else {
SyntacticType.FunctionOrMethod ut = (SyntacticType.FunctionOrMethod) type;
ArrayList<SyntacticType> utParamTypes = ut.paramTypes;
int start = 0;
if(ut instanceof SyntacticType.Method) {
myKind = Type.K_METHOD;
} else {
myKind = Type.K_FUNCTION;
}
myChildren = new int[start + 2 + utParamTypes.size()];
myChildren[start++] = resolveAsType(ut.ret,context,states,roots,nominal,unconstrained);
if(ut.throwType == null) {
// this case indicates the user did not provide a throws clause.
myChildren[start++] = resolveAsType(new SyntacticType.Void(),context,states,roots,nominal,unconstrained);
} else {
myChildren[start++] = resolveAsType(ut.throwType,context,states,roots,nominal,unconstrained);
}
for(SyntacticType pt : utParamTypes) {
myChildren[start++] = resolveAsType(pt,context,states,roots,nominal,unconstrained);
}
}
states.set(myIndex,new Automaton.State(myKind,myData,myDeterministic,myChildren));
return myIndex;
}
private int resolveAsType(NameID key, ArrayList<Automaton.State> states,
HashMap<NameID, Integer> roots, boolean unconstrained) throws Exception {
// First, check the various caches we have
Integer root = roots.get(key);
if (root != null) { return root; }
// check whether this type is external or not
WhileyFile wf = builder.getSourceFile(key.module());
if (wf == null) {
// indicates a non-local key which we can resolve immediately
// FIXME: need to properly support unconstrained types here
WyilFile mi = builder.getModule(key.module());
WyilFile.TypeDeclaration td = mi.type(key.name());
return append(td.type(),states);
}
WhileyFile.Type td = wf.typeDecl(key.name());
if(td == null) {
Type t = resolveAsConstant(key).type();
if(t instanceof Type.Set) {
if(unconstrained) {
// crikey this is ugly
int myIndex = states.size();
int kind = Type.leafKind(Type.T_VOID);
Object data = null;
states.add(new Automaton.State(kind,data,true,Automaton.NOCHILDREN));
return myIndex;
}
Type.Set ts = (Type.Set) t;
return append(ts.element(),states);
} else {
throw new ResolveError("type not found: " + key);
}
}
// following is needed to terminate any recursion
roots.put(key, states.size());
SyntacticType type = td.pattern.toSyntacticType();
// now, expand the given type fully
if(unconstrained && td.constraint != null) {
int myIndex = states.size();
int kind = Type.leafKind(Type.T_VOID);
Object data = null;
states.add(new Automaton.State(kind,data,true,Automaton.NOCHILDREN));
return myIndex;
} else if(type instanceof Type.Leaf) {
// FIXME: I believe this code is now redundant, and should be
// removed or updated. The problem is that SyntacticType no longer
// extends Type.
int myIndex = states.size();
int kind = Type.leafKind((Type.Leaf)type);
Object data = Type.leafData((Type.Leaf)type);
states.add(new Automaton.State(kind,data,true,Automaton.NOCHILDREN));
return myIndex;
} else {
return resolveAsType(type,td,states,roots,false,unconstrained);
}
// TODO: performance can be improved here, but actually assigning the
// constructed type into a cache of previously expanded types cache.
// This is challenging, in the case that the type may not be complete at
// this point. In particular, if it contains any back-links above this
// index there could be an issue.
}
private int resolveAsType(SyntacticType.Primitive t,
Context context, ArrayList<Automaton.State> states) {
int myIndex = states.size();
int kind;
if (t instanceof SyntacticType.Any) {
kind = Type.K_ANY;
} else if (t instanceof SyntacticType.Void) {
kind = Type.K_VOID;
} else if (t instanceof SyntacticType.Null) {
kind = Type.K_NULL;
} else if (t instanceof SyntacticType.Bool) {
kind = Type.K_BOOL;
} else if (t instanceof SyntacticType.Byte) {
kind = Type.K_BYTE;
} else if (t instanceof SyntacticType.Char) {
kind = Type.K_CHAR;
} else if (t instanceof SyntacticType.Int) {
kind = Type.K_INT;
} else if (t instanceof SyntacticType.Real) {
kind = Type.K_RATIONAL;
} else if (t instanceof SyntacticType.Strung) {
kind = Type.K_STRING;
} else {
internalFailure("unrecognised type encountered ("
+ t.getClass().getName() + ")",context,t);
return 0; // dead-code
}
states.add(new Automaton.State(kind, null, true,
Automaton.NOCHILDREN));
return myIndex;
}
private static int append(Type type, ArrayList<Automaton.State> states) {
int myIndex = states.size();
Automaton automaton = Type.destruct(type);
Automaton.State[] tStates = automaton.states;
int[] rmap = new int[tStates.length];
for (int i = 0, j = myIndex; i != rmap.length; ++i, ++j) {
rmap[i] = j;
}
for (Automaton.State state : tStates) {
states.add(Automata.remap(state, rmap));
}
return myIndex;
}
// ResolveAsConstant
public Constant resolveAsConstant(NameID nid) throws Exception {
return resolveAsConstant(nid,new HashSet<NameID>());
}
public Constant resolveAsConstant(Expr e, Context context) {
e = resolve(e, new Environment(),context);
return resolveAsConstant(e,context,new HashSet<NameID>());
}
private Constant resolveAsConstant(NameID key, HashSet<NameID> visited) throws Exception {
Constant result = constantCache.get(key);
if(result != null) {
return result;
} else if(visited.contains(key)) {
throw new ResolveError("cyclic constant definition encountered (" + key + " -> " + key + ")");
} else {
visited.add(key);
}
WhileyFile wf = builder.getSourceFile(key.module());
if (wf != null) {
WhileyFile.Declaration decl = wf.declaration(key.name());
if(decl instanceof WhileyFile.Constant) {
WhileyFile.Constant cd = (WhileyFile.Constant) decl;
if (cd.resolvedValue == null) {
cd.constant = resolve(cd.constant, new Environment(), cd);
cd.resolvedValue = resolveAsConstant(cd.constant,
cd, visited);
}
result = cd.resolvedValue;
} else {
throw new ResolveError("unable to find constant " + key);
}
} else {
WyilFile module = builder.getModule(key.module());
WyilFile.ConstantDeclaration cd = module.constant(key.name());
if(cd != null) {
result = cd.constant();
} else {
throw new ResolveError("unable to find constant " + key);
}
}
constantCache.put(key, result);
return result;
}
private Constant resolveAsConstant(Expr expr, Context context,
HashSet<NameID> visited) {
try {
if (expr instanceof Expr.Constant) {
Expr.Constant c = (Expr.Constant) expr;
return c.value;
} else if (expr instanceof Expr.ConstantAccess) {
Expr.ConstantAccess c = (Expr.ConstantAccess) expr;
return resolveAsConstant(c.nid,visited);
} else if (expr instanceof Expr.BinOp) {
Expr.BinOp bop = (Expr.BinOp) expr;
Constant lhs = resolveAsConstant(bop.lhs, context, visited);
Constant rhs = resolveAsConstant(bop.rhs, context, visited);
return evaluate(bop,lhs,rhs,context);
} else if (expr instanceof Expr.UnOp) {
Expr.UnOp uop = (Expr.UnOp) expr;
Constant lhs = resolveAsConstant(uop.mhs, context, visited);
return evaluate(uop,lhs,context);
} else if (expr instanceof Expr.Set) {
Expr.Set nop = (Expr.Set) expr;
ArrayList<Constant> values = new ArrayList<Constant>();
for (Expr arg : nop.arguments) {
values.add(resolveAsConstant(arg,context, visited));
}
return Constant.V_SET(values);
} else if (expr instanceof Expr.List) {
Expr.List nop = (Expr.List) expr;
ArrayList<Constant> values = new ArrayList<Constant>();
for (Expr arg : nop.arguments) {
values.add(resolveAsConstant(arg,context, visited));
}
return Constant.V_LIST(values);
} else if (expr instanceof Expr.Record) {
Expr.Record rg = (Expr.Record) expr;
HashMap<String,Constant> values = new HashMap<String,Constant>();
for(Map.Entry<String,Expr> e : rg.fields.entrySet()) {
Constant v = resolveAsConstant(e.getValue(),context,visited);
if(v == null) {
return null;
}
values.put(e.getKey(), v);
}
return Constant.V_RECORD(values);
} else if (expr instanceof Expr.Tuple) {
Expr.Tuple rg = (Expr.Tuple) expr;
ArrayList<Constant> values = new ArrayList<Constant>();
for(Expr e : rg.fields) {
Constant v = resolveAsConstant(e, context,visited);
if(v == null) {
return null;
}
values.add(v);
}
return Constant.V_TUPLE(values);
} else if (expr instanceof Expr.Map) {
Expr.Map rg = (Expr.Map) expr;
HashSet<Pair<Constant,Constant>> values = new HashSet<Pair<Constant,Constant>>();
for(Pair<Expr,Expr> e : rg.pairs) {
Constant key = resolveAsConstant(e.first(), context,visited);
Constant value = resolveAsConstant(e.second(), context,visited);
if(key == null || value == null) {
return null;
}
values.add(new Pair<Constant,Constant>(key,value));
}
return Constant.V_MAP(values);
} else if (expr instanceof Expr.FunctionOrMethod) {
// TODO: add support for proper lambdas
Expr.FunctionOrMethod f = (Expr.FunctionOrMethod) expr;
return Constant.V_LAMBDA(f.nid, f.type.raw());
}
} catch(SyntaxError.InternalFailure e) {
throw e;
} catch(ResolveError e) {
syntaxError(e.getMessage(),context,expr,e);
} catch(Throwable e) {
internalFailure(e.getMessage(),context,expr,e);
}
internalFailure("unknown constant expression: " + expr.getClass().getName(),context,expr);
return null; // deadcode
}
// expandAsType
public Nominal.EffectiveSet expandAsEffectiveSet(Nominal lhs) throws Exception {
Type raw = lhs.raw();
if(raw instanceof Type.EffectiveSet) {
Type nominal = expandOneLevel(lhs.nominal());
if(!(nominal instanceof Type.EffectiveSet)) {
nominal = raw; // discard nominal information
}
return (Nominal.EffectiveSet) Nominal.construct(nominal,raw);
} else {
return null;
}
}
public Nominal.EffectiveList expandAsEffectiveList(Nominal lhs) throws Exception {
Type raw = lhs.raw();
if(raw instanceof Type.EffectiveList) {
Type nominal = expandOneLevel(lhs.nominal());
if(!(nominal instanceof Type.EffectiveList)) {
nominal = raw; // discard nominal information
}
return (Nominal.EffectiveList) Nominal.construct(nominal,raw);
} else {
return null;
}
}
public Nominal.EffectiveCollection expandAsEffectiveCollection(Nominal lhs) throws Exception {
Type raw = lhs.raw();
if(raw instanceof Type.EffectiveCollection) {
Type nominal = expandOneLevel(lhs.nominal());
if(!(nominal instanceof Type.EffectiveCollection)) {
nominal = raw; // discard nominal information
}
return (Nominal.EffectiveCollection) Nominal.construct(nominal,raw);
} else {
return null;
}
}
public Nominal.EffectiveIndexible expandAsEffectiveMap(Nominal lhs) throws Exception {
Type raw = lhs.raw();
if(raw instanceof Type.EffectiveIndexible) {
Type nominal = expandOneLevel(lhs.nominal());
if(!(nominal instanceof Type.EffectiveIndexible)) {
nominal = raw; // discard nominal information
}
return (Nominal.EffectiveIndexible) Nominal.construct(nominal,raw);
} else {
return null;
}
}
public Nominal.EffectiveMap expandAsEffectiveDictionary(Nominal lhs) throws Exception {
Type raw = lhs.raw();
if(raw instanceof Type.EffectiveMap) {
Type nominal = expandOneLevel(lhs.nominal());
if(!(nominal instanceof Type.EffectiveMap)) {
nominal = raw; // discard nominal information
}
return (Nominal.EffectiveMap) Nominal.construct(nominal,raw);
} else {
return null;
}
}
public Nominal.EffectiveRecord expandAsEffectiveRecord(Nominal lhs) throws Exception {
Type raw = lhs.raw();
if(raw instanceof Type.Record) {
Type nominal = expandOneLevel(lhs.nominal());
if(!(nominal instanceof Type.Record)) {
nominal = (Type) raw; // discard nominal information
}
return (Nominal.Record) Nominal.construct(nominal,raw);
} else if(raw instanceof Type.UnionOfRecords) {
Type nominal = expandOneLevel(lhs.nominal());
if(!(nominal instanceof Type.UnionOfRecords)) {
nominal = (Type) raw; // discard nominal information
}
return (Nominal.UnionOfRecords) Nominal.construct(nominal,raw);
} {
return null;
}
}
public Nominal.EffectiveTuple expandAsEffectiveTuple(Nominal lhs) throws Exception {
Type raw = lhs.raw();
if(raw instanceof Type.EffectiveTuple) {
Type nominal = expandOneLevel(lhs.nominal());
if(!(nominal instanceof Type.EffectiveTuple)) {
nominal = raw; // discard nominal information
}
return (Nominal.EffectiveTuple) Nominal.construct(nominal,raw);
} else {
return null;
}
}
public Nominal.Reference expandAsReference(Nominal lhs) throws Exception {
Type.Reference raw = Type.effectiveReference(lhs.raw());
if(raw != null) {
Type nominal = expandOneLevel(lhs.nominal());
if(!(nominal instanceof Type.Reference)) {
nominal = raw; // discard nominal information
}
return (Nominal.Reference) Nominal.construct(nominal,raw);
} else {
return null;
}
}
public Nominal.FunctionOrMethod expandAsFunctionOrMethod(Nominal lhs) throws Exception {
Type.FunctionOrMethod raw = Type.effectiveFunctionOrMethod(lhs.raw());
if(raw != null) {
Type nominal = expandOneLevel(lhs.nominal());
if(!(nominal instanceof Type.FunctionOrMethod)) {
nominal = raw; // discard nominal information
}
return (Nominal.FunctionOrMethod) Nominal.construct(nominal,raw);
} else {
return null;
}
}
private Type expandOneLevel(Type type) throws Exception {
if(type instanceof Type.Nominal){
Type.Nominal nt = (Type.Nominal) type;
NameID nid = nt.name();
Path.ID mid = nid.module();
WhileyFile wf = builder.getSourceFile(mid);
Type r = null;
if (wf != null) {
WhileyFile.Declaration decl = wf.declaration(nid.name());
if(decl instanceof WhileyFile.Type) {
WhileyFile.Type td = (WhileyFile.Type) decl;
r = resolveAsType(td.pattern.toSyntacticType(), td)
.nominal();
}
} else {
WyilFile m = builder.getModule(mid);
WyilFile.TypeDeclaration td = m.type(nid.name());
if(td != null) {
r = td.type();
}
}
if(r == null) {
throw new ResolveError("unable to locate " + nid);
}
return expandOneLevel(r);
} else if(type instanceof Type.Leaf
|| type instanceof Type.Reference
|| type instanceof Type.Tuple
|| type instanceof Type.Set
|| type instanceof Type.List
|| type instanceof Type.Map
|| type instanceof Type.Record
|| type instanceof Type.FunctionOrMethod
|| type instanceof Type.Negation) {
return type;
} else {
Type.Union ut = (Type.Union) type;
ArrayList<Type> bounds = new ArrayList<Type>();
for(Type b : ut.bounds()) {
bounds.add(expandOneLevel(b));
}
return Type.Union(bounds);
}
}
// Constant Evaluation [this should not be located here?]
private Constant evaluate(Expr.UnOp bop, Constant v, Context context) {
switch(bop.op) {
case NOT:
if(v instanceof Constant.Bool) {
Constant.Bool b = (Constant.Bool) v;
return Constant.V_BOOL(!b.value);
}
syntaxError(errorMessage(INVALID_BOOLEAN_EXPRESSION),context,bop);
break;
case NEG:
if(v instanceof Constant.Integer) {
Constant.Integer b = (Constant.Integer) v;
return Constant.V_INTEGER(b.value.negate());
} else if(v instanceof Constant.Decimal) {
Constant.Decimal b = (Constant.Decimal) v;
return Constant.V_DECIMAL(b.value.negate());
}
syntaxError(errorMessage(INVALID_NUMERIC_EXPRESSION),context,bop);
break;
case INVERT:
if(v instanceof Constant.Byte) {
Constant.Byte b = (Constant.Byte) v;
return Constant.V_BYTE((byte) ~b.value);
}
break;
}
syntaxError(errorMessage(INVALID_UNARY_EXPRESSION),context,bop);
return null;
}
private Constant evaluate(Expr.BinOp bop, Constant v1, Constant v2, Context context) {
Type v1_type = v1.type();
Type v2_type = v2.type();
Type lub = Type.Union(v1_type, v2_type);
// FIXME: there are bugs here related to coercions.
if(Type.isSubtype(Type.T_BOOL, lub)) {
return evaluateBoolean(bop,(Constant.Bool) v1,(Constant.Bool) v2, context);
} else if(Type.isSubtype(Type.T_INT, lub)) {
return evaluate(bop,(Constant.Integer) v1, (Constant.Integer) v2, context);
} else if (Type.isImplicitCoerciveSubtype(Type.T_REAL, v1_type)
&& Type.isImplicitCoerciveSubtype(Type.T_REAL, v1_type)) {
if(v1 instanceof Constant.Integer) {
Constant.Integer i1 = (Constant.Integer) v1;
v1 = Constant.V_DECIMAL(new BigDecimal(i1.value));
} else if(v2 instanceof Constant.Integer) {
Constant.Integer i2 = (Constant.Integer) v2;
v2 = Constant.V_DECIMAL(new BigDecimal(i2.value));
}
return evaluate(bop,(Constant.Decimal) v1, (Constant.Decimal) v2, context);
} else if(Type.isSubtype(Type.T_LIST_ANY, lub)) {
return evaluate(bop,(Constant.List)v1,(Constant.List)v2, context);
} else if(Type.isSubtype(Type.T_SET_ANY, lub)) {
return evaluate(bop,(Constant.Set) v1, (Constant.Set) v2, context);
}
syntaxError(errorMessage(INVALID_BINARY_EXPRESSION),context,bop);
return null;
}
private Constant evaluateBoolean(Expr.BinOp bop, Constant.Bool v1, Constant.Bool v2, Context context) {
switch(bop.op) {
case AND:
return Constant.V_BOOL(v1.value & v2.value);
case OR:
return Constant.V_BOOL(v1.value | v2.value);
case XOR:
return Constant.V_BOOL(v1.value ^ v2.value);
}
syntaxError(errorMessage(INVALID_BOOLEAN_EXPRESSION),context,bop);
return null;
}
private Constant evaluate(Expr.BinOp bop, Constant.Integer v1, Constant.Integer v2, Context context) {
switch(bop.op) {
case ADD:
return Constant.V_INTEGER(v1.value.add(v2.value));
case SUB:
return Constant.V_INTEGER(v1.value.subtract(v2.value));
case MUL:
return Constant.V_INTEGER(v1.value.multiply(v2.value));
case DIV:
return Constant.V_INTEGER(v1.value.divide(v2.value));
case REM:
return Constant.V_INTEGER(v1.value.remainder(v2.value));
}
syntaxError(errorMessage(INVALID_NUMERIC_EXPRESSION),context,bop);
return null;
}
private Constant evaluate(Expr.BinOp bop, Constant.Decimal v1, Constant.Decimal v2, Context context) {
switch(bop.op) {
case ADD:
return Constant.V_DECIMAL(v1.value.add(v2.value));
case SUB:
return Constant.V_DECIMAL(v1.value.subtract(v2.value));
case MUL:
return Constant.V_DECIMAL(v1.value.multiply(v2.value));
case DIV:
return Constant.V_DECIMAL(v1.value.divide(v2.value));
}
syntaxError(errorMessage(INVALID_NUMERIC_EXPRESSION),context,bop);
return null;
}
private Constant evaluate(Expr.BinOp bop, Constant.List v1, Constant.List v2, Context context) {
switch(bop.op) {
case ADD:
ArrayList<Constant> vals = new ArrayList<Constant>(v1.values);
vals.addAll(v2.values);
return Constant.V_LIST(vals);
}
syntaxError(errorMessage(INVALID_LIST_EXPRESSION),context,bop);
return null;
}
private Constant evaluate(Expr.BinOp bop, Constant.Set v1, Constant.Set v2, Context context) {
switch(bop.op) {
case UNION:
{
HashSet<Constant> vals = new HashSet<Constant>(v1.values);
vals.addAll(v2.values);
return Constant.V_SET(vals);
}
case INTERSECTION:
{
HashSet<Constant> vals = new HashSet<Constant>();
for(Constant v : v1.values) {
if(v2.values.contains(v)) {
vals.add(v);
}
}
return Constant.V_SET(vals);
}
case SUB:
{
HashSet<Constant> vals = new HashSet<Constant>();
for(Constant v : v1.values) {
if(!v2.values.contains(v)) {
vals.add(v);
}
}
return Constant.V_SET(vals);
}
}
syntaxError(errorMessage(INVALID_SET_EXPRESSION),context,bop);
return null;
}
public boolean isVisible(NameID nid, Context context) throws Exception {
Path.ID mid = nid.module();
if(mid.equals(context.file().module)) {
return true;
}
WhileyFile wf = builder.getSourceFile(mid);
if(wf != null) {
Declaration d = wf.declaration(nid.name());
if(d instanceof WhileyFile.Constant) {
WhileyFile.Constant td = (WhileyFile.Constant) d;
return td.isPublic() || td.isProtected();
} else if(d instanceof WhileyFile.Type) {
WhileyFile.Type td = (WhileyFile.Type) d;
return td.isPublic() || td.isProtected();
}
return false;
} else {
// we have to do the following basically because we don't load
// modifiers properly out of jvm class files (at the moment).
return true;
// WyilFile w = builder.getModule(mid);
// WyilFile.ConstDef c = w.constant(nid.name());
// WyilFile.TypeDef t = w.type(nid.name());
// if(c != null) {
// return c.isPublic() || c.isProtected();
// } else {
// return t.isPublic() || t.isProtected();
}
}
// Misc
// Check t1 :> t2
private void checkIsSubtype(Nominal t1, Nominal t2, SyntacticElement elem, Context context) {
if (!Type.isImplicitCoerciveSubtype(t1.raw(), t2.raw())) {
syntaxError(
errorMessage(SUBTYPE_ERROR, t1.nominal(), t2.nominal()),
context, elem);
}
}
private void checkIsSubtype(Nominal t1, Expr t2, Context context) {
if (!Type.isImplicitCoerciveSubtype(t1.raw(), t2.result().raw())) {
// We use the nominal type for error reporting, since this includes
// more helpful names.
syntaxError(
errorMessage(SUBTYPE_ERROR, t1.nominal(), t2.result()
.nominal()), context, t2);
}
}
private void checkIsSubtype(Type t1, Expr t2, Context context) {
if (!Type.isImplicitCoerciveSubtype(t1, t2.result().raw())) {
// We use the nominal type for error reporting, since this includes
// more helpful names.
syntaxError(errorMessage(SUBTYPE_ERROR, t1, t2.result().nominal()),
context, t2);
}
}
private static final Environment BOTTOM = new Environment();
private static final Environment join(
Environment lhs,
Environment rhs) {
// first, need to check for the special bottom value case.
if(lhs == BOTTOM) {
return rhs;
} else if(rhs == BOTTOM) {
return lhs;
}
// ok, not bottom so compute intersection.
lhs.free();
rhs.free();
Environment result = new Environment();
for(String key : lhs.keySet()) {
if(rhs.containsKey(key)) {
Nominal lhs_t = lhs.get(key);
Nominal rhs_t = rhs.get(key);
result.put(key, Nominal.Union(lhs_t, rhs_t));
}
}
return result;
}
private abstract static class Scope {
public abstract void free();
}
private static final class Handler {
public final Type exception;
public final String variable;
public Environment environment;
public Handler(Type exception, String variable) {
this.exception = exception;
this.variable = variable;
this.environment = new Environment();
}
}
}
|
package com.jme3.audio;
import com.jme3.asset.AssetManager;
import com.jme3.asset.AssetNotFoundException;
import com.jme3.export.InputCapsule;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.OutputCapsule;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import com.jme3.util.PlaceholderAssets;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* An <code>AudioNode</code> is used in jME3 for playing audio files.
* <br/>
* First, an {@link AudioNode} is loaded from file, and then assigned
* to an audio node for playback. Once the audio node is attached to the
* scene, its location will influence the position it is playing from relative
* to the {@link Listener}.
* <br/>
* An audio node can also play in "headspace", meaning its location
* or velocity does not influence how it is played.
* The "positional" property of an AudioNode can be set via
* {@link AudioNode#setPositional(boolean) }.
*
* @author normenhansen
* @author Kirill Vainer
*/
public class AudioNode extends Node {
//Version #1 : AudioKey is now stored into "audio_key" instead of "key"
public static final int SAVABLE_VERSION = 1;
protected boolean loop = false;
protected float volume = 1;
protected float pitch = 1;
protected float timeOffset = 0;
protected Filter dryFilter;
protected AudioKey audioKey;
protected transient AudioData data = null;
protected transient volatile Status status = Status.Stopped;
protected transient volatile int channel = -1;
protected Vector3f velocity = new Vector3f();
protected boolean reverbEnabled = true;
protected float maxDistance = 200; // 200 meters
protected float refDistance = 10; // 10 meters
protected Filter reverbFilter;
private boolean directional = false;
protected Vector3f direction = new Vector3f(0, 0, 1);
protected float innerAngle = 360;
protected float outerAngle = 360;
protected boolean positional = true;
/**
* <code>Status</code> indicates the current status of the audio node.
*/
public enum Status {
/**
* The audio node is currently playing. This will be set if
* {@link AudioNode#play() } is called.
*/
Playing,
/**
* The audio node is currently paused.
*/
Paused,
/**
* The audio node is currently stopped.
* This will be set if {@link AudioNode#stop() } is called
* or the audio has reached the end of the file.
*/
Stopped,
}
/**
* Creates a new <code>AudioNode</code> without any audio data set.
*/
public AudioNode() {
}
/**
* Creates a new <code>AudioNode</code> with the given data and key.
*
* @param audioData The audio data contains the audio track to play.
* @param audioKey The audio key that was used to load the AudioData
*/
public AudioNode(AudioData audioData, AudioKey audioKey) {
setAudioData(audioData, audioKey);
}
/**
* Creates a new <code>AudioNode</code> with the given audio file.
*
* @param assetManager The asset manager to use to load the audio file
* @param name The filename of the audio file
* @param stream If true, the audio will be streamed gradually from disk,
* otherwise, it will be buffered.
* @param streamCache If stream is also true, then this specifies if
* the stream cache is used. When enabled, the audio stream will
* be read entirely but not decoded, allowing features such as
* seeking, looping and determining duration.
*/
public AudioNode(AssetManager assetManager, String name, boolean stream, boolean streamCache) {
this.audioKey = new AudioKey(name, stream, streamCache);
this.data = (AudioData) assetManager.loadAsset(audioKey);
}
/**
* Creates a new <code>AudioNode</code> with the given audio file.
*
* @param assetManager The asset manager to use to load the audio file
* @param name The filename of the audio file
* @param stream If true, the audio will be streamed gradually from disk,
* otherwise, it will be buffered.
*/
public AudioNode(AssetManager assetManager, String name, boolean stream) {
this(assetManager, name, stream, false);
}
/**
* Creates a new <code>AudioNode</code> with the given audio file.
*
* @param audioRenderer The audio renderer to use for playing. Cannot be null.
* @param assetManager The asset manager to use to load the audio file
* @param name The filename of the audio file
*
* @deprecated AudioRenderer parameter is ignored.
*/
public AudioNode(AudioRenderer audioRenderer, AssetManager assetManager, String name) {
this(assetManager, name, false);
}
/**
* Creates a new <code>AudioNode</code> with the given audio file.
*
* @param assetManager The asset manager to use to load the audio file
* @param name The filename of the audio file
*/
public AudioNode(AssetManager assetManager, String name) {
this(assetManager, name, false);
}
protected AudioRenderer getRenderer() {
AudioRenderer result = AudioContext.getAudioRenderer();
if( result == null )
throw new IllegalStateException( "No audio renderer available, make sure call is being performed on render thread." );
return result;
}
/**
* Start playing the audio.
*/
public void play(){
getRenderer().playSource(this);
}
/**
* Start playing an instance of this audio. This method can be used
* to play the same <code>AudioNode</code> multiple times. Note
* that changes to the parameters of this AudioNode will not effect the
* instances already playing.
*/
public void playInstance(){
getRenderer().playSourceInstance(this);
}
/**
* Stop playing the audio that was started with {@link AudioNode#play() }.
*/
public void stop(){
getRenderer().stopSource(this);
}
/**
* Pause the audio that was started with {@link AudioNode#play() }.
*/
public void pause(){
getRenderer().pauseSource(this);
}
/**
* Do not use.
*/
public final void setChannel(int channel) {
if (status != Status.Stopped) {
throw new IllegalStateException("Can only set source id when stopped");
}
this.channel = channel;
}
/**
* Do not use.
*/
public int getChannel() {
return channel;
}
/**
* @return The {#link Filter dry filter} that is set.
* @see AudioNode#setDryFilter(com.jme3.audio.Filter)
*/
public Filter getDryFilter() {
return dryFilter;
}
/**
* Set the dry filter to use for this audio node.
*
* When {@link AudioNode#setReverbEnabled(boolean) reverb} is used,
* the dry filter will only influence the "dry" portion of the audio,
* e.g. not the reverberated parts of the AudioNode playing.
*
* See the relevent documentation for the {@link Filter} to determine
* the effect.
*
* @param dryFilter The filter to set, or null to disable dry filter.
*/
public void setDryFilter(Filter dryFilter) {
this.dryFilter = dryFilter;
if (channel >= 0)
getRenderer().updateSourceParam(this, AudioParam.DryFilter);
}
/**
* Set the audio data to use for the audio. Note that this method
* can only be called once, if for example the audio node was initialized
* without an {@link AudioData}.
*
* @param audioData The audio data contains the audio track to play.
* @param audioKey The audio key that was used to load the AudioData
*/
public void setAudioData(AudioData audioData, AudioKey audioKey) {
if (data != null) {
throw new IllegalStateException("Cannot change data once its set");
}
data = audioData;
this.audioKey = audioKey;
}
/**
* @return The {@link AudioData} set previously with
* {@link AudioNode#setAudioData(com.jme3.audio.AudioData, com.jme3.audio.AudioKey) }
* or any of the constructors that initialize the audio data.
*/
public AudioData getAudioData() {
return data;
}
/**
* @return The {@link Status} of the audio node.
* The status will be changed when either the {@link AudioNode#play() }
* or {@link AudioNode#stop() } methods are called.
*/
public Status getStatus() {
return status;
}
/**
* Do not use.
*/
public final void setStatus(Status status) {
this.status = status;
}
/**
* @return True if the audio will keep looping after it is done playing,
* otherwise, false.
* @see AudioNode#setLooping(boolean)
*/
public boolean isLooping() {
return loop;
}
/**
* Set the looping mode for the audio node. The default is false.
*
* @param loop True if the audio should keep looping after it is done playing.
*/
public void setLooping(boolean loop) {
this.loop = loop;
if (channel >= 0)
getRenderer().updateSourceParam(this, AudioParam.Looping);
}
/**
* @return The pitch of the audio, also the speed of playback.
*
* @see AudioNode#setPitch(float)
*/
public float getPitch() {
return pitch;
}
public void setPitch(float pitch) {
if (pitch < 0.5f || pitch > 2.0f) {
throw new IllegalArgumentException("Pitch must be between 0.5 and 2.0");
}
this.pitch = pitch;
if (channel >= 0)
getRenderer().updateSourceParam(this, AudioParam.Pitch);
}
/**
* @return The volume of this audio node.
*
* @see AudioNode#setVolume(float)
*/
public float getVolume() {
return volume;
}
public void setVolume(float volume) {
if (volume < 0f) {
throw new IllegalArgumentException("Volume cannot be negative");
}
this.volume = volume;
if (channel >= 0)
getRenderer().updateSourceParam(this, AudioParam.Volume);
}
/**
* @return the time offset in the sound sample when to start playing.
*/
public float getTimeOffset() {
return timeOffset;
}
public void setTimeOffset(float timeOffset) {
if (timeOffset < 0f) {
throw new IllegalArgumentException("Time offset cannot be negative");
}
this.timeOffset = timeOffset;
if (data instanceof AudioStream) {
System.out.println("request setTime");
((AudioStream) data).setTime(timeOffset);
}else if(status == Status.Playing){
stop();
play();
}
}
/**
* @return The velocity of the audio node.
*
* @see AudioNode#setVelocity(com.jme3.math.Vector3f)
*/
public Vector3f getVelocity() {
return velocity;
}
/**
* Set the velocity of the audio node. The velocity is expected
* to be in meters. Does nothing if the audio node is not positional.
*
* @param velocity The velocity to set.
* @see AudioNode#setPositional(boolean)
*/
public void setVelocity(Vector3f velocity) {
this.velocity.set(velocity);
if (channel >= 0)
getRenderer().updateSourceParam(this, AudioParam.Velocity);
}
/**
* @return True if reverb is enabled, otherwise false.
*
* @see AudioNode#setReverbEnabled(boolean)
*/
public boolean isReverbEnabled() {
return reverbEnabled;
}
/**
* Set to true to enable reverberation effects for this audio node.
* Does nothing if the audio node is not positional.
* <br/>
* When enabled, the audio environment set with
* {@link AudioRenderer#setEnvironment(com.jme3.audio.Environment) }
* will apply a reverb effect to the audio playing from this audio node.
*
* @param reverbEnabled True to enable reverb.
*/
public void setReverbEnabled(boolean reverbEnabled) {
this.reverbEnabled = reverbEnabled;
if (channel >= 0) {
getRenderer().updateSourceParam(this, AudioParam.ReverbEnabled);
}
}
/**
* @return Filter for the reverberations of this audio node.
*
* @see AudioNode#setReverbFilter(com.jme3.audio.Filter)
*/
public Filter getReverbFilter() {
return reverbFilter;
}
/**
* Set the reverb filter for this audio node.
* <br/>
* The reverb filter will influence the reverberations
* of the audio node playing. This only has an effect if
* reverb is enabled.
*
* @param reverbFilter The reverb filter to set.
* @see AudioNode#setDryFilter(com.jme3.audio.Filter)
*/
public void setReverbFilter(Filter reverbFilter) {
this.reverbFilter = reverbFilter;
if (channel >= 0)
getRenderer().updateSourceParam(this, AudioParam.ReverbFilter);
}
/**
* @return Max distance for this audio node.
*
* @see AudioNode#setMaxDistance(float)
*/
public float getMaxDistance() {
return maxDistance;
}
public void setMaxDistance(float maxDistance) {
if (maxDistance < 0) {
throw new IllegalArgumentException("Max distance cannot be negative");
}
this.maxDistance = maxDistance;
if (channel >= 0)
getRenderer().updateSourceParam(this, AudioParam.MaxDistance);
}
/**
* @return The reference playing distance for the audio node.
*
* @see AudioNode#setRefDistance(float)
*/
public float getRefDistance() {
return refDistance;
}
public void setRefDistance(float refDistance) {
if (refDistance < 0) {
throw new IllegalArgumentException("Reference distance cannot be negative");
}
this.refDistance = refDistance;
if (channel >= 0)
getRenderer().updateSourceParam(this, AudioParam.RefDistance);
}
/**
* @return True if the audio node is directional
*
* @see AudioNode#setDirectional(boolean)
*/
public boolean isDirectional() {
return directional;
}
/**
* Set the audio node to be directional.
* Does nothing if the audio node is not positional.
* <br/>
* After setting directional, you should call
* {@link AudioNode#setDirection(com.jme3.math.Vector3f) }
* to set the audio node's direction.
*
* @param directional If the audio node is directional
*/
public void setDirectional(boolean directional) {
this.directional = directional;
if (channel >= 0)
getRenderer().updateSourceParam(this, AudioParam.IsDirectional);
}
/**
* @return The direction of this audio node.
*
* @see AudioNode#setDirection(com.jme3.math.Vector3f)
*/
public Vector3f getDirection() {
return direction;
}
/**
* Set the direction of this audio node.
* Does nothing if the audio node is not directional.
*
* @param direction
* @see AudioNode#setDirectional(boolean)
*/
public void setDirection(Vector3f direction) {
this.direction = direction;
if (channel >= 0)
getRenderer().updateSourceParam(this, AudioParam.Direction);
}
/**
* @return The directional audio node, cone inner angle.
*
* @see AudioNode#setInnerAngle(float)
*/
public float getInnerAngle() {
return innerAngle;
}
/**
* Set the directional audio node cone inner angle.
* Does nothing if the audio node is not directional.
*
* @param innerAngle The cone inner angle.
*/
public void setInnerAngle(float innerAngle) {
this.innerAngle = innerAngle;
if (channel >= 0)
getRenderer().updateSourceParam(this, AudioParam.InnerAngle);
}
/**
* @return The directional audio node, cone outer angle.
*
* @see AudioNode#setOuterAngle(float)
*/
public float getOuterAngle() {
return outerAngle;
}
/**
* Set the directional audio node cone outer angle.
* Does nothing if the audio node is not directional.
*
* @param outerAngle The cone outer angle.
*/
public void setOuterAngle(float outerAngle) {
this.outerAngle = outerAngle;
if (channel >= 0)
getRenderer().updateSourceParam(this, AudioParam.OuterAngle);
}
/**
* @return True if the audio node is positional.
*
* @see AudioNode#setPositional(boolean)
*/
public boolean isPositional() {
return positional;
}
/**
* Set the audio node as positional.
* The position, velocity, and distance parameters effect positional
* audio nodes. Set to false if the audio node should play in "headspace".
*
* @param positional True if the audio node should be positional, otherwise
* false if it should be headspace.
*/
public void setPositional(boolean positional) {
this.positional = positional;
if (channel >= 0) {
getRenderer().updateSourceParam(this, AudioParam.IsPositional);
}
}
@Override
public void updateGeometricState(){
boolean updatePos = false;
if ((refreshFlags & RF_TRANSFORM) != 0){
updatePos = true;
}
super.updateGeometricState();
if (updatePos && channel >= 0)
getRenderer().updateSourceParam(this, AudioParam.Position);
}
@Override
public AudioNode clone(){
AudioNode clone = (AudioNode) super.clone();
clone.direction = direction.clone();
clone.velocity = velocity.clone();
return clone;
}
@Override
public void write(JmeExporter ex) throws IOException {
super.write(ex);
OutputCapsule oc = ex.getCapsule(this);
oc.write(audioKey, "audio_key", null);
oc.write(loop, "looping", false);
oc.write(volume, "volume", 1);
oc.write(pitch, "pitch", 1);
oc.write(timeOffset, "time_offset", 0);
oc.write(dryFilter, "dry_filter", null);
oc.write(velocity, "velocity", null);
oc.write(reverbEnabled, "reverb_enabled", false);
oc.write(reverbFilter, "reverb_filter", null);
oc.write(maxDistance, "max_distance", 20);
oc.write(refDistance, "ref_distance", 10);
oc.write(directional, "directional", false);
oc.write(direction, "direction", null);
oc.write(innerAngle, "inner_angle", 360);
oc.write(outerAngle, "outer_angle", 360);
oc.write(positional, "positional", false);
}
@Override
public void read(JmeImporter im) throws IOException {
super.read(im);
InputCapsule ic = im.getCapsule(this);
// NOTE: In previous versions of jME3, audioKey was actually
// written with the name "key". This has been changed
// to "audio_key" in case Spatial's key will be written as "key".
if (ic.getSavableVersion(AudioNode.class) == 0){
audioKey = (AudioKey) ic.readSavable("key", null);
}else{
audioKey = (AudioKey) ic.readSavable("audio_key", null);
}
loop = ic.readBoolean("looping", false);
volume = ic.readFloat("volume", 1);
pitch = ic.readFloat("pitch", 1);
timeOffset = ic.readFloat("time_offset", 0);
dryFilter = (Filter) ic.readSavable("dry_filter", null);
velocity = (Vector3f) ic.readSavable("velocity", null);
reverbEnabled = ic.readBoolean("reverb_enabled", false);
reverbFilter = (Filter) ic.readSavable("reverb_filter", null);
maxDistance = ic.readFloat("max_distance", 20);
refDistance = ic.readFloat("ref_distance", 10);
directional = ic.readBoolean("directional", false);
direction = (Vector3f) ic.readSavable("direction", null);
innerAngle = ic.readFloat("inner_angle", 360);
outerAngle = ic.readFloat("outer_angle", 360);
positional = ic.readBoolean("positional", false);
if (audioKey != null) {
try {
data = im.getAssetManager().loadAsset(audioKey);
} catch (AssetNotFoundException ex){
Logger.getLogger(AudioNode.class.getName()).log(Level.FINE, "Cannot locate {0} for audio node {1}", new Object[]{audioKey, key});
data = PlaceholderAssets.getPlaceholderAudio();
}
}
}
@Override
public String toString() {
String ret = getClass().getSimpleName()
+ "[status=" + status;
if (volume != 1f) {
ret += ", vol=" + volume;
}
if (pitch != 1f) {
ret += ", pitch=" + pitch;
}
return ret + "]";
}
}
|
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import api.gui.swing.ApplicationWindow;
import api.gui.swing.RichTextPane;
import api.util.EventHandler;
import api.util.Support;
public class GraphDominatrixDemo
{
public final static void main(final String[] args)
{
new GraphDominatrixDemo(args);
}
private boolean isDebugging = false;
private RichTextPane output = null;
private ApplicationWindow window = null;
public GraphDominatrixDemo(final String[] args)
{
this.setDebugging(Support.promptDebugMode(this.getWindow()));
// Define a self-contained ActionListener event handler.
EventHandler<GraphDominatrixDemo> myActionPerformed = new EventHandler<GraphDominatrixDemo>(this)
{
private final static long serialVersionUID = 1L;
@Override
public final void run(final AWTEvent event)
{
ActionEvent actionEvent = (ActionEvent)event;
GraphDominatrixDemo parent = this.getParent();
if (parent.getOutput() != null)
{
switch (actionEvent.getActionCommand())
{
case "Clear":
parent.getOutput().clear();
break;
case "Open":
parent.getOutput().openOrSaveFile(true);
break;
case "Save":
parent.getOutput().openOrSaveFile(false);
break;
default:
break;
}
}
}
};
// Define a self-contained interface construction event handler.
EventHandler<GraphDominatrixDemo> myDrawGUI = new EventHandler<GraphDominatrixDemo>(this)
{
private final static long serialVersionUID = 1L;
@Override
public final void run(final ApplicationWindow window)
{
GraphDominatrixDemo parent = this.getParent();
Container contentPane = window.getContentPane();
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem clearOption = new JMenuItem("Clear");
JMenuItem openOption = new JMenuItem("Open");
JMenuItem saveOption = new JMenuItem("Save");
JPanel graphPanel = new JPanel();
RichTextPane outputBox = new RichTextPane(window, true, window.isDebugging());
JScrollPane outputPanel = new JScrollPane(outputBox);
clearOption.setFont(Support.DEFAULT_TEXT_FONT);
clearOption.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.Event.CTRL_MASK));
clearOption.setMnemonic('C');
clearOption.addActionListener(window);
openOption.setFont(Support.DEFAULT_TEXT_FONT);
openOption.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.Event.CTRL_MASK));
openOption.setMnemonic('O');
openOption.addActionListener(window);
saveOption.setFont(Support.DEFAULT_TEXT_FONT);
saveOption.setAccelerator(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.Event.CTRL_MASK));
saveOption.setMnemonic('S');
saveOption.addActionListener(window);
fileMenu.setFont(Support.DEFAULT_TEXT_FONT);
fileMenu.setMnemonic('F');
fileMenu.add(clearOption);
fileMenu.add(openOption);
fileMenu.add(saveOption);
menuBar.setFont(Support.DEFAULT_TEXT_FONT);
menuBar.add(fileMenu);
window.setJMenuBar(menuBar);
contentPane.setLayout(new BorderLayout());
contentPane.add(graphPanel, BorderLayout.CENTER);
contentPane.add(outputPanel, BorderLayout.SOUTH);
parent.setOutput(outputBox);
}
};
this.setWindow(new ApplicationWindow(null, "Graph Dominatrix", new Dimension(800, 600), this.isDebugging(),
false, myActionPerformed, myDrawGUI));
}
public final RichTextPane getOutput()
{
return this.output;
}
public final ApplicationWindow getWindow()
{
return this.window;
}
public final boolean isDebugging()
{
return this.isDebugging;
}
protected final void setDebugging(final boolean isDebugging)
{
this.isDebugging = isDebugging;
}
protected final void setOutput(final RichTextPane output)
{
this.output = output;
}
protected final void setWindow(final ApplicationWindow window)
{
this.window = window;
}
}
|
package etomica.surfacetension;
import java.util.List;
import etomica.action.IAction;
import etomica.action.activity.ActivityIntegrate;
import etomica.api.IAtomList;
import etomica.api.IAtomType;
import etomica.api.IBox;
import etomica.api.IVector;
import etomica.api.IVectorMutable;
import etomica.box.Box;
import etomica.config.ConfigurationLattice;
import etomica.data.AccumulatorAverage;
import etomica.data.AccumulatorAverageCollapsing;
import etomica.data.AccumulatorAverageFixed;
import etomica.data.AccumulatorHistory;
import etomica.data.DataDump;
import etomica.data.DataFork;
import etomica.data.DataProcessor;
import etomica.data.DataPump;
import etomica.data.DataPumpListener;
import etomica.data.DataSourceCountSteps;
import etomica.data.DataTag;
import etomica.data.meter.MeterNMolecules;
import etomica.data.meter.MeterPressureTensor;
import etomica.data.meter.MeterProfileByVolume;
import etomica.graphics.DisplayPlot;
import etomica.graphics.DisplayTextBoxesCAE;
import etomica.graphics.SimulationGraphic;
import etomica.integrator.IntegratorMC;
import etomica.integrator.mcmove.MCMoveAtomInRegion;
import etomica.integrator.mcmove.MCMoveStepTracker;
import etomica.lattice.LatticeCubicFcc;
import etomica.listener.IntegratorListenerAction;
import etomica.nbr.cell.PotentialMasterCell;
import etomica.potential.P2LennardJones;
import etomica.potential.P2SoftSphericalTruncated;
import etomica.simulation.Simulation;
import etomica.space.ISpace;
import etomica.space3d.Space3D;
import etomica.species.SpeciesSpheresMono;
import etomica.util.HistoryCollapsingAverage;
import etomica.util.ParameterBase;
import etomica.util.ParseArgs;
public class LJMC extends Simulation {
public final PotentialMasterCell potentialMaster;
public final SpeciesSpheresMono species;
public final IBox box;
public final ActivityIntegrate activityIntegrate;
public final IntegratorMC integrator;
public final MCMoveAtomInRegion mcMoveAtom, mcMoveAtomBigStep;
public LJMC(ISpace _space, int numAtoms, double temperature, double aspectRatio) {
super(_space);
double rc = 4.0;
potentialMaster = new PotentialMasterCell(this, rc, space);
potentialMaster.setCellRange(2);
potentialMaster.lrcMaster().setEnabled(false);
//controller and integrator
integrator = new IntegratorMC(potentialMaster, random, 1.0);
activityIntegrate = new ActivityIntegrate(integrator);
getController().addAction(activityIntegrate);
//species and potentials
species = new SpeciesSpheresMono(this, space);//index 1
species.setIsDynamic(true);
addSpecies(species);
//instantiate several potentials for selection in combo-box
P2LennardJones potential = new P2LennardJones(space);
P2SoftSphericalTruncated p2Truncated = new P2SoftSphericalTruncated(space, potential, rc);
potentialMaster.addPotential(p2Truncated, new IAtomType[]{species.getLeafType(), species.getLeafType()});
//construct box
box = new Box(space);
addBox(box);
IVectorMutable dim = space.makeVector();
box.getBoundary().setBoxSize(dim);
integrator.setBox(box);
mcMoveAtom = new MCMoveAtomInRegion(random, potentialMaster, space);
integrator.getMoveManager().addMCMove(mcMoveAtom);
mcMoveAtomBigStep = new MCMoveAtomInRegion(random, potentialMaster, space);
// mcMoveAtomBigStep.setStepSize(6);
// mcMoveAtomBigStep.setStepSizeMin(5);
integrator.getMoveManager().addMCMove(mcMoveAtomBigStep);
integrator.getMoveManager().setFrequency(mcMoveAtomBigStep, 0.2);
//new ConfigurationLattice(new LatticeCubicFcc(space), space).initializeCoordinates(box);
double Tc = 1.31;
double rhoc = 0.314;
double T = temperature;
double rhoV = rhoc - 0.477*Math.pow(Tc-T,1.0/3.0) + 0.05333*(Tc-T) + 0.1261*Math.pow(Tc-T, 1.5);
double rhoL = rhoc + 0.477*Math.pow(Tc-T,1.0/3.0) + 0.2124*(Tc-T) - 0.01151*Math.pow(Tc-T, 1.5);
double xL = 1.0/(1.0 + Math.pow(rhoL/rhoV,1.0/3.0));
// V = NV/rhoV + NL/rhoL
// rho = 0.75 rhoV + 0.25 rhoL
double rho = (1-xL)*rhoV + xL*rhoL;
double V = numAtoms / rho;
// Lx * Lyz * Lyz = V
// Lx = Lyz * 4
// 4 * Lyz^3 = V
// Lyz = (V/4)^(1/3)
double Lyz = Math.pow(V/aspectRatio, 1.0/3.0);
if (Lyz < 2*rc) {
throw new RuntimeException("cutoff("+rc+") too large for box size ("+Lyz+")");
}
double Lx = Lyz*aspectRatio;
mcMoveAtom.setXRange(-0.6*Lx*xL, 0.6*Lx*xL, 5);
mcMoveAtomBigStep.setXRange(0.4*Lx*xL, -0.4*Lx*xL, 50);
mcMoveAtomBigStep.setStepSize(6);
mcMoveAtomBigStep.setStepSizeMin(5);
((MCMoveStepTracker)mcMoveAtomBigStep.getTracker()).setAcceptanceTarget(0.2);
// ((MCMoveStepTracker)mcMoveAtom.getTracker()).setNoisyAdjustment(true);
// ((MCMoveStepTracker)mcMoveAtomBigStep.getTracker()).setNoisyAdjustment(true);
//initialize box to just liquid size, put atoms on FCC lattice
int nL = (int)((Lx*xL*Lyz*Lyz)*rhoL);
box.setNMolecules(species, nL);
box.getBoundary().setBoxSize(space.makeVector(new double[]{Lx*xL,Lyz,Lyz}));
new ConfigurationLattice(new LatticeCubicFcc(space), space).initializeCoordinates(box);
// then expand box size
Box boxV = new Box(space);
addBox(boxV);
boxV.setNMolecules(species, numAtoms-nL);
boxV.getBoundary().setBoxSize(space.makeVector(new double[]{Lx*(1-xL),Lyz,Lyz}));
new ConfigurationLattice(new LatticeCubicFcc(space), space).initializeCoordinates(boxV);
box.setNMolecules(species, numAtoms);
IAtomList atoms = box.getLeafList();
for (int i=0; i<numAtoms-nL; i++) {
IVector vx = boxV.getLeafList().getAtom(i).getPosition();
IVectorMutable x = atoms.getAtom(nL+i).getPosition();
x.E(vx);
if (vx.getX(0) > 0) {
x.setX(0, vx.getX(0) + 0.5*Lx*xL);
}
else {
x.setX(0, vx.getX(0) - 0.5*Lx*xL);
}
}
box.getBoundary().setBoxSize(space.makeVector(new double[]{Lx,Lyz,Lyz}));
integrator.getMoveEventManager().addListener(potentialMaster.getNbrCellManager(box).makeMCMoveListener());
}
public static void main(String[] args) {
LJMCParams params = new LJMCParams();
if (args.length > 0) {
ParseArgs.doParseArgs(params, args);
}
else {
}
ISpace space = Space3D.getInstance();
int numAtoms = params.numAtoms;
double temperature = params.temperature;
double aspectRatio = params.aspectRatio;
final LJMC sim = new LJMC(space, numAtoms, temperature, aspectRatio);
MeterPressureTensor meterPTensor = new MeterPressureTensor(sim.potentialMaster, space);
meterPTensor.setBox(sim.box);
meterPTensor.setTemperature(temperature);
if (true) {
SimulationGraphic ljmcGraphic = new SimulationGraphic(sim, SimulationGraphic.TABBED_PANE, space, sim.getController());
SimulationGraphic.makeAndDisplayFrame(ljmcGraphic.getPanel(), "LJ surface tension");
IAction recenterAction = new ActionRecenter(sim);
IntegratorListenerAction recenterActionListener = new IntegratorListenerAction(recenterAction);
sim.integrator.getEventManager().addListener(recenterActionListener);
recenterActionListener.setInterval(100);
List<DataPump> dataStreamPumps = ljmcGraphic.getController().getDataStreamPumps();
MeterProfileByVolume densityProfileMeter = new MeterProfileByVolume(space);
densityProfileMeter.setBox(sim.box);
densityProfileMeter.getXDataSource().setNValues(400);
MeterNMolecules meterNMolecules = new MeterNMolecules();
meterNMolecules.setSpecies(sim.species);
densityProfileMeter.setDataSource(meterNMolecules);
DataFork profileFork = new DataFork();
AccumulatorAverageFixed densityProfileAvg = new AccumulatorAverageFixed(10);
densityProfileAvg.setPushInterval(10);
DataPump profilePump = new DataPump(densityProfileMeter, profileFork);
profileFork.addDataSink(densityProfileAvg);
DataDump profileDump = new DataDump();
densityProfileAvg.addDataSink(profileDump, new AccumulatorAverage.StatType[]{densityProfileAvg.AVERAGE});
IntegratorListenerAction profilePumpListener = new IntegratorListenerAction(profilePump);
sim.integrator.getEventManager().addListener(profilePumpListener);
profilePumpListener.setInterval(numAtoms);
dataStreamPumps.add(profilePump);
final FitTanh fitTanh = new FitTanh();
densityProfileAvg.addDataSink(fitTanh, new AccumulatorAverage.StatType[]{densityProfileAvg.AVERAGE});
DisplayPlot profilePlot = new DisplayPlot();
densityProfileAvg.addDataSink(profilePlot.getDataSet().makeDataSink(), new AccumulatorAverage.StatType[]{densityProfileAvg.AVERAGE});
fitTanh.setDataSink(profilePlot.getDataSet().makeDataSink());
profilePlot.setLegend(new DataTag[]{densityProfileAvg.getTag()}, "density");
profilePlot.setLegend(new DataTag[]{densityProfileAvg.getTag(), fitTanh.getTag()}, "fit");
profilePlot.setDoLegend(true);
profilePlot.setLabel("Density");
ljmcGraphic.add(profilePlot);
final FitTanh fitTanh0 = new FitTanh();
profileFork.addDataSink(fitTanh0);
DisplayPlot profile0Plot = new DisplayPlot();
profileFork.addDataSink(profile0Plot.getDataSet().makeDataSink());
fitTanh0.setDataSink(profile0Plot.getDataSet().makeDataSink());
profile0Plot.setLegend(new DataTag[]{densityProfileMeter.getTag()}, "density");
profile0Plot.setLegend(new DataTag[]{fitTanh0.getTag()}, "fit");
profile0Plot.setDoLegend(true);
profile0Plot.setLabel("Density0");
ljmcGraphic.add(profile0Plot);
DataProcessor surfaceTension = new DataProcessorSurfaceTension();
DataPumpListener tensionPump = new DataPumpListener(meterPTensor, surfaceTension, numAtoms);
DataFork tensionFork = new DataFork();
surfaceTension.setDataSink(tensionFork);
AccumulatorAverageCollapsing surfaceTensionAvg = new AccumulatorAverageCollapsing();
tensionFork.addDataSink(surfaceTensionAvg);
DisplayTextBoxesCAE tensionBox = new DisplayTextBoxesCAE();
tensionBox.setAccumulator(surfaceTensionAvg);
tensionBox.setLabel("Surface Tension");
tensionBox.setPrecision(4);
dataStreamPumps.add(tensionPump);
sim.integrator.getEventManager().addListener(tensionPump);
ljmcGraphic.add(tensionBox);
SurfaceTensionMapped stMap = new SurfaceTensionMapped(space, sim.box, sim.species, sim.potentialMaster);
tensionFork.addDataSink(stMap);
DataFork mappedFork = new DataFork();
stMap.setDataSink(mappedFork);
AccumulatorAverageCollapsing surfaceTensionMappedAvg = new AccumulatorAverageCollapsing();
mappedFork.addDataSink(surfaceTensionMappedAvg);
DisplayTextBoxesCAE mappedTensionBox = new DisplayTextBoxesCAE();
mappedTensionBox.setAccumulator(surfaceTensionMappedAvg);
mappedTensionBox.setLabel("Mapped Surface Tension");
mappedTensionBox.setPrecision(4);
ljmcGraphic.add(mappedTensionBox);
AccumulatorHistory stHistory = new AccumulatorHistory(new HistoryCollapsingAverage());
DataSourceCountSteps stepCounter = new DataSourceCountSteps(sim.integrator);
stHistory.setTimeDataSource(stepCounter);
tensionFork.addDataSink(stHistory);
AccumulatorHistory stMappedHistory = new AccumulatorHistory(new HistoryCollapsingAverage());
stMappedHistory.setTimeDataSource(stepCounter);
mappedFork.addDataSink(stMappedHistory);
DisplayPlot stPlot = new DisplayPlot();
stHistory.setDataSink(stPlot.getDataSet().makeDataSink());
stPlot.setLegend(new DataTag[]{stHistory.getTag()}, "conv");
stMappedHistory.setDataSink(stPlot.getDataSet().makeDataSink());
stPlot.setLegend(new DataTag[]{stMappedHistory.getTag()}, "mapped");
stPlot.setLabel("History");
ljmcGraphic.add(stPlot);
return;
}
sim.getController().actionPerformed();
}
public static class LJMCParams extends ParameterBase {
public int numAtoms = 1000;
public double temperature = 1.1;
public double aspectRatio = 6;
}
}
|
package org.nakedobjects.utility;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public abstract class Logger {
private String fileName;
private DateFormat format;
private boolean logAlso;
private org.apache.log4j.Logger logger;
private boolean showTime;
private final long start;
private PrintStream stream;
public Logger() {
start = time();
logAlso = true;
showTime = true;
format = new SimpleDateFormat("yyyyMMdd-hhmm-ss.SSS");
}
public Logger(final String fileName, boolean logAlso) {
this();
this.fileName = fileName;
this.logAlso = logAlso;
}
public void close() {
if (stream != null) {
stream.close();
}
}
protected abstract Class getDecoratedClass();
public boolean isLogToFile() {
return fileName != null;
}
public boolean isLogToLog4j() {
return logAlso;
}
public void log(String message) {
if (logAlso) {
logger().info(message);
}
if (fileName != null) {
if (stream == null) {
try {
if (fileName == null) {
return;
}
stream = new PrintStream(new FileOutputStream(fileName));
} catch (IOException e) {
e.printStackTrace();
}
}
if (showTime) {
stream.print(format.format(new Date(time())));
} else {
stream.print(time() - start);
}
stream.print(" ");
stream.println(message);
stream.flush();
}
}
public void log(String request, Object result) {
log(request + " -> " + result);
}
private org.apache.log4j.Logger logger() {
if (logger == null) {
logger = org.apache.log4j.Logger.getLogger(getDecoratedClass());
}
return logger;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public void setLogAlso(boolean logAlso) {
this.logAlso = logAlso;
}
public void setShowTime(boolean showTime) {
this.showTime = showTime;
}
public void setTimeFormat(String format) {
this.format = new SimpleDateFormat(format);
}
private long time() {
return System.currentTimeMillis();
}
}
|
package dynamake.models;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import dynamake.commands.CommandState;
import dynamake.commands.MappableForwardable;
import dynamake.commands.PendingCommandState;
import dynamake.commands.SetPropertyCommand;
import dynamake.models.Model.PendingUndoablePair;
import dynamake.transcription.Collector;
import dynamake.transcription.SimpleExPendingCommandFactory;
import dynamake.transcription.Trigger;
public class RestorableModel implements Serializable {
private static final long serialVersionUID = 1L;
public static String PROPERTY_ORIGINS = "Origins";
public static String PROPERTY_CREATION = "Creation";
public static String PROPERTY_CLEANUP = "Cleanup";
protected byte[] modelBaseSerialization;
// Origins must guarantee to not require mapping to new references
protected List<CommandState<Model>> modelOrigins;
protected List<CommandState<Model>> modelCreation;
protected MappableForwardable modelHistory;
protected List<CommandState<Model>> modelCleanup;
public static RestorableModel wrap(Model model, boolean includeLocalHistory) {
RestorableModel wrapper = new RestorableModel();
wrap(wrapper, model, includeLocalHistory);
return wrapper;
}
protected static void wrap(RestorableModel wrapper, Model model, boolean includeLocalHistory) {
MappableForwardable modelHistory = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream out = new ObjectOutputStream(bos);
Model modelBase = model.cloneBase();
if(includeLocalHistory)
modelHistory = model.cloneHistory(includeLocalHistory);
out.writeObject(modelBase);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
byte[] modelBaseSerialization = bos.toByteArray();
@SuppressWarnings("unchecked")
List<CommandState<Model>> modelOrigins = new ArrayList<CommandState<Model>>((List<CommandState<Model>>)model.getProperty(RestorableModel.PROPERTY_ORIGINS));
@SuppressWarnings("unchecked")
List<CommandState<Model>> modelCreation1 = (List<CommandState<Model>>)model.getProperty(RestorableModel.PROPERTY_CREATION);
List<CommandState<Model>> modelCreation = modelCreation1 != null ? new ArrayList<CommandState<Model>>(modelCreation1) : null;
@SuppressWarnings("unchecked")
List<CommandState<Model>> modelCleanup1 = (List<CommandState<Model>>)model.getProperty(RestorableModel.PROPERTY_CLEANUP);
List<CommandState<Model>> modelCleanup = modelCleanup1 != null ? new ArrayList<CommandState<Model>>(modelCleanup1) : null;
wrapper.modelBaseSerialization = modelBaseSerialization;
wrapper.modelOrigins = modelOrigins;
wrapper.modelCreation = modelCreation;
wrapper.modelHistory = modelHistory;
wrapper.modelCleanup = modelCleanup;
}
protected RestorableModel(byte[] modelBaseSerialization, List<CommandState<Model>> modelOrigins, List<CommandState<Model>> modelCreation, MappableForwardable modelHistory, List<CommandState<Model>> modelCleanup) {
this.modelBaseSerialization = modelBaseSerialization;
this.modelOrigins = modelOrigins;
this.modelCreation = modelCreation;
this.modelHistory = modelHistory;
this.modelCleanup = modelCleanup;
}
protected RestorableModel(byte[] modelBaseSerialization, List<CommandState<Model>> modelOrigins) {
this.modelBaseSerialization = modelBaseSerialization;
this.modelOrigins = modelOrigins;
}
protected RestorableModel() { }
public RestorableModel mapToReferenceLocation(Model sourceReference, Model targetReference) {
RestorableModel mapped = createRestorableModel(modelBaseSerialization, modelOrigins);
mapToReferenceLocation(mapped, sourceReference, targetReference);
return mapped;
}
protected void mapToReferenceLocation(RestorableModel mapped, Model sourceReference, Model targetReference) {
if(modelCreation != null) {
mapped.modelCreation = new ArrayList<CommandState<Model>>();
for(CommandState<Model> modelCreationPart: modelCreation) {
CommandState<Model> newModelCreationPart = modelCreationPart.mapToReferenceLocation(sourceReference, targetReference);
mapped.modelCreation.add(newModelCreationPart);
}
}
if(modelHistory != null)
mapped.modelHistory = modelHistory.mapToReferenceLocation(sourceReference, targetReference);
if(modelCleanup != null) {
mapped.modelCleanup = new ArrayList<CommandState<Model>>();
for(CommandState<Model> mc: modelCleanup) {
CommandState<Model> newModelCleanup = mc.mapToReferenceLocation(sourceReference, targetReference);
mapped.modelCleanup.add(newModelCleanup);
}
}
afterMapToReferenceLocation(mapped, sourceReference, targetReference);
}
public RestorableModel forForwarding() {
RestorableModel mapped = createRestorableModel(modelBaseSerialization, modelOrigins);
forForwarding(mapped);
return mapped;
}
protected void forForwarding(RestorableModel mapped) {
if(modelCreation != null) {
mapped.modelCreation = new ArrayList<CommandState<Model>>();
for(CommandState<Model> modelCreationPart: modelCreation) {
CommandState<Model> newModelCreationPart = modelCreationPart.forForwarding();
mapped.modelCreation.add(newModelCreationPart);
}
}
if(modelHistory != null)
mapped.modelHistory = modelHistory.forForwarding();
if(modelCleanup != null) {
mapped.modelCleanup = new ArrayList<CommandState<Model>>();
for(CommandState<Model> mc: modelCleanup) {
CommandState<Model> newModelCleanup = mc.forForwarding();
mapped.modelCleanup.add(newModelCleanup);
}
}
afterForForwarding(mapped);
}
protected RestorableModel createRestorableModel(byte[] modelBaseSerialization, List<CommandState<Model>> modelOrigins) {
return new RestorableModel(modelBaseSerialization, modelOrigins);
}
public Model unwrapBase(PropogationContext propCtx, int propDistance, Collector<Model> collector) {
Model modelBase = null;
ByteArrayInputStream bis = new ByteArrayInputStream(modelBaseSerialization);
ObjectInputStream in;
try {
in = new ObjectInputStream(bis);
modelBase = (Model) in.readObject();
in.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return modelBase;
}
public void restoreOriginsOnBase(Model modelBase, PropogationContext propCtx, int propDistance, Collector<Model> collector) {
modelBase.playThenReverse(modelOrigins, propCtx, propDistance, collector);
modelBase.setProperty(RestorableModel.PROPERTY_ORIGINS, modelOrigins, propCtx, propDistance, collector);
}
public void restoreChangesOnBase(final Model modelBase, final PropogationContext propCtx, final int propDistance, Collector<Model> collector) {
ArrayList<CommandState<Model>> modelCreationAsPendingCommands = new ArrayList<CommandState<Model>>();
if(modelCreation != null) {
for(CommandState<Model> modelCreationPart: modelCreation) {
modelCreationAsPendingCommands.add(((Model.PendingUndoablePair)modelCreationPart).pending);
}
}
modelCreationAsPendingCommands.addAll(appendedCreation);
// if(modelCreationAsPendingCommands.size() > 0) {
// collector.execute(new SimpleExPendingCommandFactory2<Model>(modelBase, modelCreationAsPendingCommands) {
// @Override
// public void afterPropogationFinished(List<PendingUndoablePair> pendingUndoablePairs, PropogationContext propCtx, int propDistance, Collector<Model> collector) {
// collector.execute(new SimpleExPendingCommandFactory2<Model>(modelBase, new PendingCommandState<Model>(
// new SetPropertyCommand(RestorableModel.PROPERTY_CREATION, pendingUndoablePairs),
// new SetPropertyCommand.AfterSetProperty()
restoreChanges(modelBase, collector, modelCreationAsPendingCommands, 0, new ArrayList<PendingUndoablePair>());
if(modelHistory != null)
modelBase.restoreHistory(modelHistory, propCtx, propDistance, collector);
collector.execute(new Trigger<Model>() {
@Override
public void run(Collector<Model> collector) {
afterRestoreChangesOnBase(modelBase, propCtx, propDistance, collector);
}
});
}
private void restoreChanges(final Model modelBase, Collector<Model> collector, final List<CommandState<Model>> modelCreation, final int i, final List<PendingUndoablePair> allPendingUndoablePairs) {
// Execute one command at a time to leave space for side effect in between
if(i < modelCreation.size()) {
collector.execute(new SimpleExPendingCommandFactory<Model>(modelBase, modelCreation.subList(i, i + 1)) {
@Override
public void afterPropogationFinished(List<PendingUndoablePair> pendingUndoablePairs, PropogationContext propCtx, int propDistance, Collector<Model> collector) {
allPendingUndoablePairs.addAll(pendingUndoablePairs);
restoreChanges(modelBase, collector, modelCreation, i + 1, allPendingUndoablePairs);
}
});
} else {
collector.execute(new SimpleExPendingCommandFactory<Model>(modelBase, new PendingCommandState<Model>(
new SetPropertyCommand(RestorableModel.PROPERTY_CREATION, allPendingUndoablePairs),
new SetPropertyCommand.AfterSetProperty()
)));
}
}
protected void afterMapToReferenceLocation(RestorableModel mapped, Model sourceReference, Model targetReference) { }
protected void afterForForwarding(RestorableModel forForwarded) { }
protected void afterRestoreChangesOnBase(final Model modelBase, PropogationContext propCtx, int propDistance, Collector<Model> collector) { }
protected void afterRestoreCleanupOnBase(final Model modelBase, PropogationContext propCtx, int propDistance, Collector<Model> collector) { }
public Model unwrap(PropogationContext propCtx, int propDistance, Collector<Model> collector) {
Model modelBase = unwrapBase(propCtx, propDistance, collector);
restoreOriginsOnBase(modelBase, propCtx, propDistance, collector);
restoreChangesOnBase(modelBase, propCtx, propDistance, collector);
return modelBase;
}
private ArrayList<CommandState<Model>> appendedCreation = new ArrayList<CommandState<Model>>();
public void appendCreation(CommandState<Model> creationPartToAppend) {
appendedCreation.add(creationPartToAppend);
}
public void clearCreation() {
if(modelCreation != null)
modelCreation.clear();
}
}
|
package org.iatrix.views;
import static ch.elexis.core.data.events.ElexisEvent.EVENT_DELETE;
import static ch.elexis.core.data.events.ElexisEvent.EVENT_DESELECTED;
import static ch.elexis.core.data.events.ElexisEvent.EVENT_SELECTED;
import static ch.elexis.core.data.events.ElexisEvent.EVENT_UPDATE;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableColorProvider;
import org.eclipse.jface.viewers.ITableFontProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceAdapter;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.ISaveablePart2;
import org.eclipse.ui.contexts.IContextService;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Hyperlink;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.iatrix.Iatrix;
import org.iatrix.actions.IatrixEventHelper;
import org.iatrix.data.KonsTextLock;
import org.iatrix.data.Problem;
import org.iatrix.dialogs.ChooseKonsRevisionDialog;
import org.iatrix.widgets.KonsListDisplay;
import ch.elexis.admin.AccessControlDefaults;
import ch.elexis.core.data.activator.CoreHub;
import ch.elexis.core.data.events.ElexisEvent;
import ch.elexis.core.data.events.ElexisEventDispatcher;
import ch.elexis.core.data.events.Heartbeat.HeartListener;
import ch.elexis.core.data.interfaces.IDiagnose;
import ch.elexis.core.data.interfaces.IVerrechenbar;
import ch.elexis.core.data.util.Extensions;
import ch.elexis.core.model.ISticker;
import ch.elexis.core.text.model.Samdas;
import ch.elexis.core.ui.UiDesk;
import ch.elexis.core.ui.actions.CodeSelectorHandler;
import ch.elexis.core.ui.actions.GlobalActions;
import ch.elexis.core.ui.actions.GlobalEventDispatcher;
import ch.elexis.core.ui.actions.IActivationListener;
import ch.elexis.core.ui.actions.ICodeSelectorTarget;
import ch.elexis.core.ui.constants.ExtensionPointConstantsUi;
import ch.elexis.core.ui.contacts.views.PatientDetailView2;
import ch.elexis.core.ui.data.UiSticker;
import ch.elexis.core.ui.dialogs.KontaktSelektor;
import ch.elexis.core.ui.dialogs.MediDetailDialog;
import ch.elexis.core.ui.events.ElexisUiEventListenerImpl;
import ch.elexis.core.ui.icons.Images;
import ch.elexis.core.ui.text.EnhancedTextField;
import ch.elexis.core.ui.util.IKonsExtension;
import ch.elexis.core.ui.util.Log;
import ch.elexis.core.ui.util.SWTHelper;
import ch.elexis.core.ui.util.ViewMenus;
import ch.elexis.core.ui.views.codesystems.DiagnosenView;
import ch.elexis.core.ui.views.codesystems.LeistungenView;
import ch.elexis.core.ui.views.rechnung.AccountView;
import ch.elexis.core.ui.views.rechnung.BillSummary;
import ch.elexis.data.Anschrift;
import ch.elexis.data.Anwender;
import ch.elexis.data.Artikel;
import ch.elexis.data.Fall;
import ch.elexis.data.Konsultation;
import ch.elexis.data.Mandant;
import ch.elexis.data.Patient;
import ch.elexis.data.PersistentObject;
import ch.elexis.data.PersistentObjectFactory;
import ch.elexis.data.Prescription;
import ch.elexis.data.Query;
import ch.elexis.data.Rechnung;
import ch.elexis.data.Rechnungssteller;
import ch.elexis.data.RnStatus;
import ch.elexis.data.Sticker;
import ch.elexis.data.Verrechnet;
import ch.elexis.extdoc.util.Email;
import ch.elexis.icpc.Encounter;
import ch.elexis.icpc.Episode;
import ch.rgw.tools.ExHandler;
import ch.rgw.tools.Money;
import ch.rgw.tools.Result;
import ch.rgw.tools.StringTool;
import ch.rgw.tools.TimeTool;
import ch.rgw.tools.VersionedResource;
import ch.rgw.tools.VersionedResource.ResourceItem;
import de.kupzog.ktable.KTable;
import de.kupzog.ktable.KTableCellDoubleClickListener;
import de.kupzog.ktable.KTableCellEditor;
import de.kupzog.ktable.KTableCellRenderer;
import de.kupzog.ktable.KTableCellSelectionListener;
import de.kupzog.ktable.KTableModel;
import de.kupzog.ktable.SWTX;
import de.kupzog.ktable.renderers.FixedCellRenderer;
/**
* KG-Ansicht nach Iatrix-Vorstellungen
*
* Oben wird die Problemliste dargestellt, unten die aktuelle Konsultation und die bisherigen
* Konsultationen. Hinweis: Es wird sichergestellt, dass die Problemliste und die Konsultation(en)
* zum gleichen Patienten gehoeren.
*
* TODO Definieren, wann welcher Patient und welche Konsultation gesetzt werden soll. Wie mit
* Faellen umgehen? TODO adatpMenu as in KonsDetailView TODO check compatibility of assigned
* problems if fall is changed
*
* @author Daniel Lutz <danlutz@watz.ch>
*/
public class JournalView extends ViewPart implements IActivationListener, ISaveablePart2,
HeartListener {
public static final String ID = "org.iatrix.views.JournalView"; //$NON-NLS-1$
private static final String VIEW_CONTEXT_ID = "org.iatrix.view.context"; //$NON-NLS-1$
private static final String NEWCONS_COMMAND = "org.iatrix.commands.newcons"; //$NON-NLS-1$
private static final String NEWPROBLEM_COMMAND = "org.iatrix.commands.newproblem"; //$NON-NLS-1$
private static final String EXPORT_CLIPBOARD_COMMAND = "org.iatrix.commands.export_clipboard"; //$NON-NLS-1$
private static final String EXPORT_SEND_EMAIL_COMMAND = "org.iatrix.commands.send_email"; //$NON-NLS-1$
// org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds.SAVE
private static final String SAVE_COMMAND = "org.eclipse.ui.file.save";
private static final String UNKNOWN = "(unbekannt)";
private static final DateComparator DATE_COMPARATOR = new DateComparator();
private static final NumberComparator NUMBER_COMPARATOR = new NumberComparator();
private static final StatusComparator STATUS_COMPARATOR = new StatusComparator();
static Log log = Log.get(JournalView.class.getSimpleName());
private Patient actPatient = null;
private Konsultation actKons;
private static boolean creatingKons = false;
private static String savedInitialKonsText = null;
private Hashtable<String, IKonsExtension> hXrefs;
private final DecimalFormat df = new DecimalFormat("0.00");
private EnhancedTextField text;
/*
* private Label lKonsultation;
*/
private Hyperlink hlKonsultationDatum;
private Hyperlink hlMandant;
private Label lVersion;
private Label lKonsLock;
private Combo cbFall;
// container for hKonsultationDatum, hlMandant, cbFall
private Composite konsFallArea;
private FormToolkit tk;
private Form form;
private Hyperlink formTitel;
private Label remarkLabel;
private Label stickerLabel;
private Image sticker;
private Label kontoLabel;
private Color kontoLabelColor; // original color of kontoLabel
// private Label lProbleme;
private Hyperlink hVerrechnung;
private Text tVerrechnungKuerzel;
private Action versionBackAction;
private Action purgeAction;
private Action versionFwdAction;
private Action chooseVersionAction;
private Action saveAction;
int displayedVersion;
private MyKTable problemsKTable;
private ProblemsTableModel problemsTableModel;
private ProblemsTableColorProvider problemsTableColorProvider;
// column indices
private static final int DATUM = 0;
private static final int NUMMER = 1;
private static final int BEZEICHNUNG = 2;
private static final int THERAPIE = 3;
private static final int DIAGNOSEN = 4;
/*
* private static final int GESETZ = 5; private static final int STATUS = 6;
*/
private static final int STATUS = 5;
private static final String[] COLUMN_TEXT = {
"Datum", // DATUM
"Nr.", // NUMMER
"Problem/Diagnose", // BEZEICHNUNG
"Proc./Medic.", // THERAPIE
"Code", // DIAGNOSEN
/*
* "Fall", // GESETZ
*/
""
};
private static final String[] TOOLTIP_TEXT = {
"Was soll niklaus hier schreiben (row 0)",
"Datum/Dauer des Ereignis, z.B. 2013-12-30, 1999-11, 1988, 1988-2010", // DATUM
"Nummer des Ereignis", // NUMMER
"Geschildertes Problem, Diagnose", // BEZEICHNUNG
"Therapie, Medikation", // THERAPIE
"Was soll niklaus hier schreiben (row 5)", "Was soll niklaus hier schreiben (row 6)",
"Was soll niklaus hier schreiben (row 7)",
};
private static final int[] DEFAULT_COLUMN_WIDTH = {
80, // DATUM
30, // NUMMER
120, // BEZEICHNUNG
120, // THERAPIE
80, // DIAGNOSEN
/*
* 40, // GESETZ
*/
20
// STATUS
};
private static final String CFG_BASE_KEY = "org.iatrix/views/journalview/column_width";
private static final String[] COLUMN_CFG_KEY = {
CFG_BASE_KEY + "/" + "date", // DATUM
CFG_BASE_KEY + "/" + "number", // NUMMER
CFG_BASE_KEY + "/" + "description", // BEZEICHNUNG
CFG_BASE_KEY + "/" + "therapy", // THERAPIE
CFG_BASE_KEY + "/" + "diagnoses", // DIAGNOSEN
/*
* CFG_BASE_KEY + "/" + "law", // GESETZ
*/
CFG_BASE_KEY + "/" + "status", // STATUS
};
private CheckboxTableViewer problemAssignmentViewer;
private TableViewer verrechnungViewer;
private Color verrechnungViewerColor; // original color of verrechnungViewer
private CLabel lDiagnosis;
// HistoryDisplay history;
KonsListDisplay konsListDisplay;
private Action showAllChargesAction;
private Action showAllConsultationsAction;
private ViewMenus menus;
/* Actions */
private IAction exportToClipboardAction;
private IAction sendEmailAction;
/* Konsultation */
private IAction addKonsultationAction;
/* problemsTableViewer */
private IAction addProblemAction;
private IAction delProblemAction;
private IAction addFixmedikationAction;
private IAction editFixmedikationAction;
private IAction deleteFixmedikationAction;
/* problemAssignmentViewer */
private IAction unassignProblemAction;
/* verrechnungViewer */
private IAction delVerrechnetAction;
private IAction changeVerrechnetPreisAction;
private IAction changeVerrechnetZahlAction;
private ICodeSelectorTarget problemDiagnosesCodeSelectorTarget;
private ICodeSelectorTarget problemFixmedikationCodeSelectorTarget;
private ICodeSelectorTarget konsultationVerrechnungCodeSelectorTarget;
private Color normalColor;
private Color highlightColor;
/*
* Heartbeat activation management The heartbeat events are only processed if these variables
* are set to true. They may be set to false if heartbeat processing would distrub, e. g. in
* case of editing a problem or the consultation text.
*/
private boolean heartbeatProblemEnabled = true;
private boolean konsEditorHasFocus = false;
private KonsTextLock konsTextLock = null;
private boolean heartbeatActive = false;
private int konsTextSaverCount = 0;
/**
* Flag indicating if there are more than one mandants. This variable is initially set in
* createPartControl().
*/
private boolean hasMultipleMandants = false;
/**
* Initialize hasMultipleMandants variable
*/
private void initHasMultipleMandants(){
Query<Mandant> query = new Query<Mandant>(Mandant.class);
List<Mandant> list = query.execute();
if (list != null && list.size() > 1) {
hasMultipleMandants = true;
}
}
private final ElexisUiEventListenerImpl eeli_problem = new ElexisUiEventListenerImpl(
Episode.class, EVENT_UPDATE | EVENT_DESELECTED) {
@Override
public void runInUi(ElexisEvent ev){
switch (ev.getType()) {
case EVENT_UPDATE:
// problem change may affect current problems list and consultation
// TODO check if problem is part of current consultation
// work-around: just update the current patient and consultation
setPatient(actPatient);
updateKonsultation(!konsEditorHasFocus, false);
break;
case EVENT_DESELECTED:
problemsKTable.clearSelection();
break;
}
}
};
private final ElexisUiEventListenerImpl eeli_kons = new ElexisUiEventListenerImpl(
Konsultation.class, EVENT_DELETE | EVENT_UPDATE | EVENT_SELECTED | EVENT_DESELECTED) {
@Override
public void runInUi(ElexisEvent ev){
Konsultation k = (Konsultation) ev.getObject();
switch (ev.getType()) {
case EVENT_UPDATE:
if (actKons != null && k.getId().equals(actKons.getId())) {
updateKonsultation(!konsEditorHasFocus, false);
}
break;
case EVENT_DELETE:
if (actKons != null && k.getId().equals(actKons.getId())) {
setKonsultation(null, false);
}
break;
case EVENT_SELECTED:
Patient patient = k.getFall().getPatient();
setPatient(patient);
setKonsultation(k, true);
break;
case EVENT_DESELECTED:
setKonsultation(null, true);
break;
}
}
};
private final ElexisUiEventListenerImpl eeli_fall = new ElexisUiEventListenerImpl(Fall.class,
ElexisEvent.EVENT_SELECTED) {
@Override
public void runInUi(ElexisEvent ev){
Fall fall = (Fall) ev.getObject();
Patient patient = fall.getPatient();
// falls aktuell ausgewaehlte Konsulation zu diesem Fall
// gehoert,
// diese setzen
Konsultation konsulation =
(Konsultation) ElexisEventDispatcher.getSelected(Konsultation.class);
if (konsulation != null) {
if (konsulation.getFall().getId().equals(fall.getId())) {
// diese Konsulation gehoert zu diesem Patienten
setPatient(patient);
setKonsultation(konsulation, true);
return;
}
}
// sonst die aktuellste Konsulation des Falls setzen
konsulation = getTodaysLatestKons(fall);
setPatient(patient);
setKonsultation(konsulation, true);
}
};
private final ElexisUiEventListenerImpl eeli_pat =
new ElexisUiEventListenerImpl(Patient.class) {
@Override
public void runInUi(ElexisEvent ev){
if (ev.getType() == ElexisEvent.EVENT_SELECTED) {
Patient selectedPatient = (Patient) ev.getObject();
showAllChargesAction.setChecked(false);
showAllConsultationsAction.setChecked(false);
Patient patient = null;
Fall fall = null;
Konsultation konsultation = null;
konsultation =
(Konsultation) ElexisEventDispatcher.getSelected(Konsultation.class);
if (konsultation != null) {
// diese Konsulation setzen, falls sie zum ausgewaehlten
// Patienten gehoert
fall = konsultation.getFall();
patient = fall.getPatient();
if (patient.getId().equals(selectedPatient.getId())) {
setPatient(patient);
setKonsultation(konsultation, true);
return;
}
}
// Konsulation gehoert nicht zu diesem Patienten, Fall
// untersuchen
fall = (Fall) ElexisEventDispatcher.getSelected(Fall.class);
if (fall != null) {
patient = fall.getPatient();
if (patient.getId().equals(selectedPatient.getId())) {
// aktuellste Konsultation dieses Falls waehlen
konsultation = getTodaysLatestKons(fall);
setPatient(patient);
setKonsultation(konsultation, true);
return;
}
}
// weder aktuell ausgewaehlte Konsulation noch aktuell
// ausgewaehlter Fall gehoeren zu diesem Patienten
setPatient(selectedPatient);
// lezte Kons setzen, falls heutiges Datum
Konsultation letzteKons = getTodaysLatestKons(selectedPatient);
if (letzteKons != null) {
TimeTool letzteKonsDate = new TimeTool(letzteKons.getDatum());
TimeTool today = new TimeTool();
if (!letzteKonsDate.isSameDay(today)) {
letzteKons = null;
}
setKonsultation(letzteKons, true);
} else {
setKonsultation(null, true);
}
} else if (ev.getType() == ElexisEvent.EVENT_DESELECTED) {
setPatient(null);
}
}
};
private final ElexisUiEventListenerImpl eeli_user = new ElexisUiEventListenerImpl(
Anwender.class, ElexisEvent.EVENT_USER_CHANGED) {
@Override
public void runInUi(ElexisEvent ev){
adaptMenus();
}
};
@Override
public void createPartControl(Composite parent){
initHasMultipleMandants();
// ICodeSelectorTarget for diagnoses in problems list
problemDiagnosesCodeSelectorTarget = new ICodeSelectorTarget() {
@Override
public String getName(){
return JournalView.this.getPartName();
}
@Override
public void codeSelected(PersistentObject po){
if (po instanceof IDiagnose) {
IDiagnose diagnose = (IDiagnose) po;
Problem problem = getSelectedProblem();
if (problem != null) {
problem.addDiagnose(diagnose);
IatrixEventHelper.updateProblem(problem);
if (CoreHub.userCfg.get(Iatrix.CFG_CODE_SELECTION_AUTOCLOSE,
Iatrix.CFG_CODE_SELECTION_AUTOCLOSE_DEFAULT)) {
// re-activate this view
try {
getViewSite().getPage().showView(JournalView.ID);
} catch (Exception ex) {
ExHandler.handle(ex);
log.log("Fehler beim Öffnen von JournalView: " + ex.getMessage(),
Log.ERRORS);
}
}
}
}
}
@Override
public void registered(boolean registered){
highlightProblemsTable(registered);
}
};
// ICodeSelectorTarget for fixmedikation in problems list
problemFixmedikationCodeSelectorTarget = new ICodeSelectorTarget() {
@Override
public String getName(){
return JournalView.this.getPartName();
}
@Override
public void codeSelected(PersistentObject po){
Problem problem = getSelectedProblem();
if (problem != null) {
if (po instanceof Artikel) {
Artikel artikel = (Artikel) po;
Prescription prescription =
new Prescription(artikel, problem.getPatient(), "", "");
problem.addPrescription(prescription);
// Let the user set the Prescription properties
MediDetailDialog dlg =
new MediDetailDialog(getViewSite().getShell(), prescription);
dlg.open();
// tell other viewers that something has changed
IatrixEventHelper.updateProblem(problem);
if (CoreHub.userCfg.get(Iatrix.CFG_CODE_SELECTION_AUTOCLOSE,
Iatrix.CFG_CODE_SELECTION_AUTOCLOSE_DEFAULT)) {
// re-activate this view
try {
getViewSite().getPage().showView(JournalView.ID);
} catch (Exception ex) {
ExHandler.handle(ex);
log.log("Fehler beim Öffnen von JournalView: " + ex.getMessage(),
Log.ERRORS);
}
}
}
}
}
@Override
public void registered(boolean registered){
if (registered) {
highlightProblemsTable(true, true);
} else {
highlightProblemsTable(false);
}
}
};
// ICodeSelectorTarget for Verrechnung in consultation area
konsultationVerrechnungCodeSelectorTarget = new ICodeSelectorTarget() {
@Override
public String getName(){
return JournalView.this.getPartName();
}
@Override
public void codeSelected(PersistentObject po){
if (po instanceof IVerrechenbar) {
if (CoreHub.acl.request(AccessControlDefaults.LSTG_VERRECHNEN) == false) {
SWTHelper.alert("Fehlende Rechte",
"Sie haben nicht die Berechtigung, Leistungen zu verrechnen");
} else {
IVerrechenbar verrechenbar = (IVerrechenbar) po;
if (actKons != null) {
Result<IVerrechenbar> result = actKons.addLeistung(verrechenbar);
if (!result.isOK()) {
SWTHelper
.alert("Diese Verrechnung ist ungültig", result.toString());
} else {
if (CoreHub.userCfg.get(Iatrix.CFG_CODE_SELECTION_AUTOCLOSE,
Iatrix.CFG_CODE_SELECTION_AUTOCLOSE_DEFAULT)) {
// re-activate this view
try {
getViewSite().getPage().showView(JournalView.ID);
} catch (Exception ex) {
ExHandler.handle(ex);
log.log(
"Fehler beim Öffnen von JournalView: "
+ ex.getMessage(), Log.ERRORS);
}
}
}
verrechnungViewer.refresh();
updateVerrechnungSum();
}
}
}
}
@Override
public void registered(boolean registered){
highlightVerrechnung(registered);
}
};
parent.setLayout(new FillLayout());
tk = UiDesk.getToolkit();
form = tk.createForm(parent);
Composite formBody = form.getBody();
formBody.setLayout(new GridLayout(1, true));
// highlighting colors for ICodeSelectorTarget
normalColor = form.getBackground();
highlightColor = form.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND);
Composite formHeader = new Composite(formBody, SWT.NONE);
tk.adapt(formHeader);
formHeader.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false));
formHeader.setLayout(new GridLayout(3, false));
GridData gd;
formTitel = tk.createHyperlink(formHeader, "Iatrix KG", SWT.WRAP);
// set font
formTitel.setFont(JFaceResources.getHeaderFont());
formTitel.setText("Kein Patient ausgewählt");
formTitel.setEnabled(false);
formTitel.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e){
if (actPatient != null) {
try {
getViewSite().getPage().showView(PatientDetailView2.ID);
} catch (Exception ex) {
ExHandler.handle(ex);
log.log("Fehler beim Öffnen von PatientDetailView: " + ex.getMessage(),
Log.ERRORS);
}
}
}
});
Composite patInfoArea = tk.createComposite(formHeader);
gd = SWTHelper.getFillGridData(1, true, 1, false);
patInfoArea.setLayoutData(gd);
GridLayout infoLayout = new GridLayout(2, false);
// save space
infoLayout.horizontalSpacing = 5;
infoLayout.verticalSpacing = 0;
infoLayout.marginWidth = 0;
infoLayout.marginHeight = 0;
patInfoArea.setLayout(infoLayout);
remarkLabel = tk.createLabel(patInfoArea, "");
gd = new GridData(SWT.LEFT, SWT.TOP, false, false);
remarkLabel.setLayoutData(gd);
remarkLabel.setBackground(patInfoArea.getDisplay().getSystemColor(SWT.COLOR_YELLOW));
remarkLabel.setToolTipText("Bemerkung kann via Doppelclick geändert werden");
remarkLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseDoubleClick(MouseEvent e){
openRemarkEditorDialog();
}
});
stickerLabel = tk.createLabel(patInfoArea, "");
gd = SWTHelper.getFillGridData(1, true, 1, false);
sticker = Images.IMG_MANN.getImage();
stickerLabel.setImage(sticker);
stickerLabel.setLayoutData(gd);
stickerLabel.setToolTipText("Sticker des Patienten");
stickerLabel.setLayoutData(gd);
Composite kontoArea = tk.createComposite(formHeader);
gd = new GridData(SWT.END, SWT.CENTER, true, false);
kontoArea.setLayoutData(gd);
GridLayout gridLayout = new GridLayout(2, false);
// save space
gridLayout.horizontalSpacing = 5;
gridLayout.verticalSpacing = 0;
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
kontoArea.setLayout(gridLayout);
Hyperlink kontoHyperlink = tk.createHyperlink(kontoArea, "Kontostand:", SWT.NONE);
kontoHyperlink.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e){
if (actPatient != null) {
try {
getViewSite().getPage().showView(AccountView.ID);
} catch (Exception ex) {
ExHandler.handle(ex);
log.log("Fehler beim Öffnen von AccountView: " + ex.getMessage(),
Log.ERRORS);
}
}
}
});
kontoLabel = tk.createLabel(kontoArea, "", SWT.RIGHT);
gd = SWTHelper.getFillGridData(1, true, 1, false);
gd.verticalAlignment = GridData.END;
kontoLabel.setLayoutData(gd);
kontoLabelColor = kontoLabel.getForeground();
Hyperlink openBillsHyperlink =
tk.createHyperlink(kontoArea, "Rechnungsübersicht", SWT.NONE);
openBillsHyperlink.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e){
if (actPatient != null) {
try {
getViewSite().getPage().showView(BillSummary.ID);
} catch (Exception ex) {
ExHandler.handle(ex);
log.log("Fehler beim Öffnen von AccountView: " + ex.getMessage(),
Log.ERRORS);
}
}
}
});
openBillsHyperlink.setLayoutData(SWTHelper.getFillGridData(2, true, 1, false));
SashForm mainSash = new SashForm(form.getBody(), SWT.VERTICAL);
mainSash.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true));
Composite topArea = tk.createComposite(mainSash, SWT.NONE);
topArea.setLayout(new FillLayout(SWT.VERTICAL));
topArea.setBackground(topArea.getDisplay().getSystemColor(SWT.COLOR_WHITE));
createProblemsTable(topArea);
Composite middleArea = tk.createComposite(mainSash, SWT.NONE);
middleArea.setLayout(new FillLayout());
createKonsultationArea(middleArea);
Composite bottomArea = tk.createComposite(mainSash, SWT.NONE);
bottomArea.setLayout(new FillLayout());
bottomArea.setBackground(bottomArea.getDisplay().getSystemColor(SWT.COLOR_WHITE));
createHistory(bottomArea);
mainSash.setWeights(new int[] {
20, 40, 30
});
makeActions();
menus = new ViewMenus(getViewSite());
if (CoreHub.acl.request(AccessControlDefaults.AC_PURGE)) {
menus.createMenu(addKonsultationAction, GlobalActions.redateAction, addProblemAction,
GlobalActions.delKonsAction, delProblemAction, exportToClipboardAction,
sendEmailAction, versionFwdAction, versionBackAction, chooseVersionAction,
purgeAction, saveAction, showAllConsultationsAction, showAllChargesAction,
addFixmedikationAction);
} else {
menus.createMenu(addKonsultationAction, GlobalActions.redateAction, addProblemAction,
GlobalActions.delKonsAction, delProblemAction, exportToClipboardAction,
sendEmailAction, versionFwdAction, versionBackAction, chooseVersionAction,
saveAction, showAllConsultationsAction, showAllChargesAction,
addFixmedikationAction);
}
menus.createToolbar(sendEmailAction, exportToClipboardAction, addKonsultationAction,
addProblemAction, saveAction);
menus.createControlContextMenu(problemsKTable, addFixmedikationAction,
editFixmedikationAction, deleteFixmedikationAction);
menus.createViewerContextMenu(problemAssignmentViewer, unassignProblemAction);
menus.createViewerContextMenu(verrechnungViewer, changeVerrechnetPreisAction,
changeVerrechnetZahlAction, delVerrechnetAction);
GlobalEventDispatcher.addActivationListener(this, this);
activateContext();
}
/**
* Activate a context that this view uses. It will be tied to this view activation events and
* will be removed when the view is disposed. Copied from
* org.eclipse.ui.examples.contributions.InfoView.java
*/
private void activateContext(){
IContextService contextService =
(IContextService) getSite().getService(IContextService.class);
contextService.activateContext(VIEW_CONTEXT_ID);
}
private void createProblemsTable(Composite parent){
problemsKTable =
new MyKTable(parent, SWTX.MARK_FOCUS_HEADERS | SWTX.AUTO_SCROLL
| SWTX.FILL_WITH_DUMMYCOL | SWTX.EDIT_ON_KEY);
tk.adapt(problemsKTable);
problemsTableModel = new ProblemsTableModel();
problemsTableColorProvider = new ProblemsTableColorProvider();
problemsKTable.setModel(problemsTableModel);
// selections
problemsKTable.addCellSelectionListener(new KTableCellSelectionListener() {
@Override
public void cellSelected(int col, int row, int statemask){
int rowIndex = row - problemsTableModel.getFixedHeaderRowCount();
Problem problem = problemsTableModel.getProblem(rowIndex);
if (problem != null) {
IatrixEventHelper.fireSelectionEventProblem(problem);
} else {
IatrixEventHelper.clearSelectionProblem();
}
}
@Override
public void fixedCellSelected(int col, int row, int statemask){
problemsTableModel.setComparator(col, row);
problemsTableModel.reload();
problemsKTable.refresh();
}
});
// clear selection when ESC is pressed
problemsKTable.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e){
if (e.keyCode == SWT.ESC) {
problemsKTable.clearSelection();
// work-around: KTable doesn't redraw in single selection mode
problemsKTable.redraw();
IatrixEventHelper.clearSelectionProblem();
} else if ((e.character == ' ') || (e.character == '\r')) {
// Work-around for opening the diagnosis selector on ENTER
// or changing the status.
// KTable supports only cell editors based on a Control.
// So we just catch this event ourselves and assume that KTable
// hasn't processed it in KTable.onKeyDown().
if ((e.stateMask & SWT.CTRL) == 0) {
// plain SPACE or ENTER
// This is actually the same code as in the double click listener
Point[] selection = problemsKTable.getCellSelection();
if (selection.length == 1) {
int col = selection[0].x;
int row = selection[0].y;
int colIndex = col - problemsTableModel.getFixedHeaderColumnCount();
int rowIndex = row - problemsTableModel.getFixedHeaderRowCount();
Problem problem = problemsTableModel.getProblem(rowIndex);
switch (colIndex) {
case DIAGNOSEN:
// open diagnosis selector
if (problem != null) {
try {
getViewSite().getPage().showView(DiagnosenView.ID);
// register as ICodeSelectorTarget
CodeSelectorHandler.getInstance().setCodeSelectorTarget(
problemDiagnosesCodeSelectorTarget);
} catch (Exception ex) {
ExHandler.handle(ex);
log.log(
"Fehler beim Starten des Diagnosencodes "
+ ex.getMessage(), Log.ERRORS);
}
}
break;
case STATUS:
// change status when status field has been double clicked
if (problem != null) {
if (problem.getStatus() == Episode.ACTIVE) {
problem.setStatus(Episode.INACTIVE);
} else {
problem.setStatus(Episode.ACTIVE);
}
problemsKTable.refresh();
if (actKons != null) {
// only active problems are to be shown
problemAssignmentViewer.refresh();
}
}
break;
}
}
} else {
// SPACE or ENTER with CTRL
Point[] selection = problemsKTable.getCellSelection();
if (selection.length == 1) {
int col = selection[0].x;
int row = selection[0].y;
int colIndex = col - problemsTableModel.getFixedHeaderColumnCount();
switch (colIndex) {
case DIAGNOSEN:
KTableCellEditor editor =
problemsTableModel.getCellEditor(col, row);
if (editor != null
&& (editor.getActivationSignals() & KTableCellEditor.KEY_RETURN_AND_SPACE) != 0
&& editor.isApplicable(KTableCellEditor.KEY_RETURN_AND_SPACE,
problemsKTable, col, row, null, e.character + "",
e.stateMask)) {
problemsKTable.openEditorInFocus();
}
break;
}
}
}
}
}
});
problemsKTable.addCellDoubleClickListener(new KTableCellDoubleClickListener() {
@Override
public void cellDoubleClicked(int col, int row, int statemask){
int colIndex = col - problemsTableModel.getFixedHeaderColumnCount();
int rowIndex = row - problemsTableModel.getFixedHeaderRowCount();
Problem problem = problemsTableModel.getProblem(rowIndex);
switch (colIndex) {
case DIAGNOSEN:
// open diagnosis selector
if (problem != null) {
try {
getViewSite().getPage().showView(DiagnosenView.ID);
// register as ICodeSelectorTarget
CodeSelectorHandler.getInstance().setCodeSelectorTarget(
problemDiagnosesCodeSelectorTarget);
} catch (Exception ex) {
ExHandler.handle(ex);
log.log("Fehler beim Starten des Diagnosencodes " + ex.getMessage(),
Log.ERRORS);
}
}
break;
case STATUS:
// change status when status field has been double clicked
if (problem != null) {
if (problem.getStatus() == Episode.ACTIVE) {
problem.setStatus(Episode.INACTIVE);
} else {
problem.setStatus(Episode.ACTIVE);
}
problemsKTable.refresh();
if (actKons != null) {
// only active problems are to be shown
problemAssignmentViewer.refresh();
}
}
break;
}
}
@Override
public void fixedCellDoubleClicked(int col, int row, int statemask){
// nothing to do
}
});
/*
* Sortiert die Probleme nach Datum, aktuelle zuerst
*/
/*
* problemsTableDatumComparator = new ViewerComparator() { public int compare(Viewer viewer,
* Object e1, Object e2) { if (!(e1 instanceof Problem)) { return 1; } if (!(e2 instanceof
* Problem)) { return -1; }
*
* Problem p1 = (Problem) e1; Problem p2 = (Problem) e2;
*
* String datum1 = p1.getDatum(); String datum2 = p2.getDatum();
*
* if (datum1.equals(datum2)) { // datum ist identisch, nach Nummer sortieren
*
* String nummer1 = p1.getNummer(); String nummer2 = p2.getNummer();
*
* return nummer1.compareTo(nummer2); }
*
* return datum2.compareTo(datum1); } };
*
* problemsTableNummerComparator = new ViewerComparator() { public int compare(Viewer
* viewer, Object e1, Object e2) { if (!(e1 instanceof Problem)) { return 1; } if (!(e2
* instanceof Problem)) { return -1; }
*
* Problem p1 = (Problem) e1; Problem p2 = (Problem) e2;
*
* String nummer1 = p1.getNummer(); String nummer2 = p2.getNummer();
*
* return nummer1.compareTo(nummer2); } };
*
* problemsTableViewer.setComparator(problemsTableDatumComparator);
*/
/*
* Table table = problemsTableViewer.getTable(); table.setHeaderVisible(true);
* table.setLinesVisible(true);
*
* problemsTableViewer.setInput(this);
*
* TableColumn[] tc = new TableColumn[COLUMN_TEXT.length]; for (int i = 0; i <
* COLUMN_TEXT.length; i++) { tc[i] = new TableColumn(table, SWT.NONE);
* tc[i].setText(COLUMN_TEXT[i]); tc[i].setWidth(COLUMN_WIDTH[i]); }
*
* tc[DATUM].addSelectionListener(new SelectionAdapter() { public void
* widgetSelected(SelectionEvent event) {
* problemsTableViewer.setComparator(problemsTableDatumComparator); } });
*
* tc[NUMMER].addSelectionListener(new SelectionAdapter() { public void
* widgetSelected(SelectionEvent event) { problemsTableViewer
* .setComparator(problemsTableNummerComparator); } });
*/
/*
* CellEditor[] cellEditors = new CellEditor[7]; cellEditors[DATUM] = new
* TextCellEditor(table); cellEditors[NUMMER] = new TextCellEditor(table);
* cellEditors[BEZEICHNUNG] = new TextCellEditor(table); cellEditors[PROCEDERE] = new
* TextCellEditor(table);
*
* problemsTableViewer.setColumnProperties(PROPS); problemsTableViewer.setCellModifier(new
* ICellModifier() { public boolean canModify(Object element, String property) { if
* (property.equals(DATUM_PROP) || property.equals(NUMMER_PROP) ||
* property.equals(BEZEICHNUNG_PROP) || property.equals(PROCEDERE_PROP)) {
*
* return true; }
*
* return false; }
*
* public Object getValue(Object element, String property) { Problem problem = (Problem)
* element;
*
* if (property.equals(DATUM_PROP)) { return problem.getDatum(); } else if
* (property.equals(NUMMER_PROP)) { return problem.getNummer(); } else if
* (property.equals(BEZEICHNUNG_PROP)) { return problem.getBezeichnung(); } else if
* (property.equals(PROCEDERE_PROP)) { return problem.getProcedere(); } else { return null;
* } }
*
* public void modify(Object element, String property, Object value) { if (element
* instanceof Item) { element = ((Item) element).getData(); } Problem problem = (Problem)
* element;
*
* if (property.equals(DATUM_PROP)) { problem.setDatum((String) value); } else if
* (property.equals(NUMMER_PROP)) { problem.setNummer((String) value); } else if
* (property.equals(BEZEICHNUNG_PROP)) { problem.setBezeichnung((String) value); } else if
* (property.equals(PROCEDERE_PROP)) { problem.setProcedere((String) value); }
*
* problemsTableViewer.refresh(); refreshProblemAssignmentViewer(); } });
* problemsTableViewer.setCellEditors(cellEditors);
*/
// Drag'n'Drop support
// Quelle
DragSource ds = new DragSource(problemsKTable, DND.DROP_COPY);
ds.setTransfer(new Transfer[] {
TextTransfer.getInstance()
});
ds.addDragListener(new DragSourceAdapter() {
@Override
public void dragStart(DragSourceEvent event){
Point cell = problemsKTable.getCellForCoordinates(event.x, event.y);
int col = cell.x;
int row = cell.y;
// only handle normal columns/rows, no header columns/rows
if (col >= problemsTableModel.getFixedHeaderColumnCount()
&& row >= problemsTableModel.getFixedHeaderRowCount()) {
Problem problem = getSelectedProblem();
if (problem != null) {
event.doit = problem.isDragOK();
} else {
event.doit = false;
}
} else {
event.doit = false;
}
}
@Override
public void dragSetData(DragSourceEvent event){
// only add single selection
Problem problem = getSelectedProblem();
StringBuilder sb = new StringBuilder();
if (problem != null) {
sb.append(problem.storeToString()).append(",");
}
event.data = sb.toString().replace(",$", "");
}
});
// Ziel
DropTarget dt = new DropTarget(problemsKTable, DND.DROP_COPY);
dt.setTransfer(new Transfer[] {
TextTransfer.getInstance()
});
dt.addDropListener(new DropTargetListener() {
@Override
public void dragEnter(DropTargetEvent event){
/* Wir machen nur Copy-Operationen */
event.detail = DND.DROP_COPY;
}
@Override
public void dragLeave(DropTargetEvent event){
/* leer */
}
@Override
public void dragOperationChanged(DropTargetEvent event){
/* leer */
}
@Override
public void dragOver(DropTargetEvent event){
/* leer */
}
/* Erst das Loslassen interessiert uns wieder */
@Override
public void drop(DropTargetEvent event){
String drp = (String) event.data;
String[] dl = drp.split(",");
for (String obj : dl) {
PersistentObject dropped = CoreHub.poFactory.createFromString(obj);
// we don't yet support dropping to the problemsKTable
}
}
@Override
public void dropAccept(DropTargetEvent event){
/* leer */
}
});
}
private void createKonsultationArea(Composite parent){
// parent has FillLayout
Composite konsultationComposite = tk.createComposite(parent);
konsultationComposite.setLayout(new GridLayout(1, true));
konsFallArea = tk.createComposite(konsultationComposite);
konsFallArea.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false));
konsFallArea.setLayout(new GridLayout(3, false));
hlKonsultationDatum = tk.createHyperlink(konsFallArea, "", SWT.NONE);
hlKonsultationDatum.setFont(JFaceResources.getHeaderFont());
hlKonsultationDatum.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e){
GlobalActions.redateAction.run();
}
});
if (hasMultipleMandants) {
hlMandant = tk.createHyperlink(konsFallArea, "", SWT.NONE);
hlMandant.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e){
KontaktSelektor ksl =
new KontaktSelektor(getSite().getShell(), Mandant.class,
"Mandant auswählen", "Auf wen soll diese Kons verrechnet werden?",
new String[] {
Mandant.FLD_SHORT_LABEL, Mandant.FLD_NAME1, Mandant.FLD_NAME2
});
if (ksl.open() == Dialog.OK) {
actKons.setMandant((Mandant) ksl.getSelection());
updateKonsultation(true, false);
}
}
});
} else {
hlMandant = null;
// placeholder
tk.createLabel(konsFallArea, "");
}
Composite fallArea = tk.createComposite(konsFallArea);
// GridData gd = SWTHelper.getFillGridData(1, false, 1, false);
// gd.horizontalAlignment = SWT.RIGHT;
GridData gd = new GridData(SWT.RIGHT, SWT.TOP, true, false);
fallArea.setLayoutData(gd);
fallArea.setLayout(new GridLayout(2, false));
tk.createLabel(fallArea, "Fall:");
cbFall = new Combo(fallArea, SWT.SINGLE | SWT.READ_ONLY);
cbFall.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false));
cbFall.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e){
Fall[] faelle = (Fall[]) cbFall.getData();
int i = cbFall.getSelectionIndex();
Fall nFall = faelle[i];
Fall actFall = actKons.getFall();
if (!nFall.getId().equals(actFall.getId())) {
MessageDialog msd =
new MessageDialog(getViewSite().getShell(), "Fallzuordnung ändern",
Images.IMG_LOGO.getImage(), "Möchten Sie diese Behandlung vom Fall:\n'"
+ actFall.getLabel() + "' zum Fall:\n'" + nFall.getLabel()
+ "' transferieren?", MessageDialog.QUESTION, new String[] {
"Ja", "Nein"
}, 0);
if (msd.open() == 0) {
// TODO check compatibility of assigned problems
actKons.setFall(nFall);
updateKonsultation(true, false);
}
}
}
});
tk.adapt(cbFall);
cbFall.setEnabled(false);
SashForm konsultationSash = new SashForm(konsultationComposite, SWT.HORIZONTAL);
konsultationSash.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true));
Composite assignmentComposite = tk.createComposite(konsultationSash);
Composite konsultationTextComposite = tk.createComposite(konsultationSash);
Composite verrechnungComposite = tk.createComposite(konsultationSash);
konsultationSash.setWeights(new int[] {
15, 65, 20
});
assignmentComposite.setLayout(new GridLayout(1, true));
Label lProbleme = tk.createLabel(assignmentComposite, "Probleme", SWT.LEFT);
lProbleme.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false));
problemAssignmentViewer = CheckboxTableViewer.newCheckList(assignmentComposite, SWT.SINGLE);
Table problemAssignmentTable = problemAssignmentViewer.getTable();
tk.adapt(problemAssignmentTable);
problemAssignmentViewer.getControl().setLayoutData(
SWTHelper.getFillGridData(1, true, 1, true));
problemAssignmentViewer.setContentProvider(new IStructuredContentProvider() {
@Override
public Object[] getElements(Object inputElement){
/*
* if (actKons != null) { List<Problem> problems = Problem
* .getProblemsOfKonsultation(actKons); return problems.toArray(); } return new
* Problem[0];
*/
if (actKons != null) {
// get all problems of the current patient
List<Problem> patientProblems =
Problem.getProblemsOfPatient(actKons.getFall().getPatient());
List<Problem> konsProblems = Problem.getProblemsOfKonsultation(actKons);
// we only show active or assigned problems
List<Problem> problems = new ArrayList<Problem>();
// add active problems
for (Problem problem : patientProblems) {
if (problem.getStatus() == Episode.ACTIVE) {
problems.add(problem);
}
}
// add already assigned problems
for (Problem problem : konsProblems) {
if (!problems.contains(problem)) {
problems.add(problem);
}
}
// sort by date
Collections.sort(problems, DATE_COMPARATOR);
return problems.toArray();
}
return new Problem[] {};
}
@Override
public void dispose(){
// nothing to do
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput){
// nothing to do
}
});
problemAssignmentViewer.setLabelProvider(new ProblemAssignmentLabelProvider());
problemAssignmentViewer.addCheckStateListener(new ICheckStateListener() {
@Override
public void checkStateChanged(CheckStateChangedEvent event){
if (actKons == null) {
return;
}
Object element = event.getElement();
if (element instanceof Problem) {
Problem problem = (Problem) element;
if (event.getChecked()) {
problem.addToKonsultation(actKons);
} else {
// remove problem. ask user if encounter still contains data.
IatrixViewTool.removeProblemFromKonsultation(actKons, problem);
}
}
updateProblemAssignmentViewer();
setDiagnosenText(actKons);
}
});
problemAssignmentViewer.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event){
IStructuredSelection sel = (IStructuredSelection) event.getSelection();
if (sel != null) {
if (sel.size() == 1) {
Object obj = sel.getFirstElement();
if (obj instanceof Problem) {
Problem problem = (Problem) obj;
IatrixEventHelper.fireSelectionEventProblem(problem);
// select corresponding encounter. This should actually be done by the
// ICPC plugin via GlobalEvents
Encounter encounter = problem.getEncounter(actKons);
if (encounter != null) {
ElexisEventDispatcher.fireSelectionEvent(encounter);
} else {
ElexisEventDispatcher.clearSelection(Encounter.class);
}
}
}
}
}
});
problemAssignmentViewer.setInput(this);
konsultationTextComposite.setLayout(new GridLayout(1, true));
text = new EnhancedTextField(konsultationTextComposite);
hXrefs = new Hashtable<String, IKonsExtension>();
@SuppressWarnings("unchecked")
List<IKonsExtension> listKonsextensions =
Extensions.getClasses(
Extensions.getExtensions(ExtensionPointConstantsUi.KONSEXTENSION), "KonsExtension", //$NON-NLS-1$ //$NON-NLS-2$
false);
for (IKonsExtension x : listKonsextensions) {
String provider = x.connect(text);
hXrefs.put(provider, x);
}
text.setLayoutData(SWTHelper.getFillGridData(1, true, 1, true));
text.getControl().addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e){
konsEditorHasFocus = true;
}
@Override
public void focusLost(FocusEvent e){
updateEintrag();
konsEditorHasFocus = false;
}
});
Control control = text.getControl();
if (control instanceof StyledText) {
StyledText styledText = (StyledText) control;
styledText.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e){
// create new consultation if required
handleInitialKonsText();
}
});
}
tk.adapt(text);
lVersion = tk.createLabel(konsultationTextComposite, "<aktuell>");
lVersion.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false));
lKonsLock = tk.createLabel(konsultationTextComposite, "");
lKonsLock.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false));
lKonsLock.setForeground(lKonsLock.getDisplay().getSystemColor(SWT.COLOR_RED));
lKonsLock.setVisible(false);
verrechnungComposite.setLayout(new GridLayout(1, true));
Composite verrechnungHeader = tk.createComposite(verrechnungComposite);
verrechnungHeader.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false));
verrechnungHeader.setLayout(new GridLayout(2, false));
hVerrechnung = tk.createHyperlink(verrechnungHeader, "Verrechnung", SWT.NONE);
hVerrechnung.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false));
hVerrechnung.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e){
try {
getViewSite().getPage().showView(LeistungenView.ID);
CodeSelectorHandler.getInstance().setCodeSelectorTarget(
konsultationVerrechnungCodeSelectorTarget);
} catch (Exception ex) {
ExHandler.handle(ex);
log.log("Fehler beim Starten des Leistungscodes " + ex.getMessage(), Log.ERRORS);
}
}
});
hVerrechnung.setEnabled(false);
tVerrechnungKuerzel = tk.createText(verrechnungHeader, "", SWT.BORDER);
gd = new GridData(SWT.END);
gd.widthHint = 50;
tVerrechnungKuerzel.setLayoutData(gd);
tVerrechnungKuerzel.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e){
String mnemonic = tVerrechnungKuerzel.getText();
if (!StringTool.isNothing(mnemonic)) {
// TODO evaluate return value, visualize errors
addLeistungByMnemonic(mnemonic, false, false);
}
}
@Override
public void widgetDefaultSelected(SelectionEvent e){
widgetSelected(e);
}
});
tVerrechnungKuerzel.setEnabled(false);
Table verrechnungTable = tk.createTable(verrechnungComposite, SWT.MULTI);
verrechnungViewer = new TableViewer(verrechnungTable);
verrechnungViewer.getControl().setLayoutData(SWTHelper.getFillGridData(1, true, 1, true));
// used by hightlightVerrechnung()
verrechnungViewerColor = verrechnungTable.getBackground();
verrechnungViewer.setContentProvider(new IStructuredContentProvider() {
@Override
public Object[] getElements(Object inputElement){
if (actKons != null) {
List<Verrechnet> lgl = actKons.getLeistungen();
return lgl.toArray();
}
return new Object[0];
}
@Override
public void dispose(){
// nothing to do
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput){
// nothing to do
}
});
verrechnungViewer.setLabelProvider(new LabelProvider() {
@Override
public String getText(Object element){
if (!(element instanceof Verrechnet)) {
return "";
}
Verrechnet verrechnet = (Verrechnet) element;
StringBuilder sb = new StringBuilder();
int z = verrechnet.getZahl();
Money preis = new Money(verrechnet.getEffPreis()).multiply(z);
// double preis = (z * verrechnet.getEffPreisInRappen()) / 100.0;
sb.append(z).append(" ").append(verrechnet.getCode()).append(" ")
.append(verrechnet.getText()).append(" (").append(preis.getAmountAsString())
.append(")");
return sb.toString();
}
});
verrechnungViewer.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event){
boolean enableDel = false;
boolean enableChange = false;
IStructuredSelection sel = (IStructuredSelection) event.getSelection();
if (sel != null) {
if (sel.size() >= 1) {
enableDel = true;
}
if (sel.size() == 1) {
enableChange = true;
}
}
delVerrechnetAction.setEnabled(enableDel);
changeVerrechnetZahlAction.setEnabled(enableChange);
changeVerrechnetPreisAction.setEnabled(enableChange);
}
});
verrechnungViewer.setInput(this);
lDiagnosis = new CLabel(konsultationComposite, SWT.LEFT);
lDiagnosis.setText("");
tk.adapt(lDiagnosis);
lDiagnosis.setLayoutData(SWTHelper.getFillGridData(1, true, 1, false));
/* Implementation Drag&Drop */
final TextTransfer textTransfer = TextTransfer.getInstance();
Transfer[] types = new Transfer[] {
textTransfer
};
// assignmentComposite
DropTarget dtarget = new DropTarget(assignmentComposite, DND.DROP_COPY);
dtarget.setTransfer(types);
dtarget.addDropListener(new DropTargetListener() {
@Override
public void dragEnter(DropTargetEvent event){
/* Wir machen nur Copy-Operationen */
event.detail = DND.DROP_COPY;
}
@Override
public void dragLeave(DropTargetEvent event){
/* leer */
}
@Override
public void dragOperationChanged(DropTargetEvent event){
/* leer */
}
@Override
public void dragOver(DropTargetEvent event){
/* leer */
}
/* Erst das Loslassen interessiert uns wieder */
@Override
public void drop(DropTargetEvent event){
String drp = (String) event.data;
String[] dl = drp.split(",");
for (String obj : dl) {
PersistentObject dropped = CoreHub.poFactory.createFromString(obj);
if (dropped instanceof Problem) {
Problem problem = (Problem) dropped;
problem.addToKonsultation(actKons);
updateProblemAssignmentViewer();
setDiagnosenText(actKons);
}
}
}
@Override
public void dropAccept(DropTargetEvent event){
/* leer */
}
});
// verrechnungComposite
dtarget = new DropTarget(verrechnungComposite, DND.DROP_COPY);
dtarget.setTransfer(types);
dtarget.addDropListener(new DropTargetListener() {
@Override
public void dragEnter(DropTargetEvent event){
/* Wir machen nur Copy-Operationen */
event.detail = DND.DROP_COPY;
}
@Override
public void dragLeave(DropTargetEvent event){
/* leer */
}
@Override
public void dragOperationChanged(DropTargetEvent event){
/* leer */
}
@Override
public void dragOver(DropTargetEvent event){
/* leer */
}
/* Erst das Loslassen interessiert uns wieder */
@Override
public void drop(DropTargetEvent event){
String drp = (String) event.data;
String[] dl = drp.split(",");
for (String obj : dl) {
PersistentObject dropped = CoreHub.poFactory.createFromString(obj);
if (dropped instanceof IVerrechenbar) {
if (CoreHub.acl.request(AccessControlDefaults.LSTG_VERRECHNEN) == false) {
SWTHelper.alert("Fehlende Rechte",
"Sie haben nicht die Berechtigung, Leistungen zu verrechnen");
} else {
Result<IVerrechenbar> result =
actKons.addLeistung((IVerrechenbar) dropped);
if (!result.isOK()) {
SWTHelper.alert("Diese Verrechnung it ungültig", result.toString());
}
verrechnungViewer.refresh();
updateVerrechnungSum();
}
}
}
}
@Override
public void dropAccept(DropTargetEvent event){
/* leer */
}
});
}
private void highlightProblemsTable(boolean highlight){
highlightProblemsTable(highlight, false);
}
private void highlightProblemsTable(boolean highlight, boolean full){
problemsTableModel.setHighlightSelection(highlight, full);
problemsKTable.redraw();
}
private void highlightVerrechnung(boolean highlight){
Table table = verrechnungViewer.getTable();
if (highlight) {
// set highlighting color
table.setBackground(highlightColor);
} else {
// set default color
table.setBackground(verrechnungViewerColor);
}
}
private void updateProblemAssignmentViewer(){
problemAssignmentViewer.refresh();
// set selection
if (actKons != null) {
List<Problem> problems = Problem.getProblemsOfKonsultation(actKons);
problemAssignmentViewer.setCheckedElements(problems.toArray());
problemAssignmentViewer.refresh();
} else {
// empty selection
problemAssignmentViewer.setCheckedElements(new Problem[] {});
problemAssignmentViewer.refresh();
}
}
public void updateVerrechnungSum(){
StringBuilder sb = new StringBuilder();
sb.append("Verrechnung");
if (actKons != null) {
List<Verrechnet> leistungen = actKons.getLeistungen();
Money sum = new Money(0);
for (Verrechnet leistung : leistungen) {
int z = leistung.getZahl();
Money preis = leistung.getEffPreis().multiply(z);
sum.addMoney(preis);
}
sb.append(" (");
sb.append(sum.getAmountAsString());
sb.append(")");
}
hVerrechnung.setText(sb.toString());
}
private void createHistory(Composite parent){
// history = new HistoryDisplay(parent, getViewSite(), true);
konsListDisplay = new KonsListDisplay(parent);
}
@Override
public void dispose(){
// make sure to unlock the kons edit field and release the lock
removeKonsTextLock();
// ((DefaultContentProvider)fallCf.getContentProvider()).stopListening();
GlobalEventDispatcher.removeActivationListener(this, this);
super.dispose();
}
@Override
public void setFocus(){
// TODO Auto-generated method stub
}
private Problem getSelectedProblem(){
Point[] selection = problemsKTable.getCellSelection();
if (selection == null || selection.length == 0) {
return null;
} else {
int rowIndex = selection[0].y - problemsTableModel.getFixedHeaderRowCount();
Problem problem = problemsTableModel.getProblem(rowIndex);
return problem;
}
}
/**
* used by selectionEvent(PersistentObject obj)
*/
private Konsultation getTodaysLatestKons(Fall fall){
Konsultation result = null;
TimeTool today = new TimeTool();
Konsultation[] konsultationen = fall.getBehandlungen(true);
if (konsultationen != null) {
// find the latest Konsultation according to the text entry's timestamp
long timestamp = -1;
for (Konsultation k : konsultationen) {
if (new TimeTool(k.getDatum()).isSameDay(today)) {
VersionedResource vr = k.getEintrag();
if (vr != null) {
ResourceItem ri = vr.getVersion(vr.getHeadVersion());
if (ri != null) {
if (ri.timestamp > timestamp) {
timestamp = ri.timestamp;
result = k;
}
}
}
}
}
}
return result;
}
/**
* Get the latest Konsultation of today
*
* @return today's latest Konsultation
*
* Same implementation as Patient.getLetzteKons()
*/
public Konsultation getTodaysLatestKons(Patient patient){
TimeTool today = new TimeTool();
Fall[] faelle = patient.getFaelle();
if ((faelle == null) || (faelle.length == 0)) {
return null;
}
Query<Konsultation> qbe = new Query<Konsultation>(Konsultation.class);
qbe.add("MandantID", "=", CoreHub.actMandant.getId());
qbe.add("Datum", "=", today.toString(TimeTool.DATE_COMPACT));
qbe.startGroup();
boolean termInserted = false;
for (Fall fall : faelle) {
if (fall.isOpen()) {
qbe.add("FallID", "=", fall.getId());
qbe.or();
termInserted = true;
}
}
if (!termInserted) {
return null;
}
qbe.endGroup();
qbe.orderBy(true, "Datum");
List<Konsultation> list = qbe.execute();
if ((list == null) || list.isEmpty()) {
return null;
} else {
if (list.size() == 1) {
return list.get(0);
} else {
// find the latest Konsultation according to the text entry's timestamp
long timestamp = -1;
Konsultation result = null;
for (Konsultation k : list) {
VersionedResource vr = k.getEintrag();
if (vr != null) {
ResourceItem ri = vr.getVersion(vr.getHeadVersion());
if (ri != null) {
if (ri.timestamp > timestamp) {
timestamp = ri.timestamp;
result = k;
}
}
}
}
if (result == null) {
result = list.get(0);
}
return result;
}
}
}
public void adaptMenus(){
verrechnungViewer.getTable().getMenu()
.setEnabled(CoreHub.acl.request(AccessControlDefaults.LSTG_VERRECHNEN));
// TODO this belongs to GlobalActions itself (action creator)
GlobalActions.delKonsAction.setEnabled(CoreHub.acl
.request(AccessControlDefaults.KONS_DELETE));
GlobalActions.neueKonsAction.setEnabled(CoreHub.acl
.request(AccessControlDefaults.KONS_CREATE));
}
private void makeActions(){
// Konsultation
// Replacement for GlobalActions.neueKonsAction (other image)
addKonsultationAction = new Action(GlobalActions.neueKonsAction.getText()) {
{
setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin("org.iatrix",
"rsc/new_konsultation.ico"));
setToolTipText(GlobalActions.neueKonsAction.getToolTipText());
}
@Override
public void run(){
GlobalActions.neueKonsAction.run();
}
};
addKonsultationAction.setActionDefinitionId(NEWCONS_COMMAND);
GlobalActions.registerActionHandler(this, addKonsultationAction);
// Probleme
delProblemAction = new Action("Problem löschen") {
@Override
public void run(){
Problem problem = getSelectedProblem();
if (problem != null) {
String label = problem.getLabel();
if (StringTool.isNothing(label)) {
label = UNKNOWN;
}
if (MessageDialog.openConfirm(getViewSite().getShell(), "Wirklich löschen?",
label) == true) {
if (problem.remove(true) == false) {
SWTHelper.alert("Konnte Problem nicht löschen",
"Das Problem konnte nicht gelöscht werden.");
} else {
problemsTableModel.reload();
problemsKTable.refresh();
updateProblemAssignmentViewer();
}
}
}
}
};
addProblemAction = new Action("Neues Problem") {
{
setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin("org.iatrix",
"rsc/new_problem.ico"));
setToolTipText("Neues Problem für diesen Patienten erstellen");
}
@Override
public void run(){
Problem problem = new Problem(ElexisEventDispatcher.getSelectedPatient(), "");
String currentDate = new TimeTool().toString(TimeTool.DATE_ISO);
problem.setStartDate(currentDate);
IatrixEventHelper.fireSelectionEventProblem(problem);
// neues Problem der aktuellen Konsulation hinzufuegen
/*
* if (actKons != null) { MessageBox mb = new MessageBox(getViewSite().getShell(),
* SWT.ICON_QUESTION | SWT.YES | SWT.NO); mb.setText("Neues Problem"); mb
* .setMessage("Neues Problem der aktuellen Konsulation zurdnen?"); if (mb.open() ==
* SWT.YES) { problem.addToKonsultation(actKons); } }
*/
problemsTableModel.reload();
problemsKTable.refresh();
// select the new object
int rowIndex = problemsTableModel.getIndexOf(problem);
if (rowIndex > -1) {
int col = problemsTableModel.getFixedHeaderColumnCount();
int row = rowIndex + problemsTableModel.getFixedHeaderRowCount();
problemsKTable.setSelection(col, row, true);
}
updateProblemAssignmentViewer();
}
};
addProblemAction.setActionDefinitionId(NEWPROBLEM_COMMAND);
GlobalActions.registerActionHandler(this, addProblemAction);
addFixmedikationAction = new Action("Fixmedikation hinzufügen") {
{
setToolTipText("Fixmedikation hinzufügen");
}
@Override
public void run(){
Point[] selection = problemsKTable.getCellSelection();
if (selection.length != 1) {
// no problem selected
SWTHelper
.alert(
"Fixmedikation hinzufügen",
"Sie können eine Fixmedikation nur dann hinzufügen,"
+ "wenn Sie in der entsprechenden Spalte der Patientenübersicht stehen.");
return;
}
int row = selection[0].y;
int rowIndex = row - problemsTableModel.getFixedHeaderRowCount();
Problem problem = problemsTableModel.getProblem(rowIndex);
if (problem != null) {
try {
getViewSite().getPage().showView(LeistungenView.ID);
// register as ICodeSelectorTarget
CodeSelectorHandler.getInstance().setCodeSelectorTarget(
problemFixmedikationCodeSelectorTarget);
} catch (Exception ex) {
ExHandler.handle(ex);
log.log("Fehler beim Anzeigen der Artikel " + ex.getMessage(), Log.ERRORS);
}
}
}
};
editFixmedikationAction = new Action("Fixmedikation ändern...") {
{
setToolTipText("Fixmedikation ändern...");
}
@Override
public void run(){
try {
getViewSite().getPage().showView(ProblemView.ID);
} catch (Exception ex) {
ExHandler.handle(ex);
log.log("Fehler beim Öffnen von ProblemView: " + ex.getMessage(), Log.ERRORS);
}
}
};
deleteFixmedikationAction = new Action("Fixmedikation entfernen...") {
{
setToolTipText("Fixmedikation entfernen...");
}
@Override
public void run(){
try {
getViewSite().getPage().showView(ProblemView.ID);
} catch (Exception ex) {
ExHandler.handle(ex);
log.log("Fehler beim Öffnen von ProblemView: " + ex.getMessage(), Log.ERRORS);
}
}
};
unassignProblemAction = new Action("Problem entfernen") {
{
setToolTipText("Problem von Konsulation entfernen");
}
@Override
public void run(){
Object sel =
((IStructuredSelection) problemAssignmentViewer.getSelection())
.getFirstElement();
if (sel != null) {
Problem problem = (Problem) sel;
problem.removeFromKonsultation(actKons);
updateProblemAssignmentViewer();
setDiagnosenText(actKons);
}
}
};
// Konsultationstext
purgeAction = new Action("Alte Eintragsversionen entfernen") {
@Override
public void run(){
actKons.purgeEintrag();
ElexisEventDispatcher.fireSelectionEvent(actKons);
}
};
versionBackAction = new Action("Vorherige Version") {
@Override
public void run(){
if (MessageDialog
.openConfirm(
getViewSite().getShell(),
"Konsultationstext ersetzen",
"Wollen Sie wirklich den aktuellen Konsultationstext gegen eine frühere Version desselben Eintrags ersetzen?")) {
setKonsText(actKons, displayedVersion - 1, false);
text.setDirty(true);
}
}
};
versionFwdAction = new Action("nächste Version") {
@Override
public void run(){
if (MessageDialog
.openConfirm(
getViewSite().getShell(),
"Konsultationstext ersetzen",
"Wollen Sie wirklich den aktuellen Konsultationstext gegen eine spätere Version desselben Eintrags ersetzen?")) {
setKonsText(actKons, displayedVersion + 1, false);
text.setDirty(true);
}
}
};
chooseVersionAction = new Action("Version wählen...") {
@Override
public void run(){
ChooseKonsRevisionDialog dlg =
new ChooseKonsRevisionDialog(getViewSite().getShell(), actKons);
if (dlg.open() == ChooseKonsRevisionDialog.OK) {
int selectedVersion = dlg.getSelectedVersion();
if (MessageDialog.openConfirm(getViewSite().getShell(),
"Konsultationstext ersetzen",
"Wollen Sie wirklich den aktuellen Konsultationstext gegen die Version "
+ selectedVersion + " desselben Eintrags ersetzen?")) {
setKonsText(actKons, selectedVersion, false);
text.setDirty(true);
}
}
}
};
saveAction = new Action("Eintrag sichern") {
{
setImageDescriptor(Images.IMG_DISK.getImageDescriptor());
setToolTipText("Text explizit speichern");
}
@Override
public void run(){
updateEintrag();
}
};
saveAction.setActionDefinitionId(SAVE_COMMAND);
GlobalActions.registerActionHandler(this, saveAction);
// Verrechnung
delVerrechnetAction = new Action("Leistungsposition entfernen") {
@Override
public void run(){
IStructuredSelection sel = (IStructuredSelection) verrechnungViewer.getSelection();
if (sel != null) {
for (Object obj : sel.toArray()) {
if (obj instanceof Verrechnet) {
Verrechnet verrechnet = (Verrechnet) obj;
Result result = actKons.removeLeistung(verrechnet);
if (!result.isOK()) {
SWTHelper.alert("Leistungsposition kann nicht entfernt werden",
result.toString());
}
verrechnungViewer.refresh();
updateVerrechnungSum();
}
}
}
}
};
delVerrechnetAction.setActionDefinitionId(GlobalActions.DELETE_COMMAND);
GlobalActions.registerActionHandler(this, delVerrechnetAction);
changeVerrechnetPreisAction = new Action("Preis ändern") {
@Override
public void run(){
Object sel =
((IStructuredSelection) verrechnungViewer.getSelection()).getFirstElement();
if (sel != null) {
Verrechnet verrechnet = (Verrechnet) sel;
// String p=Rechnung.geldFormat.format(verrechnet.getEffPreisInRappen()/100.0);
String p = verrechnet.getEffPreis().getAmountAsString();
InputDialog dlg =
new InputDialog(getViewSite().getShell(), "Preis für Leistung ändern",
"Geben Sie bitte den neuen Preis für die Leistung ein (x.xx)", p, null);
if (dlg.open() == Dialog.OK) {
Money newPrice;
try {
newPrice = new Money(dlg.getValue());
verrechnet.setPreis(newPrice);
verrechnungViewer.refresh();
updateVerrechnungSum();
} catch (ParseException e) {
ExHandler.handle(e);
SWTHelper.showError("Falsche Eingabe",
"Konnte Angabe nicht interpretieren");
}
}
}
}
};
changeVerrechnetZahlAction = new Action("Zahl ändern") {
@Override
public void run(){
Object sel =
((IStructuredSelection) verrechnungViewer.getSelection()).getFirstElement();
if (sel != null) {
Verrechnet verrechnet = (Verrechnet) sel;
String p = Integer.toString(verrechnet.getZahl());
InputDialog dlg =
new InputDialog(
getViewSite().getShell(),
"Zahl der Leistung ändern",
"Geben Sie bitte die neue Anwendungszahl für die Leistung bzw. den Artikel ein",
p, null);
if (dlg.open() == Dialog.OK) {
int vorher = verrechnet.getZahl();
int neu = Integer.parseInt(dlg.getValue());
verrechnet.setZahl(neu);
IVerrechenbar verrechenbar = verrechnet.getVerrechenbar();
if (verrechenbar instanceof Artikel) {
Artikel art = (Artikel) verrechenbar;
art.einzelRuecknahme(vorher);
art.einzelAbgabe(neu);
}
verrechnungViewer.refresh();
updateVerrechnungSum();
}
}
}
};
exportToClipboardAction = new Action("Export (Zwischenablage)") {
{
setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin("ch.elexis",
"rsc/plaf/modern/icons/export.ico"));
setToolTipText("Zusammenfassung in Zwischenablage kopieren");
}
@Override
public void run(){
exportToClipboard();
}
};
exportToClipboardAction.setActionDefinitionId(EXPORT_CLIPBOARD_COMMAND);
GlobalActions.registerActionHandler(this, exportToClipboardAction);
sendEmailAction = new Action("E-Mail verschicken") {
{
setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin("ch.elexis",
"rsc/mail.png"));
setToolTipText("E-Mail Programm öffnent (mit Medikation und allen Konsultationen)");
}
@Override
public void run(){
Email.openMailApplication("", // No default to address
null, exportToClipboard(), null);
}
};
sendEmailAction.setActionDefinitionId(EXPORT_SEND_EMAIL_COMMAND);
GlobalActions.registerActionHandler(this, sendEmailAction);
// history display
showAllChargesAction = new Action("Alle Leistungen anzeigen", Action.AS_CHECK_BOX) {
{
setToolTipText("Leistungen aller Konsultationen anzeigen, nicht nur der ersten paar.");
}
@Override
public void run(){
konsListDisplay.setPatient(actPatient, showAllChargesAction.isChecked(),
showAllConsultationsAction.isChecked());
}
};
showAllChargesAction.setActionDefinitionId(Iatrix.SHOW_ALL_CHARGES_COMMAND);
GlobalActions.registerActionHandler(this, showAllChargesAction);
showAllConsultationsAction =
new Action("Alle Konsultationen anzeigen", Action.AS_CHECK_BOX) {
{
setToolTipText("Alle Konsultationen anzeigen");
}
@Override
public void run(){
konsListDisplay.setPatient(actPatient, showAllChargesAction.isChecked(),
showAllConsultationsAction.isChecked());
}
};
showAllConsultationsAction.setActionDefinitionId(Iatrix.SHOW_ALL_CONSULTATIONS_COMMAND);
GlobalActions.registerActionHandler(this, showAllConsultationsAction);
}
private void updateEintrag(){
if (actKons != null) {
log.log("updateEintrag", Log.DEBUGMSG);
if (text.isDirty() || textChanged()) {
if (hasKonsTextLock()) {
actKons.updateEintrag(text.getContentsAsXML(), false);
log.log("saved.", Log.DEBUGMSG);
text.setDirty(false);
// update kons version label
// (we would get an objectChanged event, but this event isn't processed
// in case the kons text field has the focus.)
updateKonsVersionLabel();
} else {
// should never happen...
SWTHelper
.alert(
"Konsultation gesperrt",
"Der Text kann nicht gespeichert werden, weil die Konsultation durch einen anderen Benutzer gesperrt ist."
+ " (Dieses Problem ist ein Programmfehler. Bitte informieren Sie die Entwickler.)");
}
}
}
}
/**
* Check whether the text in the text field has changed compared to the database entry.
*
* @return true, if the text changed, false else
*/
private boolean textChanged(){
String dbEintrag = actKons.getEintrag().getHead();
String textEintrag = text.getContentsAsXML();
if (textEintrag != null) {
if (!textEintrag.equals(dbEintrag)) {
// text differs from db entry
log.log("textChanged", Log.DEBUGMSG);
return true;
}
}
return false;
}
@Override
public void activation(boolean mode){
if (mode == true) {
setKonsultation((Konsultation) ElexisEventDispatcher.getSelected(Konsultation.class),
false);
} else {
updateEintrag();
}
}
@Override
public void visible(boolean mode){
if (mode == true) {
showAllChargesAction.setChecked(false);
showAllConsultationsAction.setChecked(false);
ElexisEventDispatcher.getInstance().addListeners(eeli_kons, eeli_problem, eeli_fall,
eeli_pat, eeli_user);
Patient patient = ElexisEventDispatcher.getSelectedPatient();
setPatient(patient);
/*
* setPatient(Patient) setzt eine neue Konsultation, falls bereits eine gestzt ist und
* diese nicht zum neuen Patienten gehoert. Ansonsten sollten wir die letzte
* Konsultation des Paitenten setzten.
*/
if (actKons == null) {
Konsultation kons =
(Konsultation) ElexisEventDispatcher.getSelected(Konsultation.class);
if (kons != null) {
if (!kons.getFall().getPatient().equals(patient)) {
kons = patient.getLetzteKons(false);
}
}
setKonsultation(kons, false);
}
CoreHub.heart.addListener(this);
} else {
CoreHub.heart.removeListener(this);
ElexisEventDispatcher.getInstance().removeListeners(eeli_kons, eeli_problem, eeli_fall,
eeli_pat, eeli_user);
/*
* setPatient(null) ruft setKonsultation(null) auf.
*/
setPatient(null);
}
};
/**
* Refresh (reload) data
*/
@Override
public void heartbeat(){
// don't run while another heartbeat is currently processed
if (heartbeatActive) {
return;
}
heartbeatActive = true;
UiDesk.getDisplay().asyncExec(new Runnable() {
@Override
public void run(){
heartbeatProblem();
heartbeatKonsultation();
heartbeatSaveKonsText();
}
});
heartbeatActive = false;
}
private void heartbeatProblem(){
if (heartbeatProblemEnabled) {
// backup selection
boolean isRowSelectMode = problemsKTable.isRowSelectMode();
Problem selectedProblem = null;
int currentColumn = -1;
if (isRowSelectMode) {
// full row selection
// not supported
} else {
// single cell selection
Point[] cells = problemsKTable.getCellSelection();
if (cells != null && cells.length > 0) {
int row = cells[0].y;
int rowIndex = row - problemsTableModel.getFixedHeaderRowCount();
selectedProblem = problemsTableModel.getProblem(rowIndex);
currentColumn = cells[0].x;
}
}
// reload data
setPatient(actPatient);
// restore selection
if (selectedProblem != null) {
if (isRowSelectMode) {
// full row selection
// not supported
} else {
// single cell selection
int rowIndex = problemsTableModel.getIndexOf(selectedProblem);
if (rowIndex >= 0) {
// problem found, i. e. still in list
int row = rowIndex + problemsTableModel.getFixedHeaderRowCount();
if (currentColumn == -1) {
currentColumn = problemsTableModel.getFixedHeaderColumnCount();
}
problemsKTable.setSelection(currentColumn, row, true);
}
}
}
}
}
private void heartbeatKonsultation(){
// refresh kons text lock
if (konsTextLock != null) {
boolean success = konsTextLock.lock();
log.log("heartbeatKonsultation: konsText locked (" + success + ")", Log.DEBUGMSG);
// System.err.println("DEBUG: heartbeatKonsultation: konsText locked (" + success +
}
updateKonsultation(!konsEditorHasFocus, false);
}
/**
* Return the auto-save time period interval, as configured in CoreHub.userCfg
*
* @return the calculated period interval, or 1 if there are invalid configuration values, or 0
* if autos-save is disabled
*/
private int getKonsTextSaverPeriod(){
int timePeriod =
CoreHub.userCfg.get(Iatrix.CFG_AUTO_SAVE_PERIOD, Iatrix.CFG_AUTO_SAVE_PERIOD_DEFAULT);
if (timePeriod == 0) {
// no auto-save
return 0;
}
log.log("TimePeriod: " + timePeriod, Log.DEBUGMSG);
int heartbeatInterval =
CoreHub.localCfg.get(ch.elexis.core.constants.Preferences.ABL_HEARTRATE, 30);
if (heartbeatInterval > 0 && timePeriod >= heartbeatInterval) {
int period = timePeriod / heartbeatInterval;
if (period > 0) {
return period;
} else {
// shouldn't occur...
return 1;
}
} else {
// shouldn't occur...
return 1;
}
}
/*
* Automatically save kons text
*/
private void heartbeatSaveKonsText(){
int konsTextSaverPeriod = getKonsTextSaverPeriod();
log.log("Period: " + konsTextSaverPeriod, Log.DEBUGMSG);
if (!(konsTextSaverPeriod > 0)) {
// auto-save disabled
return;
}
// inv: konsTextSaverPeriod > 0
// increment konsTextSaverCount, but stay inside period
konsTextSaverCount++;
konsTextSaverCount %= konsTextSaverPeriod;
log.log("konsTextSaverCount = " + konsTextSaverCount, Log.DEBUGMSG);
log.log("konsEditorHasFocus: " + konsEditorHasFocus, Log.DEBUGMSG);
if (konsTextSaverCount == 0) {
if (konsEditorHasFocus) {
log.log("Auto Save Kons Text", Log.DEBUGMSG);
updateEintrag();
}
}
}
private void setHeartbeatProblemEnabled(boolean value){
heartbeatProblemEnabled = value;
}
/*
* Aktuellen Patienten setzen
*/
public void setPatient(Patient patient){
if (actPatient == patient) {
return;
}
actPatient = patient;
// widgets may be disposed when application is closed
if (form.isDisposed()) {
return;
}
if (actPatient != null) {
// Pruefe, ob Patient Probleme hat, sonst Standardproblem erstellen
List<Problem> problems = Problem.getProblemsOfPatient(actPatient);
if (problems.size() == 0) {
// TODO don't yet do this
// Problem.createStandardProblem(actPatient);
}
problemsTableModel.reload();
problemsKTable.refresh();
// Konsistenz Patient/Konsultation ueberpruefen
if (actKons != null) {
if (!actKons.getFall().getPatient().getId().equals(actPatient.getId())) {
// aktuelle Konsultation gehoert nicht zum aktuellen Patienten
setKonsultation(actPatient.getLetzteKons(false), false);
}
}
// history.stop();
// history.load(actPatient);
// history.start();
log.log("Patient: " + actPatient.getId(), Log.DEBUGMSG);
} else {
// problemsTable.setInput(null);
problemsTableModel.reload();
problemsKTable.refresh();
// Kein Patient ausgewaehlt, somit auch keine Konsultation anzeigen
setKonsultation(null, false);
// TODO history widget may be disposed, how to recognize?
/*
* history.stop(); history.load(null, true); history.start();
*/
log.log("Patient: null", Log.DEBUGMSG);
}
konsListDisplay.setPatient(actPatient, showAllChargesAction.isChecked(),
showAllConsultationsAction.isChecked());
setPatientTitel();
setRemarkAndSticker();
setKontoText();
}
/**
* Set the version label to reflect the current kons' latest version Called by: updateEintrag()
*/
void updateKonsVersionLabel(){
if (actKons != null) {
int version = actKons.getHeadVersion();
log.log("Update Version Label: " + version, Log.DEBUGMSG);
VersionedResource vr = actKons.getEintrag();
ResourceItem entry = vr.getVersion(version);
StringBuilder sb = new StringBuilder();
sb.append("rev. ").append(version).append(" vom ")
.append(new TimeTool(entry.timestamp).toString(TimeTool.FULL_GER)).append(" (")
.append(entry.remark).append(")");
lVersion.setText(sb.toString());
} else {
lVersion.setText("");
}
}
void setKonsText(Konsultation b, int version, boolean putCaretToEnd){
if (b != null) {
String ntext = "";
if ((version >= 0) && (version <= b.getHeadVersion())) {
VersionedResource vr = b.getEintrag();
ResourceItem entry = vr.getVersion(version);
ntext = entry.data;
StringBuilder sb = new StringBuilder();
sb.append("rev. ").append(version).append(" vom ")
.append(new TimeTool(entry.timestamp).toString(TimeTool.FULL_GER)).append(" (")
.append(entry.remark).append(")");
lVersion.setText(sb.toString());
} else {
lVersion.setText("");
}
text.setText(PersistentObject.checkNull(ntext));
text.setKons(b);
text.setEnabled(hasKonsTextLock());
displayedVersion = version;
versionBackAction.setEnabled(version != 0);
versionFwdAction.setEnabled(version != b.getHeadVersion());
if (putCaretToEnd) {
// set focus and put caret at end of text
text.putCaretToEnd();
}
} else {
lVersion.setText("");
text.setText("");
text.setKons(null);
if (actPatient == null) {
text.setEnabled(false);
} else {
// enable text, in case user wants to create a new kons by
// typing in the empty text field
text.setEnabled(true);
}
displayedVersion = -1;
versionBackAction.setEnabled(false);
versionFwdAction.setEnabled(false);
}
}
private void setDiagnosenText(Konsultation konsultation){
String text = "";
Image image = null;
if (konsultation != null) {
List<IDiagnose> diagnosen = konsultation.getDiagnosen();
if (diagnosen != null && diagnosen.size() > 0) {
List<String> dxList = new ArrayList<String>();
for (IDiagnose diagnose : diagnosen) {
dxList.add(diagnose.getLabel());
}
text = "Diagnosen: " + StringTool.join(dxList, ", ");
} else {
// no diagnosis, warn error
text = "Keine Diagnosen";
image = Images.IMG_ACHTUNG.getImage();
}
}
lDiagnosis.setText(PersistentObject.checkNull(text));
lDiagnosis.setImage(image);
}
private void setPatientTitel(){
String text = "Kein Patient ausgewählt";
formTitel.setEnabled(actPatient != null);
if (actPatient != null) {
text = actPatient.getLabel();
}
formTitel.setText(PersistentObject.checkNull(text));
formTitel.getParent().layout();
}
private void setRemarkAndSticker(){
String text = "";
sticker = Images.IMG_EMPTY_TRANSPARENT.getImage();
if (actPatient != null) {
text = actPatient.getBemerkung();
ISticker et = actPatient.getSticker();
if (et != null) {
sticker = new UiSticker((Sticker) et).getImage();
}
}
if (sticker == null) {
sticker = Images.IMG_EMPTY_TRANSPARENT.getImage();
}
stickerLabel.setImage(sticker);
if (PersistentObject.checkNull(text).length() == 0)
remarkLabel.setText("Bemerkungen");
else
remarkLabel.setText(PersistentObject.checkNull(text));
formTitel.getParent().layout();
}
private void setKontoText(){
// TODO common isTardyPayer method in class Patient
// this may involve a slow query
kontoLabel.getDisplay().asyncExec(new Runnable() {
@Override
public void run(){
boolean tardyPayer = false;
// the widget may already be disposed when the application exits
if (remarkLabel.isDisposed()) {
return;
}
String text = "";
if (actPatient != null) {
text = actPatient.getKontostand().getAmountAsString();
tardyPayer = isTardyPayer(actPatient);
}
kontoLabel.setText(PersistentObject.checkNull(text));
kontoLabel.getParent().layout();
// draw the label red if the patient is a tardy payer
Color textColor;
if (tardyPayer) {
textColor = kontoLabel.getDisplay().getSystemColor(SWT.COLOR_RED);
} else {
textColor = kontoLabelColor;
}
kontoLabel.setForeground(textColor);
formTitel.getParent().layout();
}
});
}
/**
* Aktuelle Konsultation setzen.
*
* Wenn eine Konsultation gesetzt wird stellen wir sicher, dass der gesetzte Patient zu dieser
* Konsultation gehoert. Falls nicht, wird ein neuer Patient gesetzt.
*
* @param putCaretToEnd
* if true, activate text field ant put caret to the end
*/
public void setKonsultation(Konsultation k, boolean putCaretToEnd){
// save probably not yet saved changes
updateEintrag();
// make sure to unlock the kons edit field and release the lock
removeKonsTextLock();
actKons = k;
if (savedInitialKonsText != null && actKons != null) {
actKons.updateEintrag(savedInitialKonsText, true);
savedInitialKonsText = null;
}
creatingKons = false;
if (actKons != null) {
// create new konsTextLock
createKonsTextLock();
Patient patient = actKons.getFall().getPatient();
// Konsistenz Patient/Konsultation ueberpruefen
if (actPatient == null || (!actPatient.equals(patient))) {
setPatient(patient);
}
}
updateKonsultation(true, putCaretToEnd);
// update konslock label and enable/disable save action
updateKonsLockLabel();
saveAction.setEnabled(konsTextLock == null || hasKonsTextLock());
}
private void updateKonsLockLabel(){
if (konsTextLock == null || hasKonsTextLock()) {
lKonsLock.setVisible(false);
lKonsLock.setText("");
} else {
Anwender user = konsTextLock.getLockValue().getUser();
String text;
if (user != null && user.exists()) {
text = "Konsultation wird von Benutzer \"" + user.getLabel() + "\" bearbeitet.";
} else {
text = "Konsultation wird von anderem Benutzer bearbeitet.";
}
lKonsLock.setText(text);
lKonsLock.setVisible(true);
}
lKonsLock.getParent().layout();
}
private void updateKonsultation(boolean updateText, boolean putCaretToEnd){
if (actKons != null) {
cbFall.setEnabled(true);
hVerrechnung.setEnabled(true);
tVerrechnungKuerzel.setEnabled(true);
StringBuilder sb = new StringBuilder();
sb.append(actKons.getDatum());
/*
* lKonsultation.setText(sb.toString());
*/
hlKonsultationDatum.setText(sb.toString());
hlKonsultationDatum.setEnabled(true);
if (hasMultipleMandants) {
// inv: hlMandant != null
Mandant m = actKons.getMandant();
sb = new StringBuilder();
if (m == null) {
sb.append("(nicht von Ihnen)");
} else {
Rechnungssteller rs = m.getRechnungssteller();
if (rs.getId().equals(m.getId())) {
sb.append("(").append(m.getLabel()).append(")");
} else {
sb.append("(").append(m.getLabel()).append("/").append(rs.getLabel())
.append(")");
}
}
hlMandant.setText(sb.toString());
hlMandant.setEnabled(CoreHub.acl.request(AccessControlDefaults.KONS_REASSIGN));
}
reloadFaelle(actKons);
if (updateText) {
setKonsText(actKons, actKons.getHeadVersion(), putCaretToEnd);
}
setDiagnosenText(actKons);
log.log("Konsultation: " + actKons.getId(), Log.DEBUGMSG);
} else {
cbFall.setEnabled(false);
hVerrechnung.setEnabled(false);
tVerrechnungKuerzel.setEnabled(false);
hlKonsultationDatum.setText("Keine Konsultation ausgewählt");
hlKonsultationDatum.setEnabled(false);
if (hlMandant != null) {
hlMandant.setText("");
hlMandant.setEnabled(false);
}
reloadFaelle(null);
setKonsText(null, 0, putCaretToEnd);
setDiagnosenText(null);
log.log("Konsultation: null", Log.DEBUGMSG);
}
konsFallArea.layout();
updateProblemAssignmentViewer();
verrechnungViewer.refresh();
updateVerrechnungSum();
}
private void reloadFaelle(Konsultation konsultation){
cbFall.removeAll();
if (konsultation != null) {
Fall fall = konsultation.getFall();
Patient patient = fall.getPatient();
Fall[] faelle = patient.getFaelle();
// find current case
int index = -1;
for (int i = 0; i < faelle.length; i++) {
if (faelle[i].getId().equals(fall.getId())) {
index = i;
}
}
// add cases and select current case if found
if (index >= 0) {
cbFall.setData(faelle);
for (Fall f : faelle) {
cbFall.add(f.getLabel());
}
// no selection event seems to be generated
cbFall.select(index);
}
}
}
private void openRemarkEditorDialog(){
if (actPatient == null) {
return;
}
String initialValue = PersistentObject.checkNull(actPatient.getBemerkung());
InputDialog dialog =
new InputDialog(getViewSite().getShell(), "Bemerkungen", "Bemerkungen eingeben",
initialValue, null);
if (dialog.open() == Window.OK) {
String text = dialog.getValue();
actPatient.setBemerkung(text);
setRemarkAndSticker();
}
}
/**
* Is the patient a tardy payer, i. e. hasn't it paid all his bills?
*
* @param patient
* the patient to examine
* @return true if the patient is a tardy payer, false otherwise
*
* TODO this maybe makes the view slower
*/
private boolean isTardyPayer(Patient patient){
// find bills with status MAHNUNG_1 to TOTALVERLUST
// if there are such, the patient is a tardy payer
// find all patient's bills
Query<Rechnung> query = new Query<Rechnung>(Rechnung.class);
Fall[] faelle = patient.getFaelle();
if ((faelle != null) && (faelle.length > 0)) {
query.startGroup();
query.insertFalse();
query.or();
for (Fall fall : faelle) {
if (fall.isOpen()) {
query.add("FallID", "=", fall.getId());
}
}
query.endGroup();
} else {
// no cases found
return false;
}
query.and();
query.startGroup();
query.insertFalse();
query.or();
for (int s = RnStatus.MAHNUNG_1; s <= RnStatus.TOTALVERLUST; s++) {
query.add("RnStatus", "=", new Integer(s).toString());
}
query.endGroup();
List<Rechnung> rechnungen = query.execute();
if (rechnungen != null && rechnungen.size() > 0) {
// there are tardy bills
return true;
} else {
// no tardy bills (or sql error)
return false;
}
}
/**
* Creates a new consultation if text has been entered, but no consultation is selected.
*/
private void handleInitialKonsText(){
if (actPatient != null && actKons == null && creatingKons == false) {
creatingKons = true;
String initialText = text.getContentsAsXML();
Konsultation.neueKons(initialText);
} else {
savedInitialKonsText = text.getContentsAsXML();
}
}
@Override
public int promptToSaveOnClose(){
return GlobalActions.fixLayoutAction.isChecked() ? ISaveablePart2.CANCEL
: ISaveablePart2.NO;
}
@Override
public void doSave(IProgressMonitor monitor){ /* leer */}
@Override
public void doSaveAs(){ /* leer */}
@Override
public boolean isDirty(){
return true;
}
@Override
public boolean isSaveAsAllowed(){
return false;
}
@Override
public boolean isSaveOnCloseNeeded(){
return true;
}
private class ProblemsTableLabelProvider implements ITableLabelProvider, ITableFontProvider,
ITableColorProvider {
@Override
public void addListener(ILabelProviderListener listener){
// nothing to do
}
@Override
public void removeListener(ILabelProviderListener listener){
// nothing to do
}
@Override
public void dispose(){
// nothing to do
}
@Override
public Image getColumnImage(Object element, int columnIndex){
if (!(element instanceof Problem)) {
return null;
}
Problem problem = (Problem) element;
switch (columnIndex) {
case STATUS:
if (problem.getStatus() == Episode.ACTIVE) {
return UiDesk.getImage(Iatrix.IMG_ACTIVE);
} else {
return UiDesk.getImage(Iatrix.IMG_INACTIVE);
}
default:
return null;
}
}
@Override
public String getColumnText(Object element, int columnIndex){
if (!(element instanceof Problem)) {
return "";
}
Problem problem = (Problem) element;
String text;
String lineSeparator;
switch (columnIndex) {
case BEZEICHNUNG:
return problem.getTitle();
case NUMMER:
return problem.getNumber();
case DATUM:
return problem.getStartDate();
case DIAGNOSEN:
String diagnosen = problem.getDiagnosenAsText();
lineSeparator = System.getProperty("line.separator");
text = diagnosen.replaceAll(Problem.TEXT_SEPARATOR, lineSeparator);
return text;
/*
* case GESETZ: return problem.getGesetz();
*/
/*
* case RECHNUNGSDATEN: return "not yet implemented";
*/
case THERAPIE:
String prescriptions = problem.getPrescriptionsAsText();
lineSeparator = System.getProperty("line.separator");
text = prescriptions.replaceAll(Problem.TEXT_SEPARATOR, lineSeparator);
return text;
case STATUS:
return "";
default:
return "";
}
}
@Override
public boolean isLabelProperty(Object element, String property){
return false;
}
@Override
public Font getFont(Object element, int columnIndex){
return null;
}
@Override
public Color getForeground(Object element, int columnIndex){
return null;
}
@Override
public Color getBackground(Object element, int columnIndex){
if (!(element instanceof Problem)) {
return null;
}
Problem problem = (Problem) element;
Color color;
if (problem.getStatus() == Episode.ACTIVE) {
color =
problemAssignmentViewer.getTable().getDisplay().getSystemColor(SWT.COLOR_WHITE);
} else {
color =
problemAssignmentViewer.getTable().getDisplay().getSystemColor(SWT.COLOR_GRAY);
}
return color;
}
}
/**
* Copies the most important data to the clipboard, suitable to import into other text.
* Includes: - patient data (name, birthdate, address, phone numbers) - list of problems
* including medicals (all or selected only) - the latest consultations
*/
private String exportToClipboard(){
final int NUMBER_OF_CONS = 1;
String lineSeparator = System.getProperty("line.separator");
String fieldSeparator = "\t";
String clipboardText = "";
if (actPatient != null) {
StringBuffer output = new StringBuffer();
// get list of selected problems
List<Problem> problems = new ArrayList<Problem>();
Problem p = getSelectedProblem();
if (p != null) {
problems.add(p);
}
// patient label
StringBuffer patientLabel = new StringBuffer();
patientLabel.append(actPatient.getName() + " " + actPatient.getVorname());
patientLabel.append(" (");
patientLabel.append(actPatient.getGeschlecht());
patientLabel.append("), ");
patientLabel.append(actPatient.getGeburtsdatum());
patientLabel.append(", ");
output.append(patientLabel);
// patient address
StringBuffer patientAddress = new StringBuffer();
Anschrift anschrift = actPatient.getAnschrift();
patientAddress.append(anschrift.getStrasse());
patientAddress.append(", ");
patientAddress.append(anschrift.getPlz() + " " + anschrift.getOrt());
patientAddress.append(lineSeparator);
output.append(patientAddress);
// patient phone numbers
boolean isFirst = true;
StringBuffer patientPhones = new StringBuffer();
String telefon1 = actPatient.get("Telefon1");
String telefon2 = actPatient.get("Telefon2");
String natel = actPatient.get("Natel");
String eMail = actPatient.get("E-Mail");
if (!StringTool.isNothing(telefon1)) {
if (isFirst) {
isFirst = false;
} else {
patientPhones.append(", ");
}
patientPhones.append("T: ");
patientPhones.append(telefon1);
if (!StringTool.isNothing(telefon2)) {
patientPhones.append(", ");
patientPhones.append(telefon2);
}
}
if (!StringTool.isNothing(natel)) {
if (isFirst) {
isFirst = false;
} else {
patientPhones.append(", ");
}
patientPhones.append("M: ");
patientPhones.append(natel);
}
if (!StringTool.isNothing(natel)) {
if (isFirst) {
isFirst = false;
} else {
patientPhones.append(", ");
}
patientPhones.append(eMail);
}
patientPhones.append(lineSeparator);
output.append(patientPhones);
output.append(lineSeparator);
// consultations
List<Konsultation> konsultationen = new ArrayList<Konsultation>();
if (problems.size() > 0) {
// get consultations of selected problems
for (Problem problem : problems) {
konsultationen.addAll(problem.getKonsultationen());
}
} else {
// get all consultations
for (Fall fall : actPatient.getFaelle()) {
for (Konsultation k : fall.getBehandlungen(false)) {
konsultationen.add(k);
}
}
}
// sort list of consultations in reverse order, get the latest ones
Collections.sort(konsultationen, new Comparator<Konsultation>() {
@Override
public int compare(Konsultation k1, Konsultation k2){
String d1 = k1.getDatum();
String d2 = k2.getDatum();
if (d1 == null) {
return 1;
}
if (d2 == null) {
return -1;
}
TimeTool date1 = new TimeTool(d1);
TimeTool date2 = new TimeTool(d2);
// reverse order
return -(date1.compareTo(date2));
}
});
for (int i = 0; i < NUMBER_OF_CONS && konsultationen.size() >= (i + 1); i++) {
Konsultation konsultation = konsultationen.get(i);
// output
StringBuffer sb = new StringBuffer();
sb.append(konsultation.getLabel());
List<Problem> konsProblems = Problem.getProblemsOfKonsultation(konsultation);
if (konsProblems != null && konsProblems.size() > 0) {
StringBuffer problemsLabel = new StringBuffer();
problemsLabel.append(" (");
// first problem in list
problemsLabel.append(konsProblems.get(0).getTitle());
for (int j = 1; j < konsProblems.size(); j++) {
// further problems in list
problemsLabel.append(", ");
problemsLabel.append(konsProblems.get(j).getTitle());
}
problemsLabel.append(")");
sb.append(problemsLabel);
}
sb.append(lineSeparator);
Samdas samdas = new Samdas(konsultation.getEintrag().getHead());
sb.append(samdas.getRecordText());
sb.append(lineSeparator);
sb.append(lineSeparator);
output.append(sb);
}
if (problems.size() == 0) {
List<Problem> allProblems = Problem.getProblemsOfPatient(actPatient);
if (problems != null) {
problems.addAll(allProblems);
}
}
Collections.sort(problems, DATE_COMPARATOR);
StringBuffer problemsText = new StringBuffer();
problemsText.append("Persönliche Anamnese");
problemsText.append(lineSeparator);
for (Problem problem : problems) {
String date = problem.getStartDate();
String text = problem.getTitle();
List<String> therapy = new ArrayList<String>();
String procedure = problem.getProcedere();
if (!StringTool.isNothing(procedure)) {
therapy.add(procedure.trim());
}
List<Prescription> prescriptions = problem.getPrescriptions();
for (Prescription prescription : prescriptions) {
String label =
prescription.getArtikel().getLabel() + " (" + prescription.getDosis() + ")";
therapy.add(label.trim());
}
StringBuffer sb = new StringBuffer();
sb.append(date);
sb.append(fieldSeparator);
sb.append(text);
sb.append(fieldSeparator);
if (!therapy.isEmpty()) {
// first therapy entry
sb.append(therapy.get(0));
}
sb.append(lineSeparator);
// further therapy entries
if (therapy.size() > 1) {
for (int i = 1; i < therapy.size(); i++) {
sb.append(fieldSeparator);
sb.append(fieldSeparator);
sb.append(therapy.get(i));
sb.append(lineSeparator);
}
}
problemsText.append(sb);
}
output.append(problemsText);
clipboardText = output.toString();
}
Clipboard clipboard = new Clipboard(UiDesk.getDisplay());
TextTransfer textTransfer = TextTransfer.getInstance();
Transfer[] transfers = new Transfer[] {
textTransfer
};
Object[] data = new Object[] {
clipboardText
};
clipboard.setContents(data, transfers);
clipboard.dispose();
return clipboardText;
}
/**
* Leistung anhand des Kuerzels hinzufuegen
*/
private boolean addLeistungByMnemonic(String mnemonic, boolean approximation, boolean multi){
boolean success = false;
if (actKons != null && !StringTool.isNothing(mnemonic)) {
Query<Artikel> query = new Query<Artikel>(Artikel.class);
if (approximation) {
query.add("Eigenname", "LIKE", mnemonic + "%");
} else {
query.add("Eigenname", "=", mnemonic);
}
List<Artikel> artikels = query.execute();
if (artikels != null && !artikels.isEmpty()) {
List<Artikel> selection = new ArrayList<Artikel>();
if (multi) {
selection.addAll(artikels);
} else {
selection.add(artikels.get(0));
}
List<Result<IVerrechenbar>> results = new ArrayList<Result<IVerrechenbar>>();
PersistentObjectFactory factory = new PersistentObjectFactory();
for (Artikel artikel : artikels) {
String typ = artikel.get("Typ");
String id = artikel.getId();
// work-around for articles without class information (plugin
// elexis-artikel-schweiz)
if (typ.equals("Medikament") || typ.equals("Medical") || typ.equals("MiGeL")) {
typ = "ch.elexis.artikel_ch.data." + typ;
}
PersistentObject po = factory.createFromString(typ + "::" + id);
if (po instanceof IVerrechenbar) {
Result<IVerrechenbar> result = actKons.addLeistung((IVerrechenbar) po);
if (!result.isOK()) {
results.add(result);
}
}
}
verrechnungViewer.refresh();
updateVerrechnungSum();
if (results.isEmpty()) {
success = true;
} else {
StringBuffer sb = new StringBuffer();
boolean first = true;
for (Result<IVerrechenbar> result : results) {
if (first) {
first = false;
} else {
sb.append("; ");
}
sb.append(result.toString());
SWTHelper.alert("Diese Verrechnung ist ungültig", sb.toString());
}
}
}
}
return success;
}
/*
* Extendsion of KTable KTable doesn't update the scrollbar visibility if the model changes. We
* would require to call setModel(). As a work-around, we implement refresh(), which calls
* updateScrollbarVisibility() before redraw().
*/
class MyKTable extends KTable {
public MyKTable(Composite parent, int style){
super(parent, style);
}
public void refresh(){
updateScrollbarVisibility();
redraw();
}
}
class ProblemsTableModel implements KTableModel {
private Object[] problems = null;
private final Hashtable<Integer, Integer> colWidths = new Hashtable<Integer, Integer>();
private final Hashtable<Integer, Integer> rowHeights = new Hashtable<Integer, Integer>();
private final KTableCellRenderer fixedRenderer = new FixedCellRenderer(
FixedCellRenderer.STYLE_PUSH | FixedCellRenderer.INDICATION_SORT
| FixedCellRenderer.INDICATION_FOCUS | FixedCellRenderer.INDICATION_CLICKED);
private final KTableCellRenderer textRenderer = new ProblemsTableTextCellRenderer();
private final KTableCellRenderer imageRenderer = new ProblemsTableImageCellRenderer();
private final KTableCellRenderer therapyRenderer = new ProblemsTableTherapyCellRenderer();
private Comparator comparator = DATE_COMPARATOR;
private boolean highlightSelection = false;
private boolean highlightRow = false;
public Problem getProblem(int index){
Problem problem = null;
if (problems != null) {
if (index >= 0 && index < problems.length) {
Object element = problems[index];
if (element instanceof Problem) {
problem = (Problem) element;
}
}
}
return problem;
}
/**
* Finds the index of the given problem (array index, not row)
*
* @param problem
* @return the index, or -1 if not found
*/
public int getIndexOf(Problem problem){
if (problems != null) {
for (int i = 0; i < problems.length; i++) {
Object element = problems[i];
if (element instanceof Problem) {
Problem p = (Problem) element;
if (p.getId().equals(problem.getId())) {
return i;
}
}
}
}
return -1;
}
/**
* Returns the KTable index corresponding to our model index (mapping)
*
* @param rowIndex
* the index of a problem
* @return the problem's index as a KTable index
*/
public int modelIndexToTableIndex(int rowIndex){
return rowIndex + problemsTableModel.getFixedHeaderRowCount();
}
/**
* Returns the model index corresponding to the KTable index (mapping)
*
* @param row
* the KTable index of a problem
* @return the problem's index of the model
*/
public int tableIndexToRowIndex(int row){
return row - problemsTableModel.getFixedHeaderRowCount();
}
@Override
public Point belongsToCell(int col, int row){
return new Point(col, row);
}
@Override
public KTableCellEditor getCellEditor(int col, int row){
if (row < getFixedHeaderRowCount() || col < getFixedHeaderColumnCount()) {
return null;
}
int colIndex = col - getFixedHeaderColumnCount();
if (colIndex == BEZEICHNUNG || colIndex == NUMMER || colIndex == DATUM) {
return new MyKTableCellEditorText2();
} else if (colIndex == THERAPIE) {
return new KTableTherapyCellEditor();
} else {
return null;
}
}
@Override
public KTableCellRenderer getCellRenderer(int col, int row){
if (row < getFixedHeaderRowCount() || col < getFixedHeaderColumnCount()) {
return fixedRenderer;
}
int colIndex = col - getFixedHeaderColumnCount();
if (colIndex == STATUS) {
return imageRenderer;
}
if (colIndex == THERAPIE) {
return therapyRenderer;
}
return textRenderer;
}
@Override
public int getColumnCount(){
return getFixedHeaderColumnCount() + COLUMN_TEXT.length;
}
@Override
public int getRowCount(){
loadElements();
return getFixedHeaderRowCount() + problems.length;
}
@Override
public int getFixedHeaderColumnCount(){
return 1;
}
@Override
public int getFixedSelectableColumnCount(){
return 0;
}
@Override
public int getFixedHeaderRowCount(){
return 1;
}
@Override
public int getFixedSelectableRowCount(){
return 0;
}
private int getInitialColumnWidth(int col){
if (col < getFixedHeaderColumnCount()) {
return 20;
}
int colIndex = col - getFixedHeaderColumnCount();
if (colIndex >= 0 && colIndex < COLUMN_TEXT.length) {
int width =
CoreHub.localCfg.get(COLUMN_CFG_KEY[colIndex], DEFAULT_COLUMN_WIDTH[colIndex]);
return width;
} else {
// invalid column
return 0;
}
}
@Override
public int getColumnWidth(int col){
Integer width = colWidths.get(new Integer(col));
if (width == null) {
width = new Integer(getInitialColumnWidth(col));
colWidths.put(new Integer(col), width);
}
return width.intValue();
}
private int getHeaderRowHeight(){
// TODO
return 22;
}
@Override
public int getRowHeightMinimum(){
// TODO
return 10;
}
@Override
public int getRowHeight(int row){
Integer height = rowHeights.get(new Integer(row));
if (height == null) {
height = new Integer(getOptimalRowHeight(row));
rowHeights.put(new Integer(row), height);
}
return height.intValue();
}
private int getOptimalRowHeight(int row){
if (row < getFixedHeaderRowCount()) {
return getHeaderRowHeight();
} else {
int height = 0;
GC gc = new GC(problemsKTable);
for (int i = 0; i < COLUMN_TEXT.length; i++) {
int col = i + getFixedHeaderColumnCount();
int currentHeight = 0;
Object obj = getContentAt(col, row);
if (obj instanceof String) {
String text = (String) obj;
currentHeight = gc.textExtent(text).y;
} else if (obj instanceof Image) {
Image image = (Image) obj;
currentHeight = image.getBounds().height;
} else if (obj instanceof Problem && i == THERAPIE) {
Problem problem = (Problem) obj;
ProblemsTableTherapyCellRenderer cellRenderer =
(ProblemsTableTherapyCellRenderer) getCellRenderer(col, row);
currentHeight = cellRenderer.getOptimalHeight(gc, problem);
}
if (currentHeight > height) {
height = currentHeight;
}
}
gc.dispose();
return height;
}
}
@Override
public void setColumnWidth(int col, int width){
colWidths.put(new Integer(col), new Integer(width));
// store new column with in localCfg
int colIndex = col - getFixedHeaderColumnCount();
if (colIndex >= 0 && colIndex < COLUMN_TEXT.length) {
CoreHub.localCfg.set(COLUMN_CFG_KEY[colIndex], width);
}
}
@Override
public void setRowHeight(int row, int height){
rowHeights.put(new Integer(row), new Integer(height));
}
private void loadElements(){
if (problems == null) {
List<Object> elements = new ArrayList<Object>();
if (actPatient != null) {
List<Problem> problems = Problem.getProblemsOfPatient(actPatient);
if (comparator != null) {
Collections.sort(problems, comparator);
}
elements.addAll(problems);
// add dummy element
elements.add(new DummyProblem());
}
problems = elements.toArray();
}
}
private void addElement(Object element){
Object[] newProblems = new Object[problems.length + 1];
System.arraycopy(problems, 0, newProblems, 0, problems.length);
newProblems[newProblems.length - 1] = element;
}
private void reload(){
// force elements to be reloaded
problems = null;
// force heights to be re-calculated
rowHeights.clear();
}
private Object getHeaderContentAt(int col){
int colIndex = col - getFixedHeaderColumnCount();
if (colIndex >= 0 && colIndex < COLUMN_TEXT.length) {
return COLUMN_TEXT[colIndex];
} else {
return "";
}
}
@Override
public Object getContentAt(int col, int row){
if (row < getFixedHeaderRowCount()) {
// header
return getHeaderContentAt(col);
}
// rows
// load problems if required
loadElements();
int colIndex = col - getFixedHeaderColumnCount();
int rowIndex = row - getFixedHeaderRowCount(); // consider header row
if (rowIndex >= 0 && rowIndex < problems.length) {
Object element = problems[rowIndex];
if (element instanceof Problem) {
Problem problem = (Problem) element;
String text;
String lineSeparator;
switch (colIndex) {
case BEZEICHNUNG:
return problem.getTitle();
case NUMMER:
return problem.getNumber();
case DATUM:
return problem.getStartDate();
case DIAGNOSEN:
String diagnosen = problem.getDiagnosenAsText();
lineSeparator = System.getProperty("line.separator");
text = diagnosen.replaceAll(Problem.TEXT_SEPARATOR, lineSeparator);
return text;
/*
* case GESETZ: return problem.getGesetz();
*/
/*
* case RECHNUNGSDATEN: return "not yet implemented";
*/
case THERAPIE:
/*
* String prescriptions = problem.getPrescriptionsAsText(); lineSeparator =
* System.getProperty("line.separator"); text =
* prescriptions.replaceAll(Problem.TEXT_SEPARATOR, lineSeparator); return
* text;
*/
return problem;
/*
* case PROCEDERE: return problem.getProcedere();
*/
case STATUS:
if (problem.getStatus() == Episode.ACTIVE) {
return UiDesk.getImage(Iatrix.IMG_ACTIVE);
} else {
return UiDesk.getImage(Iatrix.IMG_INACTIVE);
}
default:
return "";
}
} else {
// DummyProblem
if (col < getFixedHeaderColumnCount()) {
return "*";
} else {
return "";
}
}
} else {
// row index out of bound
return "";
}
}
@Override
public String getTooltipAt(int col, int row){
if (col < TOOLTIP_TEXT.length)
return TOOLTIP_TEXT[col];
else
return "Tooltip für col " + col;
}
@Override
public boolean isColumnResizable(int col){
return true;
}
@Override
public boolean isRowResizable(int row){
return true;
}
@Override
public void setContentAt(int col, int row, Object value){
// don't do anything if there are no problems
if (problems == null) {
return;
}
// only accept String values
if (!(value instanceof String)) {
return;
}
String text = (String) value;
int colIndex = col - getFixedHeaderColumnCount();
int rowIndex = row - getFixedHeaderRowCount();
if (rowIndex >= 0 && rowIndex < problems.length) {
boolean isNew = false;
Problem problem;
if (problems[rowIndex] instanceof Problem) {
problem = (Problem) problems[rowIndex];
} else {
// replace dummy object with real object
if (actPatient == null) {
// shuldn't happen; silently ignore
return;
}
problem = new Problem(actPatient, "");
String currentDate = new TimeTool().toString(TimeTool.DATE_ISO);
problem.setStartDate(currentDate);
IatrixEventHelper.fireSelectionEventProblem(problem);
problems[rowIndex] = problem;
addElement(new DummyProblem());
isNew = true;
}
switch (colIndex) {
case BEZEICHNUNG:
problem.setTitle(text);
break;
case NUMMER:
problem.setNumber(text);
break;
case DATUM:
problem.setStartDate(text);
break;
case THERAPIE:
problem.setProcedere(text);
break;
}
if (isNew) {
reload();
problemsKTable.refresh();
}
}
}
public void setComparator(int col, int row){
if (row < problemsTableModel.getFixedHeaderRowCount()) {
int colIndex = col - problemsTableModel.getFixedHeaderColumnCount();
switch (colIndex) {
case DATUM:
comparator = DATE_COMPARATOR;
break;
case NUMMER:
comparator = NUMBER_COMPARATOR;
break;
case STATUS:
comparator = STATUS_COMPARATOR;
break;
}
}
}
public void setHighlightSelection(boolean highlight, boolean row){
this.highlightSelection = highlight;
this.highlightRow = row;
}
public boolean isHighlightSelection(){
return highlightSelection;
}
public boolean isHighlightRow(){
return highlightSelection && highlightRow;
}
}
class ProblemsTableColorProvider {
public Color getForegroundColor(int col, int row){
int rowIndex = row - problemsTableModel.getFixedHeaderRowCount();
Problem problem = problemsTableModel.getProblem(rowIndex);
if (problem != null && problem.getStatus() == Episode.ACTIVE) {
return Display.getCurrent().getSystemColor(SWT.COLOR_BLACK);
} else {
return Display.getCurrent().getSystemColor(SWT.COLOR_GRAY);
}
}
}
abstract class ProblemsTableCellRendererBase implements KTableCellRenderer {
protected Problem getSelectedProblem(){
Point[] selection = problemsKTable.getCellSelection();
if (selection == null || selection.length == 0) {
return null;
} else {
int rowIndex = selection[0].y - problemsTableModel.getFixedHeaderRowCount();
Problem problem = problemsTableModel.getProblem(rowIndex);
return problem;
}
}
protected boolean isSelected(int row){
if (problemsKTable.isRowSelectMode()) {
int[] selectedRows = problemsKTable.getRowSelection();
if (selectedRows != null) {
for (int r : selectedRows) {
if (r == row) {
return true;
}
}
}
} else {
Point[] selectedCells = problemsKTable.getCellSelection();
if (selectedCells != null) {
for (Point cell : selectedCells) {
if (cell.y == row) {
return true;
}
}
}
}
return false;
}
}
class ProblemsTableTextCellRenderer extends ProblemsTableCellRendererBase {
private final Display display;
public ProblemsTableTextCellRenderer(){
display = Display.getCurrent();
}
@Override
public int getOptimalWidth(GC gc, int col, int row, Object content, boolean fixed,
KTableModel model){
if (content instanceof String) {
String text = (String) content;
return gc.textExtent(text).x + 8;
} else {
return 0;
}
}
@Override
public void drawCell(GC gc, Rectangle rect, int col, int row, Object content,
boolean focus, boolean fixed, boolean clicked, KTableModel model){
Color textColor;
Color backColor;
Color borderColor;
String text;
if (content instanceof String) {
text = (String) content;
} else {
text = "";
}
if (focus) {
textColor = display.getSystemColor(SWT.COLOR_BLUE);
} else {
textColor = problemsTableColorProvider.getForegroundColor(col, row);
}
if (isSelected(row) && ((ProblemsTableModel) model).isHighlightRow()) {
backColor = highlightColor;
} else if (focus && ((ProblemsTableModel) model).isHighlightSelection()) {
backColor = highlightColor;
} else {
backColor = display.getSystemColor(SWT.COLOR_LIST_BACKGROUND);
}
borderColor = display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);
gc.setForeground(borderColor);
gc.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height);
gc.setForeground(borderColor);
gc.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height);
gc.setBackground(backColor);
gc.setForeground(textColor);
gc.fillRectangle(rect);
Rectangle oldClipping = gc.getClipping();
gc.setClipping(rect);
gc.drawText((text), rect.x + 3, rect.y);
gc.setClipping(oldClipping);
if (focus) {
gc.drawFocus(rect.x, rect.y, rect.width, rect.height);
}
}
}
class ProblemsTableImageCellRenderer extends ProblemsTableCellRendererBase {
private final Display display;
public ProblemsTableImageCellRenderer(){
display = Display.getCurrent();
}
@Override
public int getOptimalWidth(GC gc, int col, int row, Object content, boolean fixed,
KTableModel model){
if (content instanceof Image) {
Image image = (Image) content;
return image.getBounds().width;
} else {
return 0;
}
}
@Override
public void drawCell(GC gc, Rectangle rect, int col, int row, Object content,
boolean focus, boolean fixed, boolean clicked, KTableModel model){
Color backColor;
Color borderColor;
Image image = null;
if (content instanceof Image) {
image = (Image) content;
}
if (isSelected(row) && ((ProblemsTableModel) model).isHighlightRow()) {
backColor = highlightColor;
} else if (focus && ((ProblemsTableModel) model).isHighlightSelection()) {
backColor = highlightColor;
} else {
backColor = display.getSystemColor(SWT.COLOR_LIST_BACKGROUND);
}
borderColor = display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);
gc.setForeground(borderColor);
gc.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height);
gc.setForeground(borderColor);
gc.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height);
gc.setBackground(backColor);
gc.fillRectangle(rect);
if (image != null) {
// center image
Rectangle imageBounds = image.getBounds();
int imageWidth = imageBounds.width;
int imageHeight = imageBounds.height;
int xOffset = (rect.width - imageWidth) / 2;
int yOffset = (rect.height - imageHeight) / 2;
Rectangle oldClipping = gc.getClipping();
gc.setClipping(rect);
gc.drawImage(image, rect.x + xOffset, rect.y + yOffset);
gc.setClipping(oldClipping);
}
if (focus) {
gc.drawFocus(rect.x, rect.y, rect.width, rect.height);
}
}
}
/**
* Renderer for Therapy cell. Shows the procedere of the problem. If there are prescriptions,
* they are shown above the procedere, separated by a line.
*
* @author danlutz
*/
class ProblemsTableTherapyCellRenderer extends ProblemsTableCellRendererBase {
private static final int MARGIN = 8;
private static final int PADDING = 3;
private final Display display;
public ProblemsTableTherapyCellRenderer(){
display = Display.getCurrent();
}
private boolean hasPrescriptions(Problem problem){
List<Prescription> prescriptions = problem.getPrescriptions();
return (prescriptions.size() > 0);
}
private boolean hasProcedere(Problem problem){
if (!StringTool.isNothing(PersistentObject.checkNull(problem.getProcedere()))) {
return true;
} else {
return false;
}
}
private String getPrescriptionsText(Problem problem){
String prescriptions = PersistentObject.checkNull(problem.getPrescriptionsAsText());
String lineSeparator = System.getProperty("line.separator");
String prescriptionsText =
prescriptions.replaceAll(Problem.TEXT_SEPARATOR, lineSeparator);
return prescriptionsText;
}
private String getProcedereText(Problem problem){
return PersistentObject.checkNull(problem.getProcedere());
}
public int getOptimalHeight(GC gc, Problem problem){
int height = 0;
int prescriptionsHeight = 0;
if (hasPrescriptions(problem)) {
String prescriptionsText = getPrescriptionsText(problem);
prescriptionsHeight = gc.textExtent(prescriptionsText).y;
}
int procedereHeight = 0;
if (hasProcedere(problem)) {
String procedereText = getProcedereText(problem);
procedereHeight = gc.textExtent(procedereText).y;
}
if (prescriptionsHeight > 0 && procedereHeight > 0) {
height = prescriptionsHeight + PADDING + procedereHeight;
} else if (prescriptionsHeight > 0) {
height = prescriptionsHeight;
} else if (procedereHeight > 0) {
height = procedereHeight;
}
if (height == 0) {
// default height
height = gc.textExtent("").y;
}
return height;
}
@Override
public int getOptimalWidth(GC gc, int col, int row, Object content, boolean fixed,
KTableModel model){
if (content instanceof Problem) {
Problem problem = (Problem) content;
String prescriptionsText = getPrescriptionsText(problem);
String procedereText = getProcedereText(problem);
int width1 = gc.textExtent(prescriptionsText).x;
int width2 = gc.textExtent(procedereText).x;
int width = Math.max(width1, width2);
return width + MARGIN;
} else {
return 0;
}
}
@Override
public void drawCell(GC gc, Rectangle rect, int col, int row, Object content,
boolean focus, boolean fixed, boolean clicked, KTableModel model){
Color textColor;
Color backColor;
Color borderColor;
String prescriptionsText = "";
String procedereText = "";
boolean hasPrescriptions = false;
boolean hasProcedere = false;
if (content instanceof Problem) {
Problem problem = (Problem) content;
prescriptionsText = getPrescriptionsText(problem);
procedereText = getProcedereText(problem);
hasPrescriptions = hasPrescriptions(problem);
hasProcedere = hasProcedere(problem);
}
if (focus) {
textColor = display.getSystemColor(SWT.COLOR_BLUE);
} else {
textColor = problemsTableColorProvider.getForegroundColor(col, row);
}
if (isSelected(row) && ((ProblemsTableModel) model).isHighlightRow()) {
backColor = highlightColor;
} else if (focus && ((ProblemsTableModel) model).isHighlightSelection()) {
backColor = highlightColor;
} else {
backColor = display.getSystemColor(SWT.COLOR_LIST_BACKGROUND);
}
borderColor = display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);
gc.setForeground(borderColor);
gc.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height);
gc.setForeground(borderColor);
gc.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height);
gc.setBackground(backColor);
gc.setForeground(textColor);
gc.fillRectangle(rect);
Rectangle oldClipping = gc.getClipping();
gc.setClipping(rect);
if (hasPrescriptions && hasProcedere) {
// draw prescriptions and procedre, separated by a line
int prescriptionsHeight = gc.textExtent(prescriptionsText).y;
gc.setForeground(borderColor);
gc.drawLine(rect.x, rect.y + prescriptionsHeight + 1, rect.x + rect.width, rect.y
+ prescriptionsHeight + 1);
gc.setBackground(backColor);
gc.setForeground(textColor);
gc.drawText(prescriptionsText, rect.x + 3, rect.y);
gc.drawText(procedereText, rect.x + 3, rect.y + prescriptionsHeight + PADDING);
} else {
String text;
if (hasPrescriptions) {
// prescriptions only
text = prescriptionsText;
} else if (hasProcedere) {
// procedere only
text = procedereText;
} else {
// nothing
text = "";
}
gc.setBackground(backColor);
gc.setForeground(textColor);
gc.drawText(text, rect.x + 3, rect.y);
}
gc.setClipping(oldClipping);
if (focus) {
gc.drawFocus(rect.x, rect.y, rect.width, rect.height);
}
}
}
public class KTableTherapyCellEditor extends BaseCellEditor {
private Text m_Text;
private final KeyAdapter keyListener = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e){
try {
onKeyPressed(e);
} catch (Exception ex) {
// Do nothing
}
}
};
private final TraverseListener travListener = new TraverseListener() {
@Override
public void keyTraversed(TraverseEvent e){
onTraverse(e);
}
};
@Override
public void open(KTable table, int col, int row, Rectangle rect){
super.open(table, col, row, rect);
String text = "";
Object obj = m_Model.getContentAt(m_Col, m_Row);
if (obj instanceof Problem) {
Problem problem = (Problem) obj;
text = problem.getProcedere();
}
m_Text.setText(PersistentObject.checkNull(text));
m_Text.selectAll();
m_Text.setVisible(true);
m_Text.setFocus();
}
@Override
public void close(boolean save){
if (save)
m_Model.setContentAt(m_Col, m_Row, m_Text.getText());
m_Text.removeKeyListener(keyListener);
m_Text.removeTraverseListener(travListener);
m_Text = null;
super.close(save);
}
@Override
protected Control createControl(){
m_Text = new Text(m_Table, SWT.MULTI | SWT.V_SCROLL);
m_Text.addKeyListener(keyListener);
m_Text.addTraverseListener(travListener);
return m_Text;
}
/**
* Implement In-Textfield navigation with the keys...
*
* @see de.kupzog.ktable.KTableCellEditor#onTraverse(org.eclipse.swt.events.TraverseEvent)
*/
@Override
protected void onTraverse(TraverseEvent e){
if (e.keyCode == SWT.ARROW_LEFT) {
// handel the event within the text widget!
} else if (e.keyCode == SWT.ARROW_RIGHT) {
// handle the event within the text widget!
} else
super.onTraverse(e);
}
/*
* overridden from superclass
*/
@Override
public void setBounds(Rectangle rect){
super.setBounds(new Rectangle(rect.x, rect.y, rect.width, rect.height));
}
/*
* (non-Javadoc)
*
* @see de.kupzog.ktable.KTableCellEditor#setContent(java.lang.Object)
*/
@Override
public void setContent(Object content){
m_Text.setText(content.toString());
m_Text.setSelection(content.toString().length());
}
}
/**
* Base class for our cell editors Especially, we need to take care of heartbeat management
*/
abstract class BaseCellEditor extends KTableCellEditor {
@Override
public void open(KTable table, int col, int row, Rectangle rect){
setHeartbeatProblemEnabled(false);
super.open(table, col, row, rect);
}
@Override
public void close(boolean save){
super.close(save);
setHeartbeatProblemEnabled(true);
}
}
/**
* Replacement for KTableCellEditorText2 We don't want to have the editor vertically centered
*
* @author danlutz
*
*/
public class MyKTableCellEditorText2 extends BaseCellEditor {
protected Text m_Text;
protected KeyAdapter keyListener = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e){
try {
onKeyPressed(e);
} catch (Exception ex) {
ex.printStackTrace();
// Do nothing
}
}
};
protected TraverseListener travListener = new TraverseListener() {
@Override
public void keyTraversed(TraverseEvent e){
onTraverse(e);
}
};
@Override
public void open(KTable table, int col, int row, Rectangle rect){
super.open(table, col, row, rect);
m_Text.setText(m_Model.getContentAt(m_Col, m_Row).toString());
m_Text.selectAll();
m_Text.setVisible(true);
m_Text.setFocus();
}
@Override
public void close(boolean save){
if (save)
m_Model.setContentAt(m_Col, m_Row, m_Text.getText());
m_Text.removeKeyListener(keyListener);
m_Text.removeTraverseListener(travListener);
super.close(save);
m_Text = null;
}
@Override
protected Control createControl(){
m_Text = new Text(m_Table, SWT.NONE);
m_Text.addKeyListener(keyListener);
m_Text.addTraverseListener(travListener);
return m_Text;
}
/**
* Implement In-Textfield navigation with the keys...
*
* @see de.kupzog.ktable.KTableCellEditor#onTraverse(org.eclipse.swt.events.TraverseEvent)
*/
@Override
protected void onTraverse(TraverseEvent e){
if (e.keyCode == SWT.ARROW_LEFT) {
// handel the event within the text widget!
} else if (e.keyCode == SWT.ARROW_RIGHT) {
// handle the event within the text widget!
} else
super.onTraverse(e);
}
@Override
protected void onKeyPressed(KeyEvent e){
if ((e.character == '\r') && ((e.stateMask & SWT.SHIFT) == 0)) {
close(true);
// move one row below!
// if (m_Row<m_Model.getRowCount())
// m_Table.setSelection(m_Col, m_Row+1, true);
} else
super.onKeyPressed(e);
}
/*
* (non-Javadoc)
*
* @see de.kupzog.ktable.KTableCellEditor#setContent(java.lang.Object)
*/
@Override
public void setContent(Object content){
m_Text.setText(content.toString());
m_Text.setSelection(content.toString().length());
}
}
public class KTableDiagnosisCellEditor extends BaseCellEditor {
private Combo combo;
private final KeyAdapter keyListener = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e){
try {
onKeyPressed(e);
} catch (Exception ex) {
// Do nothing
}
}
};
private final TraverseListener travListener = new TraverseListener() {
@Override
public void keyTraversed(TraverseEvent e){
onTraverse(e);
}
};
@Override
public void open(KTable table, int col, int row, Rectangle rect){
super.open(table, col, row, rect);
String text = "";
Object obj = m_Model.getContentAt(m_Col, m_Row);
if (obj instanceof Problem) {
Problem problem = (Problem) obj;
text = "test";
}
combo.setText(text);
combo.setVisible(true);
combo.setFocus();
}
@Override
public void close(boolean save){
if (save)
m_Model.setContentAt(m_Col, m_Row, combo.getText());
combo.removeKeyListener(keyListener);
combo.removeTraverseListener(travListener);
combo = null;
super.close(save);
}
@Override
protected Control createControl(){
combo = new Combo(m_Table, SWT.DROP_DOWN);
combo.addKeyListener(keyListener);
combo.addTraverseListener(travListener);
return combo;
}
/**
* Implement In-Textfield navigation with the keys...
*
* @see de.kupzog.ktable.KTableCellEditor#onTraverse(org.eclipse.swt.events.TraverseEvent)
*/
@Override
protected void onTraverse(TraverseEvent e){
if (e.keyCode == SWT.ARROW_LEFT) {
// handel the event within the text widget!
} else if (e.keyCode == SWT.ARROW_RIGHT) {
// handle the event within the text widget!
} else
super.onTraverse(e);
}
/*
* overridden from superclass
*/
@Override
public void setBounds(Rectangle rect){
super.setBounds(new Rectangle(rect.x, rect.y, rect.width, rect.height));
}
/*
* (non-Javadoc)
*
* @see de.kupzog.ktable.KTableCellEditor#setContent(java.lang.Object)
*/
@Override
public void setContent(Object content){
combo.setText(content.toString());
}
}
class ProblemAssignmentLabelProvider extends LabelProvider implements ITableColorProvider {
@Override
public Color getForeground(Object element, int columnIndex){
Color color = null;
if (problemAssignmentViewer.getChecked(element)) {
color = Display.getCurrent().getSystemColor(SWT.COLOR_BLACK);
} else {
color = Display.getCurrent().getSystemColor(SWT.COLOR_GRAY);
}
return color;
}
@Override
public Color getBackground(Object element, int columnIndex){
// we don't set the background
return null;
}
}
static class DateComparator implements Comparator<Problem> {
@Override
public int compare(Problem o1, Problem o2){
if (o1 == null && o2 == null) {
return 0;
}
if (o1 == null) {
return 1;
}
if (o2 == null) {
return -1;
}
return PersistentObject.checkNull(o1.getStartDate()).compareTo(
PersistentObject.checkNull(o2.getStartDate()));
}
@Override
public boolean equals(Object obj){
return super.equals(obj);
}
}
static class NumberComparator implements Comparator<Problem> {
@Override
public int compare(Problem o1, Problem o2){
if (o1 == null && o2 == null) {
return 0;
}
if (o1 == null) {
return 1;
}
if (o2 == null) {
return -1;
}
return PersistentObject.checkNull(o1.getNumber()).compareTo(
PersistentObject.checkNull(o2.getNumber()));
}
@Override
public boolean equals(Object obj){
return super.equals(obj);
}
}
/**
* Compare by status. ACTIVE problems are sorted before INACTIVE problems. Problems with same
* status are sorted by date.
*
* @author danlutz
*/
static class StatusComparator implements Comparator<Problem> {
@Override
public int compare(Problem o1, Problem o2){
if (o1 == null && o2 == null) {
return 0;
}
if (o1 == null) {
return 1;
}
if (o2 == null) {
return -1;
}
int status1 = o1.getStatus();
int status2 = o2.getStatus();
if (status1 == status2) {
// same status, compare date
return PersistentObject.checkNull(o1.getStartDate()).compareTo(
PersistentObject.checkNull(o2.getStartDate()));
} else if (status1 == Episode.ACTIVE) {
return -1;
} else {
return 1;
}
}
@Override
public boolean equals(Object obj){
return super.equals(obj);
}
}
static class DummyProblem {}
// helper method to create a KonsTextLock object in a save way
// should be called when a new konsultation is set
private void createKonsTextLock(){
// remove old lock
removeKonsTextLock();
if (actKons != null && CoreHub.actUser != null) {
konsTextLock = new KonsTextLock(actKons, CoreHub.actUser);
} else {
konsTextLock = null;
}
if (konsTextLock != null) {
boolean success = konsTextLock.lock();
log.log("createKonsTextLock: konsText locked (" + success + ")", Log.DEBUGMSG);
// System.err.println("DEBUG: createKonsTextLock: konsText locked (" + success + ")");
}
}
// helper method to release a KonsTextLock
// should be called before a new konsultation is set
// or the program/view exits
private void removeKonsTextLock(){
if (konsTextLock != null) {
boolean success = konsTextLock.unlock();
log.log("removeKonsTextLock: konsText unlocked (" + success + ")", Log.DEBUGMSG);
// System.err.println("DEBUG: removeKonsTextLock: konsText unlocked (" + success + ")");
konsTextLock = null;
}
}
/**
* Check whether we own the lock
*
* @return true, if we own the lock, false else
*/
private boolean hasKonsTextLock(){
return (konsTextLock != null && konsTextLock.isLocked());
}
}
|
package ibis.ipl.impl.tcp;
import ibis.io.BufferedArrayInputStream;
import ibis.io.BufferedArrayOutputStream;
import ibis.ipl.AlreadyConnectedException;
import ibis.ipl.ConnectionRefusedException;
import ibis.ipl.ConnectionTimedOutException;
import ibis.ipl.IbisCapabilities;
import ibis.ipl.MessageUpcall;
import ibis.ipl.PortMismatchException;
import ibis.ipl.PortType;
import ibis.ipl.ReceivePortConnectUpcall;
import ibis.ipl.RegistryEventHandler;
import ibis.ipl.SendPortDisconnectUpcall;
import ibis.ipl.impl.IbisIdentifier;
import ibis.ipl.impl.ReceivePort;
import ibis.ipl.impl.SendPort;
import ibis.ipl.impl.SendPortIdentifier;
import ibis.util.ThreadPool;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Properties;
import org.apache.log4j.Logger;
public final class TcpIbis extends ibis.ipl.impl.Ibis
implements Runnable, TcpProtocol {
static final Logger logger
= Logger.getLogger("ibis.ipl.impl.tcp.TcpIbis");
private IbisSocketFactory factory;
private IbisServerSocket systemServer;
private IbisSocketAddress myAddress;
private boolean quiting = false;
private HashMap<ibis.ipl.IbisIdentifier, IbisSocketAddress> addresses
= new HashMap<ibis.ipl.IbisIdentifier, IbisSocketAddress>();
public TcpIbis(RegistryEventHandler registryEventHandler, IbisCapabilities capabilities, PortType[] types, Properties userProperties) {
super(registryEventHandler, capabilities, types, userProperties);
this.properties.checkProperties("ibis.ipl.impl.tcp.",
new String[] {"ibis.ipl.impl.tcp.smartsockets"}, null, true);
factory.setIdent(ident);
// Create a new accept thread
ThreadPool.createNew(this, "TcpIbis Accept Thread");
}
protected byte[] getData() throws IOException {
factory = new IbisSocketFactory(properties);
systemServer = factory.createServerSocket(0, 50, true, null);
myAddress = systemServer.getLocalSocketAddress();
if (logger.isDebugEnabled()) {
logger.debug("--> TcpIbis: address = " + myAddress);
}
return myAddress.toBytes();
}
/*
// NOTE: this is wrong ? Even though the ibis has left, the IbisIdentifier
may still be floating around in the system... We should just have
some timeout on the cache entries instead...
public void left(ibis.ipl.IbisIdentifier id) {
super.left(id);
synchronized(addresses) {
addresses.remove(id);
}
}
public void died(ibis.ipl.IbisIdentifier id) {
super.died(id);
synchronized(addresses) {
addresses.remove(id);
}
}
*/
IbisSocket connect(TcpSendPort sp, ibis.ipl.impl.ReceivePortIdentifier rip,
int timeout, boolean fillTimeout) throws IOException {
IbisIdentifier id = (IbisIdentifier) rip.ibisIdentifier();
String name = rip.name();
IbisSocketAddress idAddr;
synchronized(addresses) {
idAddr = addresses.get(id);
if (idAddr == null) {
idAddr = new IbisSocketAddress(id.getImplementationData());
addresses.put(id, idAddr);
}
}
long startTime = System.currentTimeMillis();
if (logger.isDebugEnabled()) {
logger.debug("--> Creating socket for connection to " + name
+ " at " + idAddr);
}
do {
DataOutputStream out = null;
IbisSocket s = null;
int result = -1;
try {
s = factory.createClientSocket(idAddr, timeout, fillTimeout,
sp.dynamicProperties());
s.setTcpNoDelay(true);
out = new DataOutputStream(new BufferedArrayOutputStream(
s.getOutputStream(), 4096));
out.writeUTF(name);
sp.getIdent().writeTo(out);
sp.getPortType().writeTo(out);
out.flush();
result = s.getInputStream().read();
switch(result) {
case ReceivePort.ACCEPTED:
return s;
case ReceivePort.ALREADY_CONNECTED:
throw new AlreadyConnectedException("Already connected", rip);
case ReceivePort.TYPE_MISMATCH:
throw new PortMismatchException(
"Cannot connect ports of different port types", rip);
case ReceivePort.DENIED:
throw new ConnectionRefusedException(
"Receiver denied connection", rip);
case ReceivePort.NO_MANYTOONE:
throw new ConnectionRefusedException(
"Receiver already has a connection and ManyToOne "
+ "is not set", rip);
case ReceivePort.NOT_PRESENT:
case ReceivePort.DISABLED:
// and try again if we did not reach the timeout...
if (timeout > 0 && System.currentTimeMillis()
> startTime + timeout) {
throw new ConnectionTimedOutException(
"Could not connect", rip);
}
break;
case -1:
throw new IOException("Encountered EOF in TcpIbis.connect");
default:
throw new IOException("Illegal opcode in TcpIbis.connect");
}
} catch(SocketTimeoutException e) {
throw new ConnectionTimedOutException("Could not connect", rip);
} finally {
if (result != ReceivePort.ACCEPTED) {
try {
out.close();
} catch(Throwable e) {
// ignored
}
try {
s.close();
} catch(Throwable e) {
// ignored
}
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// ignore
}
} while (true);
}
protected void quit() {
try {
quiting = true;
// Connect so that the TcpIbis thread wakes up.
factory.createClientSocket(myAddress, 0, false, null);
} catch (Throwable e) {
// Ignore
}
}
private void handleConnectionRequest(IbisSocket s) throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("--> TcpIbis got connection request from " + s);
}
BufferedArrayInputStream bais
= new BufferedArrayInputStream(s.getInputStream(), 4096);
DataInputStream in = new DataInputStream(bais);
OutputStream out = s.getOutputStream();
String name = in.readUTF();
SendPortIdentifier send = new SendPortIdentifier(in);
PortType sp = new PortType(in);
// First, lookup receiveport.
TcpReceivePort rp = (TcpReceivePort) findReceivePort(name);
int result;
if (rp == null) {
result = ReceivePort.NOT_PRESENT;
} else {
result = rp.connectionAllowed(send, sp);
}
if (logger.isDebugEnabled()) {
logger.debug("--> S RP = " + name + ": "
+ ReceivePort.getString(result));
}
out.write(result);
out.flush();
if (result == ReceivePort.ACCEPTED) {
// add the connection to the receiveport.
rp.connect(send, s, bais);
if (logger.isDebugEnabled()) {
logger.debug("--> S connect done ");
}
} else {
out.close();
in.close();
s.close();
}
}
public void run() {
// This thread handles incoming connection request from the
// connect(TcpSendPort) call.
boolean stop = false;
while (!stop) {
IbisSocket s = null;
if (logger.isDebugEnabled()) {
logger.debug("--> TcpIbis doing new accept()");
}
try {
s = systemServer.accept();
s.setTcpNoDelay(true);
} catch (Throwable e) {
/* if the accept itself fails, we have a fatal problem. */
logger.fatal("TcpIbis:run: got fatal exception in accept! ", e);
cleanup();
throw new Error("Fatal: TcpIbis could not do an accept", e);
// This error is thrown in the TcpIbis thread, not in a user
// thread. It kills the thread.
}
if (logger.isDebugEnabled()) {
logger.debug("--> TcpIbis through new accept()");
}
try {
if (quiting) {
s.close();
if (logger.isDebugEnabled()) {
logger.debug("--> it is a quit: RETURN");
}
cleanup();
return;
}
// This thread will now live on as a connection handler. Start
// a new accept thread here, and make sure that this thread does
// not do an accept again, if it ever returns to this loop.
stop = true;
try {
Thread.currentThread().setName("Connection Handler");
} catch (Exception e) {
// ignore
}
ThreadPool.createNew(this, "TcpIbis Accept Thread");
// Try to get the accept thread into an accept call. (Ceriel)
// Thread.currentThread().yield();
// Yield is evil. It breaks the whole concept of starting a
// replacement thread and handling the incoming request
// ourselves. -- Jason
handleConnectionRequest(s);
} catch (Throwable e) {
try {
s.close();
} catch(Throwable e2) {
// ignored
}
logger.error("EEK: TcpIbis:run: got exception "
+ "(closing this socket only: ", e);
}
}
}
public void printStatistics() {
factory.printStatistics(ident.toString());
}
private void cleanup() {
try {
systemServer.close();
} catch (Throwable e) {
// Ignore
}
}
public void end() throws IOException {
super.end();
printStatistics();
}
protected SendPort doCreateSendPort(PortType tp, String nm,
SendPortDisconnectUpcall cU, Properties props) throws IOException {
return new TcpSendPort(this, tp, nm, cU, props);
}
protected ReceivePort doCreateReceivePort(PortType tp, String nm,
MessageUpcall u, ReceivePortConnectUpcall cU, Properties props)
throws IOException {
return new TcpReceivePort(this, tp, nm, u, cU, props);
}
}
|
package com.jme3.scene;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.InputCapsule;
import com.jme3.export.OutputCapsule;
import com.jme3.export.Savable;
import com.jme3.math.FastMath;
import com.jme3.renderer.GLObject;
import com.jme3.renderer.Renderer;
import com.jme3.util.BufferUtils;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
/**
* A <code>VertexBuffer</code> contains a particular type of geometry
* data used by {@link Mesh}es. Every VertexBuffer set on a <code>Mesh</code>
* is sent as an attribute to the vertex shader to be processed.
*/
public class VertexBuffer extends GLObject implements Savable, Cloneable {
/**
* Type of buffer. Specifies the actual attribute it defines.
*/
public static enum Type {
/**
* Position of the vertex (3 floats)
*/
Position,
/**
* The size of the point when using point buffers.
*/
Size,
/**
* Normal vector, normalized.
*/
Normal,
/**
* Texture coordinate
*/
TexCoord,
/**
* Color and Alpha (4 floats)
*/
Color,
/**
* Tangent vector, normalized.
*/
Tangent,
/**
* Binormal vector, normalized.
*/
Binormal,
/**
* Specifies the source data for various vertex buffers
* when interleaving is used.
*/
InterleavedData,
/**
* Do not use.
*/
@Deprecated
MiscAttrib,
/**
* Specifies the index buffer, must contain integer data.
*/
Index,
/**
* Inital vertex position, used with animation
*/
BindPosePosition,
/**
* Inital vertex normals, used with animation
*/
BindPoseNormal,
/**
* Bone weights, used with animation
*/
BoneWeight,
/**
* Bone indices, used with animation
*/
BoneIndex,
/**
* Texture coordinate #2
*/
TexCoord2,
/**
* Texture coordinate #3
*/
TexCoord3,
/**
* Texture coordinate #4
*/
TexCoord4,
/**
* Texture coordinate #5
*/
TexCoord5,
/**
* Texture coordinate #6
*/
TexCoord6,
/**
* Texture coordinate #7
*/
TexCoord7,
/**
* Texture coordinate #8
*/
TexCoord8,
}
/**
* The usage of the VertexBuffer, specifies how often the buffer
* is used. This can determine if a vertex buffer is placed in VRAM
* or held in video memory, but no guarantees are made- it's only a hint.
*/
public static enum Usage {
/**
* Mesh data is sent once and very rarely updated.
*/
Static,
/**
* Mesh data is updated occasionally (once per frame or less).
*/
Dynamic,
/**
* Mesh data is updated every frame.
*/
Stream,
/**
* Mesh data is not sent to GPU at all. It is only
* used by the CPU.
*/
CpuOnly;
}
public static enum Format {
// Floating point formats
Half(2),
Float(4),
Double(8),
// Integer formats
Byte(1),
UnsignedByte(1),
Short(2),
UnsignedShort(2),
Int(4),
UnsignedInt(4);
private int componentSize = 0;
Format(int componentSize){
this.componentSize = componentSize;
}
/**
* @return Size in bytes of this data type.
*/
public int getComponentSize(){
return componentSize;
}
}
protected int offset = 0;
protected int lastLimit = 0;
protected int stride = 0;
protected int components = 0;
/**
* derived from components * format.getComponentSize()
*/
protected transient int componentsLength = 0;
protected Buffer data = null;
protected Usage usage;
protected Type bufType;
protected Format format;
protected boolean normalized = false;
protected transient boolean dataSizeChanged = false;
/**
* Creates an empty, uninitialized buffer.
* Must call setupData() to initialize.
*/
public VertexBuffer(Type type){
super(GLObject.Type.VertexBuffer);
this.bufType = type;
}
/**
* Do not use this constructor. Serialization purposes only.
*/
public VertexBuffer(){
super(GLObject.Type.VertexBuffer);
}
protected VertexBuffer(int id){
super(GLObject.Type.VertexBuffer, id);
}
/**
* @return The offset (in bytes) from the start of the buffer
* after which the data is sent to the GPU.
*/
public int getOffset() {
return offset;
}
/**
* @param offset Specify the offset (in bytes) from the start of the buffer
* after which the data is sent to the GPU.
*/
public void setOffset(int offset) {
this.offset = offset;
}
/**
* @return The stride (in bytes) for the data. If the data is packed
* in the buffer, then stride is 0, if there's other data that is between
* the current component and the next component in the buffer, then this
* specifies the size in bytes of that additional data.
*/
public int getStride() {
return stride;
}
/**
* @param stride The stride (in bytes) for the data. If the data is packed
* in the buffer, then stride is 0, if there's other data that is between
* the current component and the next component in the buffer, then this
* specifies the size in bytes of that additional data.
*/
public void setStride(int stride) {
this.stride = stride;
}
/**
* @return A native buffer, in the specified {@link Format format}.
*/
public Buffer getData(){
return data;
}
/**
* @return The usage of this buffer. See {@link Usage} for more
* information.
*/
public Usage getUsage(){
return usage;
}
/**
* @param usage The usage of this buffer. See {@link Usage} for more
* information.
*/
public void setUsage(Usage usage){
// if (id != -1)
// throw new UnsupportedOperationException("Data has already been sent. Cannot set usage.");
this.usage = usage;
}
/**
* @param normalized Set to true if integer components should be converted
* from their maximal range into the range 0.0 - 1.0 when converted to
* a floating-point value for the shader.
* E.g. if the {@link Format} is {@link Format#UnsignedInt}, then
* the components will be converted to the range 0.0 - 1.0 by dividing
* every integer by 2^32.
*/
public void setNormalized(boolean normalized){
this.normalized = normalized;
}
/**
* @return True if integer components should be converted to the range 0-1.
* @see VertexBuffer#setNormalized(boolean)
*/
public boolean isNormalized(){
return normalized;
}
/**
* @return The type of information that this buffer has.
*/
public Type getBufferType(){
return bufType;
}
/**
* @return The {@link Format format}, or data type of the data.
*/
public Format getFormat(){
return format;
}
/**
* @return The number of components of the given {@link Format format} per
* element.
*/
public int getNumComponents(){
return components;
}
/**
* @return The total number of data elements in the data buffer.
*/
public int getNumElements(){
int elements = data.capacity() / components;
if (format == Format.Half)
elements /= 2;
return elements;
}
/**
* Called to initialize the data in the <code>VertexBuffer</code>. Must only
* be called once.
*
* @param usage The usage for the data, or how often will the data
* be updated per frame. See the {@link Usage} enum.
* @param components The number of components per element.
* @param format The {@link Format format}, or data-type of a single
* component.
* @param data A native buffer, the format of which matches the {@link Format}
* argument.
*/
public void setupData(Usage usage, int components, Format format, Buffer data){
if (id != -1)
throw new UnsupportedOperationException("Data has already been sent. Cannot setupData again.");
if (usage == null || format == null || data == null)
throw new IllegalArgumentException("None of the arguments can be null");
if (components < 1 || components > 4)
throw new IllegalArgumentException("components must be between 1 and 4");
this.data = data;
this.components = components;
this.usage = usage;
this.format = format;
this.componentsLength = components * format.getComponentSize();
this.lastLimit = data.limit();
setUpdateNeeded();
}
/**
* Called to update the data in the buffer with new data. Can only
* be called after {@link VertexBuffer#setupData(com.jme3.scene.VertexBuffer.Usage, int, com.jme3.scene.VertexBuffer.Format, java.nio.Buffer) }
* has been called. Note that it is fine to call this method on the
* data already set, e.g. vb.updateData(vb.getData()), this will just
* set the proper update flag indicating the data should be sent to the GPU
* again.
* It is allowed to specify a buffer with different capacity than the
* originally set buffer.
*
* @param data The data buffer to set
*/
public void updateData(Buffer data){
if (id != -1){
// request to update data is okay
}
// will force renderer to call glBufferData again
if (this.data.getClass() != data.getClass() || data.limit() != lastLimit){
dataSizeChanged = true;
lastLimit = data.limit();
}
this.data = data;
setUpdateNeeded();
}
public boolean hasDataSizeChanged() {
return dataSizeChanged;
}
@Override
public void clearUpdateNeeded(){
super.clearUpdateNeeded();
dataSizeChanged = false;
}
/**
* Converts single floating-point data to {@link Format#Half half} floating-point data.
*/
public void convertToHalf(){
if (id != -1)
throw new UnsupportedOperationException("Data has already been sent.");
if (format != Format.Float)
throw new IllegalStateException("Format must be float!");
int numElements = data.capacity() / components;
format = Format.Half;
this.componentsLength = components * format.getComponentSize();
ByteBuffer halfData = BufferUtils.createByteBuffer(componentsLength * numElements);
halfData.rewind();
FloatBuffer floatData = (FloatBuffer) data;
floatData.rewind();
for (int i = 0; i < floatData.capacity(); i++){
float f = floatData.get(i);
short half = FastMath.convertFloatToHalf(f);
halfData.putShort(half);
}
this.data = halfData;
setUpdateNeeded();
dataSizeChanged = true;
}
/**
* Reduces the capacity of the buffer to the given amount
* of elements, any elements at the end of the buffer are truncated
* as necessary.
*
* @param numElements
*/
public void compact(int numElements){
int total = components * numElements;
data.clear();
switch (format){
case Byte:
case UnsignedByte:
case Half:
ByteBuffer bbuf = (ByteBuffer) data;
bbuf.limit(total);
ByteBuffer bnewBuf = BufferUtils.createByteBuffer(total);
bnewBuf.put(bbuf);
data = bnewBuf;
break;
case Short:
case UnsignedShort:
ShortBuffer sbuf = (ShortBuffer) data;
sbuf.limit(total);
ShortBuffer snewBuf = BufferUtils.createShortBuffer(total);
snewBuf.put(sbuf);
data = snewBuf;
break;
case Int:
case UnsignedInt:
IntBuffer ibuf = (IntBuffer) data;
ibuf.limit(total);
IntBuffer inewBuf = BufferUtils.createIntBuffer(total);
inewBuf.put(ibuf);
data = inewBuf;
break;
case Float:
FloatBuffer fbuf = (FloatBuffer) data;
fbuf.limit(total);
FloatBuffer fnewBuf = BufferUtils.createFloatBuffer(total);
fnewBuf.put(fbuf);
data = fnewBuf;
break;
default:
throw new UnsupportedOperationException("Unrecognized buffer format: "+format);
}
data.clear();
setUpdateNeeded();
dataSizeChanged = true;
}
public void setElementComponent(int elementIndex, int componentIndex, Object val){
int inPos = elementIndex * components;
int elementPos = componentIndex;
if (format == Format.Half){
inPos *= 2;
elementPos *= 2;
}
data.clear();
switch (format){
case Byte:
case UnsignedByte:
case Half:
ByteBuffer bin = (ByteBuffer) data;
bin.put(inPos + elementPos, (Byte)val);
break;
case Short:
case UnsignedShort:
ShortBuffer sin = (ShortBuffer) data;
sin.put(inPos + elementPos, (Short)val);
break;
case Int:
case UnsignedInt:
IntBuffer iin = (IntBuffer) data;
iin.put(inPos + elementPos, (Integer)val);
break;
case Float:
FloatBuffer fin = (FloatBuffer) data;
fin.put(inPos + elementPos, (Float)val);
break;
default:
throw new UnsupportedOperationException("Unrecognized buffer format: "+format);
}
}
public Object getElementComponent(int elementIndex, int componentIndex){
int inPos = elementIndex * components;
int elementPos = componentIndex;
if (format == Format.Half){
inPos *= 2;
elementPos *= 2;
}
data.clear();
switch (format){
case Byte:
case UnsignedByte:
case Half:
ByteBuffer bin = (ByteBuffer) data;
return bin.get(inPos + elementPos);
case Short:
case UnsignedShort:
ShortBuffer sin = (ShortBuffer) data;
return sin.get(inPos + elementPos);
case Int:
case UnsignedInt:
IntBuffer iin = (IntBuffer) data;
return iin.get(inPos + elementPos);
case Float:
FloatBuffer fin = (FloatBuffer) data;
return fin.get(inPos + elementPos);
default:
throw new UnsupportedOperationException("Unrecognized buffer format: "+format);
}
}
/**
* Copies a single element of data from this <code>VertexBuffer</code>
* to the given output VertexBuffer.
*
* @param inIndex
* @param outVb
* @param outIndex
*/
public void copyElement(int inIndex, VertexBuffer outVb, int outIndex){
if (outVb.format != format || outVb.components != components)
throw new IllegalArgumentException("Buffer format mismatch. Cannot copy");
int inPos = inIndex * components;
int outPos = outIndex * components;
int elementSz = components;
if (format == Format.Half){
// because half is stored as bytebuf but its 2 bytes long
inPos *= 2;
outPos *= 2;
elementSz *= 2;
}
data.clear();
outVb.data.clear();
switch (format){
case Byte:
case UnsignedByte:
case Half:
ByteBuffer bin = (ByteBuffer) data;
ByteBuffer bout = (ByteBuffer) outVb.data;
bin.position(inPos).limit(inPos + elementSz);
bout.position(outPos).limit(outPos + elementSz);
bout.put(bin);
break;
case Short:
case UnsignedShort:
ShortBuffer sin = (ShortBuffer) data;
ShortBuffer sout = (ShortBuffer) outVb.data;
sin.position(inPos).limit(inPos + elementSz);
sout.position(outPos).limit(outPos + elementSz);
sout.put(sin);
break;
case Int:
case UnsignedInt:
IntBuffer iin = (IntBuffer) data;
IntBuffer iout = (IntBuffer) outVb.data;
iin.position(inPos).limit(inPos + elementSz);
iout.position(outPos).limit(outPos + elementSz);
iout.put(iin);
break;
case Float:
FloatBuffer fin = (FloatBuffer) data;
FloatBuffer fout = (FloatBuffer) outVb.data;
fin.position(inPos).limit(inPos + elementSz);
fout.position(outPos).limit(outPos + elementSz);
fout.put(fin);
break;
default:
throw new UnsupportedOperationException("Unrecognized buffer format: "+format);
}
data.clear();
outVb.data.clear();
}
/**
* Creates a {@link Buffer} that satisfies the given type and size requirements
* of the parameters. The buffer will be of the type specified by
* {@link Format format} and would be able to contain the given number
* of elements with the given number of components in each element.
*
* @param format
* @param components
* @param numElements
* @return
*/
public static Buffer createBuffer(Format format, int components, int numElements){
if (components < 1 || components > 4)
throw new IllegalArgumentException("Num components must be between 1 and 4");
int total = numElements * components;
switch (format){
case Byte:
case UnsignedByte:
return BufferUtils.createByteBuffer(total);
case Half:
return BufferUtils.createByteBuffer(total * 2);
case Short:
case UnsignedShort:
return BufferUtils.createShortBuffer(total);
case Int:
case UnsignedInt:
return BufferUtils.createIntBuffer(total);
case Float:
return BufferUtils.createFloatBuffer(total);
case Double:
return BufferUtils.createDoubleBuffer(total);
default:
throw new UnsupportedOperationException("Unrecoginized buffer format: "+format);
}
}
@Override
public VertexBuffer clone(){
// NOTE: Superclass GLObject automatically creates shallow clone
// e.g re-use ID.
VertexBuffer vb = (VertexBuffer) super.clone();
vb.handleRef = new Object();
vb.id = -1;
if (data != null)
vb.updateData(BufferUtils.clone(data));
return vb;
}
public VertexBuffer clone(Type overrideType){
VertexBuffer vb = new VertexBuffer(overrideType);
vb.components = components;
vb.componentsLength = componentsLength;
vb.data = BufferUtils.clone(data);
vb.format = format;
vb.handleRef = new Object();
vb.id = -1;
vb.normalized = normalized;
vb.offset = offset;
vb.stride = stride;
vb.updateNeeded = true;
vb.usage = usage;
return vb;
}
@Override
public String toString(){
String dataTxt = null;
if (data != null){
dataTxt = ", elements="+data.capacity();
}
return getClass().getSimpleName() + "[fmt="+format.name()
+", type="+bufType.name()
+", usage="+usage.name()
+dataTxt+"]";
}
@Override
public void resetObject() {
// assert this.id != -1;
this.id = -1;
setUpdateNeeded();
}
@Override
public void deleteObject(Renderer r) {
r.deleteBuffer(this);
}
@Override
public GLObject createDestructableClone(){
return new VertexBuffer(id);
}
public void write(JmeExporter ex) throws IOException {
OutputCapsule oc = ex.getCapsule(this);
oc.write(components, "components", 0);
oc.write(usage, "usage", Usage.Dynamic);
oc.write(bufType, "buffer_type", null);
oc.write(format, "format", Format.Float);
oc.write(normalized, "normalized", false);
oc.write(offset, "offset", 0);
oc.write(stride, "stride", 0);
String dataName = "data" + format.name();
switch (format){
case Float:
oc.write((FloatBuffer) data, dataName, null);
break;
case Short:
case UnsignedShort:
oc.write((ShortBuffer) data, dataName, null);
break;
case UnsignedByte:
case Byte:
case Half:
oc.write((ByteBuffer) data, dataName, null);
break;
case Int:
case UnsignedInt:
oc.write((IntBuffer) data, dataName, null);
break;
default:
throw new IOException("Unsupported export buffer format: "+format);
}
}
public void read(JmeImporter im) throws IOException {
InputCapsule ic = im.getCapsule(this);
components = ic.readInt("components", 0);
usage = ic.readEnum("usage", Usage.class, Usage.Dynamic);
bufType = ic.readEnum("buffer_type", Type.class, null);
format = ic.readEnum("format", Format.class, Format.Float);
normalized = ic.readBoolean("normalized", false);
offset = ic.readInt("offset", 0);
stride = ic.readInt("stride", 0);
componentsLength = components * format.getComponentSize();
String dataName = "data" + format.name();
switch (format){
case Float:
data = ic.readFloatBuffer(dataName, null);
break;
case Short:
case UnsignedShort:
data = ic.readShortBuffer(dataName, null);
break;
case UnsignedByte:
case Byte:
case Half:
data = ic.readByteBuffer(dataName, null);
break;
case Int:
case UnsignedInt:
data = ic.readIntBuffer(dataName, null);
break;
default:
throw new IOException("Unsupported import buffer format: "+format);
}
}
}
|
package nxt.http;
import nxt.Currency;
import nxt.NxtException;
import nxt.util.Convert;
import org.json.simple.JSONStreamAware;
import javax.servlet.http.HttpServletRequest;
import static nxt.http.JSONResponses.MISSING_CURRENCY;
import static nxt.http.JSONResponses.UNKNOWN_CURRENCY;
public final class GetCurrency extends APIServlet.APIRequestHandler {
static final GetCurrency instance = new GetCurrency();
private GetCurrency() {
super(new APITag[] {APITag.MS}, "currency", "code", "includeCounts");
}
@Override
JSONStreamAware processRequest(HttpServletRequest req) throws NxtException {
boolean includeCounts = !"false".equalsIgnoreCase(req.getParameter("includeCounts"));
String currencyValue = Convert.emptyToNull(req.getParameter("currency"));
Currency currency;
if (currencyValue == null) {
String currencyCode = Convert.emptyToNull(req.getParameter("code"));
if (currencyCode == null) {
return MISSING_CURRENCY;
}
currency = Currency.getCurrencyByCode(currencyCode);
} else {
currency = ParameterParser.getCurrency(req);
}
if (currency == null) {
throw new ParameterException(UNKNOWN_CURRENCY);
}
return JSONData.currency(currency, includeCounts);
}
}
|
package com.triggertrap.seekarc;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
/**
*
* SeekArc.java
*
* This is a class that functions much like a SeekBar but
* follows a circle path instead of a straight line.
*
* @author Neil Davies
*
*/
public class SeekArc extends View {
private static final String TAG = SeekArc.class.getSimpleName();
private static int INVALID_PROGRESS_VALUE = -1;
// The initial rotational offset -90 means we start at 12 o'clock
private final int mAngleOffset = -90;
/**
* The Drawable for the seek arc thumbnail
*/
private Drawable mThumb;
/**
* The Maximum value that this SeekArc can be set to
*/
private int mMax = 100;
/**
* The Current value that the SeekArc is set to
*/
private int mProgress = 0;
/**
* The width of the progress line for this SeekArc
*/
private int mProgressWidth = 4;
/**
* The Width of the background arc for the SeekArc
*/
private int mArcWidth = 2;
/**
* The Angle to start drawing this Arc from
*/
private int mStartAngle = 0;
/**
* The Angle through which to draw the arc (Max is 360)
*/
private int mSweepAngle = 360;
/**
* The rotation of the SeekArc- 0 is twelve o'clock
*/
private int mRotation = 0;
/**
* Give the SeekArc rounded edges
*/
private boolean mRoundedEdges = false;
/**
* Enable touch inside the SeekArc
*/
private boolean mTouchInside = true;
/**
* Will the progress increase clockwise or anti-clockwise
*/
private boolean mClockwise = true;
/**
* is the control enabled/touchable
*/
private boolean mEnabled = true;
// Internal variables
private int mArcRadius = 0;
private float mProgressSweep = 0;
private RectF mArcRect = new RectF();
private Paint mArcPaint;
private Paint mProgressPaint;
private int mTranslateX;
private int mTranslateY;
private int mThumbXPos;
private int mThumbYPos;
private double mTouchAngle;
private float mTouchIgnoreRadius;
private OnSeekArcChangeListener mOnSeekArcChangeListener;
public interface OnSeekArcChangeListener {
/**
* Notification that the progress level has changed. Clients can use the
* fromUser parameter to distinguish user-initiated changes from those
* that occurred programmatically.
*
* @param seekArc
* The SeekArc whose progress has changed
* @param progress
* The current progress level. This will be in the range
* 0..max where max was set by
* {@link SeekArc#setMax(int)}. (The default value for
* max is 100.)
* @param fromUser
* True if the progress change was initiated by the user.
*/
void onProgressChanged(SeekArc seekArc, int progress, boolean fromUser);
/**
* Notification that the user has started a touch gesture. Clients may
* want to use this to disable advancing the seekbar.
*
* @param seekArc
* The SeekArc in which the touch gesture began
*/
void onStartTrackingTouch(SeekArc seekArc);
/**
* Notification that the user has finished a touch gesture. Clients may
* want to use this to re-enable advancing the seekarc.
*
* @param seekArc
* The SeekArc in which the touch gesture began
*/
void onStopTrackingTouch(SeekArc seekArc);
}
public SeekArc(Context context) {
super(context);
init(context, null, 0);
}
public SeekArc(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, R.attr.seekArcStyle);
}
public SeekArc(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
Log.d(TAG, "Initialising SeekArc");
float density = context.getResources().getDisplayMetrics().density;
// Defaults, may need to link this into theme settings
int arcColor = ContextCompat.getColor(context, R.color.progress_gray);
int progressColor = ContextCompat.getColor(context, R.color.default_blue_light);
int thumbHalfheight;
int thumbHalfWidth;
mThumb = ContextCompat.getDrawable(context, R.drawable.seek_arc_control_selector);
// Convert progress width to pixels for current density
mProgressWidth = (int) (mProgressWidth * density);
if (attrs != null) {
// Attribute initialization
final TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.SeekArc, defStyle, 0);
Drawable thumb = a.getDrawable(R.styleable.SeekArc_thumb);
if (thumb != null) {
mThumb = thumb;
}
thumbHalfheight = mThumb.getIntrinsicHeight() / 2;
thumbHalfWidth = mThumb.getIntrinsicWidth() / 2;
mThumb.setBounds(-thumbHalfWidth, -thumbHalfheight, thumbHalfWidth,
thumbHalfheight);
mMax = a.getInteger(R.styleable.SeekArc_max, mMax);
mProgress = a.getInteger(R.styleable.SeekArc_progress, mProgress);
mProgressWidth = (int) a.getDimension(
R.styleable.SeekArc_progressWidth, mProgressWidth);
mArcWidth = (int) a.getDimension(R.styleable.SeekArc_arcWidth,
mArcWidth);
mStartAngle = a.getInt(R.styleable.SeekArc_startAngle, mStartAngle);
mSweepAngle = a.getInt(R.styleable.SeekArc_sweepAngle, mSweepAngle);
mRotation = a.getInt(R.styleable.SeekArc_rotation, mRotation);
mRoundedEdges = a.getBoolean(R.styleable.SeekArc_roundEdges,
mRoundedEdges);
mTouchInside = a.getBoolean(R.styleable.SeekArc_touchInside,
mTouchInside);
mClockwise = a.getBoolean(R.styleable.SeekArc_clockwise,
mClockwise);
mEnabled = a.getBoolean(R.styleable.SeekArc_enabled, mEnabled);
arcColor = a.getColor(R.styleable.SeekArc_arcColor, arcColor);
progressColor = a.getColor(R.styleable.SeekArc_progressColor,
progressColor);
a.recycle();
}
mProgress = (mProgress > mMax) ? mMax : mProgress;
mProgress = (mProgress < 0) ? 0 : mProgress;
mSweepAngle = (mSweepAngle > 360) ? 360 : mSweepAngle;
mSweepAngle = (mSweepAngle < 0) ? 0 : mSweepAngle;
mProgressSweep = (float) mProgress / mMax * mSweepAngle;
mStartAngle = (mStartAngle > 360) ? 0 : mStartAngle;
mStartAngle = (mStartAngle < 0) ? 0 : mStartAngle;
mArcPaint = new Paint();
mArcPaint.setColor(arcColor);
mArcPaint.setAntiAlias(true);
mArcPaint.setStyle(Paint.Style.STROKE);
mArcPaint.setStrokeWidth(mArcWidth);
//mArcPaint.setAlpha(45);
mProgressPaint = new Paint();
mProgressPaint.setColor(progressColor);
mProgressPaint.setAntiAlias(true);
mProgressPaint.setStyle(Paint.Style.STROKE);
mProgressPaint.setStrokeWidth(mProgressWidth);
if (mRoundedEdges) {
mArcPaint.setStrokeCap(Paint.Cap.ROUND);
mProgressPaint.setStrokeCap(Paint.Cap.ROUND);
}
}
@Override
protected void onDraw(Canvas canvas) {
if(!mClockwise) {
canvas.scale(-1, 1, mArcRect.centerX(), mArcRect.centerY() );
}
// Draw the arcs
final int arcStart = mStartAngle + mAngleOffset + mRotation;
final int arcSweep = mSweepAngle;
canvas.drawArc(mArcRect, arcStart, arcSweep, false, mArcPaint);
canvas.drawArc(mArcRect, arcStart, mProgressSweep, false,
mProgressPaint);
if(mEnabled) {
// Draw the thumb nail
canvas.translate(mTranslateX - mThumbXPos, mTranslateY - mThumbYPos);
mThumb.draw(canvas);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int height = getDefaultSize(getSuggestedMinimumHeight(),
heightMeasureSpec);
final int width = getDefaultSize(getSuggestedMinimumWidth(),
widthMeasureSpec);
final int min = Math.min(width, height);
float top;
float left;
int arcDiameter;
mTranslateX = (int) (width * 0.5f);
mTranslateY = (int) (height * 0.5f);
arcDiameter = min - getPaddingLeft();
mArcRadius = arcDiameter / 2;
top = height / 2 - (arcDiameter / 2);
left = width / 2 - (arcDiameter / 2);
mArcRect.set(left, top, left + arcDiameter, top + arcDiameter);
int arcStart = (int)mProgressSweep + mStartAngle + mRotation + 90;
mThumbXPos = (int) (mArcRadius * Math.cos(Math.toRadians(arcStart)));
mThumbYPos = (int) (mArcRadius * Math.sin(Math.toRadians(arcStart)));
setTouchInSide(mTouchInside);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mEnabled) {
this.getParent().requestDisallowInterceptTouchEvent(true);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
onStartTrackingTouch();
updateOnTouch(event);
break;
case MotionEvent.ACTION_MOVE:
updateOnTouch(event);
break;
case MotionEvent.ACTION_UP:
onStopTrackingTouch();
setPressed(false);
this.getParent().requestDisallowInterceptTouchEvent(false);
break;
case MotionEvent.ACTION_CANCEL:
onStopTrackingTouch();
setPressed(false);
this.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
return true;
}
return false;
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
if (mThumb != null && mThumb.isStateful()) {
int[] state = getDrawableState();
mThumb.setState(state);
}
invalidate();
}
private void onStartTrackingTouch() {
if (mOnSeekArcChangeListener != null) {
mOnSeekArcChangeListener.onStartTrackingTouch(this);
}
}
private void onStopTrackingTouch() {
if (mOnSeekArcChangeListener != null) {
mOnSeekArcChangeListener.onStopTrackingTouch(this);
}
}
private void updateOnTouch(MotionEvent event) {
boolean ignoreTouch = ignoreTouch(event.getX(), event.getY());
if (ignoreTouch) {
return;
}
setPressed(true);
mTouchAngle = getTouchDegrees(event.getX(), event.getY());
int progress = getProgressForAngle(mTouchAngle);
onProgressRefresh(progress, true);
}
private boolean ignoreTouch(float xPos, float yPos) {
boolean ignore = false;
float x = xPos - mTranslateX;
float y = yPos - mTranslateY;
float touchRadius = (float) Math.sqrt(((x * x) + (y * y)));
if (touchRadius < mTouchIgnoreRadius) {
ignore = true;
}
return ignore;
}
private double getTouchDegrees(float xPos, float yPos) {
float x = xPos - mTranslateX;
float y = yPos - mTranslateY;
//invert the x-coord if we are rotating anti-clockwise
x= (mClockwise) ? x:-x;
// convert to arc Angle
double angle = Math.toDegrees(Math.atan2(y, x) + (Math.PI / 2)
- Math.toRadians(mRotation));
if (angle < 0) {
angle = 360 + angle;
}
angle -= mStartAngle;
return angle;
}
private int getProgressForAngle(double angle) {
int touchProgress = (int) Math.round(valuePerDegree() * angle);
touchProgress = (touchProgress < 0) ? INVALID_PROGRESS_VALUE
: touchProgress;
touchProgress = (touchProgress > mMax) ? INVALID_PROGRESS_VALUE
: touchProgress;
return touchProgress;
}
private float valuePerDegree() {
return (float) mMax / mSweepAngle;
}
private void onProgressRefresh(int progress, boolean fromUser) {
updateProgress(progress, fromUser);
}
private void updateThumbPosition() {
int thumbAngle = (int) (mStartAngle + mProgressSweep + mRotation + 90);
mThumbXPos = (int) (mArcRadius * Math.cos(Math.toRadians(thumbAngle)));
mThumbYPos = (int) (mArcRadius * Math.sin(Math.toRadians(thumbAngle)));
}
private void updateProgress(int progress, boolean fromUser) {
if (progress == INVALID_PROGRESS_VALUE) {
return;
}
progress = (progress > mMax) ? mMax : progress;
progress = (progress < 0) ? 0 : progress;
mProgress = progress;
if (mOnSeekArcChangeListener != null) {
mOnSeekArcChangeListener
.onProgressChanged(this, progress, fromUser);
}
mProgressSweep = (float) progress / mMax * mSweepAngle;
updateThumbPosition();
invalidate();
}
/**
* Sets a listener to receive notifications of changes to the SeekArc's
* progress level. Also provides notifications of when the user starts and
* stops a touch gesture within the SeekArc.
*
* @param l
* The seek bar notification listener
*
* @see SeekArc.OnSeekArcChangeListener
*/
public void setOnSeekArcChangeListener(OnSeekArcChangeListener l) {
mOnSeekArcChangeListener = l;
}
public void setProgress(int progress) {
updateProgress(progress, false);
}
public int getProgress() {
return mProgress;
}
public int getProgressWidth() {
return mProgressWidth;
}
public void setProgressWidth(int mProgressWidth) {
this.mProgressWidth = mProgressWidth;
mProgressPaint.setStrokeWidth(mProgressWidth);
}
public int getArcWidth() {
return mArcWidth;
}
public void setArcWidth(int mArcWidth) {
this.mArcWidth = mArcWidth;
mArcPaint.setStrokeWidth(mArcWidth);
}
public int getArcRotation() {
return mRotation;
}
public void setArcRotation(int mRotation) {
this.mRotation = mRotation;
updateThumbPosition();
}
public int getStartAngle() {
return mStartAngle;
}
public void setStartAngle(int mStartAngle) {
this.mStartAngle = mStartAngle;
updateThumbPosition();
}
public int getSweepAngle() {
return mSweepAngle;
}
public void setSweepAngle(int mSweepAngle) {
this.mSweepAngle = mSweepAngle;
updateThumbPosition();
}
public void setRoundedEdges(boolean isEnabled) {
mRoundedEdges = isEnabled;
if (mRoundedEdges) {
mArcPaint.setStrokeCap(Paint.Cap.ROUND);
mProgressPaint.setStrokeCap(Paint.Cap.ROUND);
} else {
mArcPaint.setStrokeCap(Paint.Cap.SQUARE);
mProgressPaint.setStrokeCap(Paint.Cap.SQUARE);
}
}
public void setTouchInSide(boolean isEnabled) {
int thumbHalfheight = mThumb.getIntrinsicHeight() / 2;
int thumbHalfWidth = mThumb.getIntrinsicWidth() / 2;
mTouchInside = isEnabled;
if (mTouchInside) {
mTouchIgnoreRadius = (float) mArcRadius / 4;
} else {
// Don't use the exact radius makes interaction too tricky
mTouchIgnoreRadius = mArcRadius
- Math.min(thumbHalfWidth, thumbHalfheight);
}
}
public void setClockwise(boolean isClockwise) {
mClockwise = isClockwise;
}
public boolean isClockwise() {
return mClockwise;
}
public boolean isEnabled() {
return mEnabled;
}
public void setEnabled(boolean enabled) {
this.mEnabled = enabled;
}
public int getProgressColor() {
return mProgressPaint.getColor();
}
public void setProgressColor(int color) {
mProgressPaint.setColor(color);
invalidate();
}
public int getArcColor() {
return mArcPaint.getColor();
}
public void setArcColor(int color) {
mArcPaint.setColor(color);
invalidate();
}
public int getMax() {
return mMax;
}
public void setMax(int mMax) {
this.mMax = mMax;
}
}
|
/**
* <code>annotations.el</code> provides classes that associate annotations with
* Java elements. {@link annotations.el.AElement}s represent Java elements
* of the scene that can carry annotations. There is a multi-level class
* hierarchy for elements that exploits certain commonalities: for example, all
* and only {@link annotations.el.ADeclaration declarations} contain an
* {@link annotations.el.ADeclaration#insertTypecasts insertTypecasts} field.
* A “scene” ({@link annotations.el.AScene}) contains many elements
* and represents all the annotations on a set of classes and packages.
*
* One related utility class that is important to understand is
* {@link annotations.util.coll.VivifyingMap}, a Map implementation that allows
* empty entries (for some user-defined meaning of
* {@link annotations.util.coll.VivifyingMap#isEmpty() empty}) and provides a
* {@link annotations.util.coll.VivifyingMap#prune() prune} method to eliminate
* these entries. The only way to create any element is to invoke
* {@link annotations.util.coll.VivifyingMap#vivify(Object) vivify()} on a
* {@link annotations.util.coll.VivifyingMap} static member of the appropriate
* {@link annotations.el.AElement} superclass.
*/
package annotations.el;
|
package io.spine.protobuf;
import com.google.common.base.Converter;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.protobuf.Any;
import com.google.protobuf.BoolValue;
import com.google.protobuf.ByteString;
import com.google.protobuf.BytesValue;
import com.google.protobuf.DoubleValue;
import com.google.protobuf.EnumValue;
import com.google.protobuf.FloatValue;
import com.google.protobuf.Int32Value;
import com.google.protobuf.Int64Value;
import com.google.protobuf.Message;
import com.google.protobuf.ProtocolMessageEnum;
import com.google.protobuf.StringValue;
import com.google.protobuf.UInt32Value;
import com.google.protobuf.UInt64Value;
import io.spine.annotation.Internal;
import io.spine.type.TypeUrl;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.spine.protobuf.AnyPacker.unpack;
import static io.spine.util.Exceptions.newIllegalArgumentException;
@Internal
public final class TypeConverter {
private static final TypeUrl ENUM_VALUE_TYPE_URL = TypeUrl.of(EnumValue.class);
/** Prevents instantiation of this utility class. */
private TypeConverter() {
}
/**
* Converts the given {@link Any} value to a Java {@link Object}.
*
* @param message the {@link Any} value to convert
* @param target the conversion target class
* @param <T> the conversion target type
* @return the converted value
*/
public static <T> T toObject(Any message, Class<T> target) {
checkNotNull(message);
checkNotNull(target);
checkNotRawEnum(message, target);
MessageCaster<? super Message, T> caster = MessageCaster.forType(target);
Message genericMessage = unpack(message);
T result = caster.convert(genericMessage);
return result;
}
/**
* Converts the given value to Protobuf {@link Any}.
*
* @param value the {@link Object} value to convert
* @param <T> the converted object type
* @return the packed value
* @see #toMessage(Object)
*/
public static <T> Any toAny(T value) {
checkNotNull(value);
Message message = toMessage(value);
Any result = AnyPacker.pack(message);
return result;
}
/**
* Converts the given value to a corresponding Protobuf {@link Message} type.
*
* @param value the {@link Object} value to convert
* @param <T> the converted object type
* @return the wrapped value
*/
public static <T> Message toMessage(T value) {
@SuppressWarnings("unchecked" /* Must be checked at runtime. */)
Class<T> srcClass = (Class<T>) value.getClass();
MessageCaster<Message, T> caster = MessageCaster.forType(srcClass);
Message message = caster.toMessage(value);
checkNotNull(message);
return message;
}
/**
* Converts the given value to a corresponding Protobuf {@link Message} type.
*
* <p>Unlike {@link #toMessage(Object)}, casts the message to the specified class.
*
* @param value the {@link Object} value to convert
* @param <T> the converted object type
* @param <M> the resulting message type
* @return the wrapped value
*/
public static <T, M extends Message> M toMessage(T value, Class<M> messageClass) {
checkNotNull(messageClass);
Message message = toMessage(value);
return messageClass.cast(message);
}
/**
* Makes sure no incorrectly packed enum values are passed to the message caster.
*
* <p>Currently, the enum values can only be converted from the {@link EnumValue} proto type.
* All other enum representations, including plain strings and numbers, are not supported.
*/
private static void checkNotRawEnum(Any message, Class<?> target) {
if (!target.isEnum()) {
return;
}
String typeUrl = message.getTypeUrl();
String enumValueTypeUrl = ENUM_VALUE_TYPE_URL.value();
checkArgument(
enumValueTypeUrl.equals(typeUrl),
"Currently the conversion of enum types packed as `%s` is not supported. " +
"Please make sure the enum value is wrapped with `%s` on the calling site.",
typeUrl, enumValueTypeUrl);
}
/**
* The {@link Function} performing the described type conversion.
*/
private abstract static class MessageCaster<M extends Message, T> extends Converter<M, T> {
private static <M extends Message, T> MessageCaster<M, T> forType(Class<T> cls) {
checkNotNull(cls);
MessageCaster<?, ?> caster;
if (Message.class.isAssignableFrom(cls)) {
caster = new MessageTypeCaster();
} else if (ByteString.class.isAssignableFrom(cls)) {
caster = new BytesCaster();
} else if (Enum.class.isAssignableFrom(cls)) {
@SuppressWarnings("unchecked") // Checked at runtime.
Class<? extends Enum<?>> enumCls = (Class<? extends Enum<?>>) cls;
caster = new EnumCaster(enumCls);
} else {
caster = new PrimitiveTypeCaster<>();
}
@SuppressWarnings("unchecked") // Logically checked.
MessageCaster<M, T> result = (MessageCaster<M, T>) caster;
return result;
}
@Override
protected T doForward(M input) {
return toObject(input);
}
@Override
protected M doBackward(T t) {
return toMessage(t);
}
protected abstract T toObject(M input);
protected abstract M toMessage(T input);
}
private static final class BytesCaster extends MessageCaster<BytesValue, ByteString> {
@Override
protected ByteString toObject(BytesValue input) {
ByteString result = input.getValue();
return result;
}
@Override
protected BytesValue toMessage(ByteString input) {
BytesValue bytes = BytesValue
.newBuilder()
.setValue(input)
.build();
return bytes;
}
}
private static final class EnumCaster extends MessageCaster<EnumValue, Enum<?>> {
@SuppressWarnings("rawtypes") // Needed to be able to pass the value to `Enum.valueOf(...)`.
private final Class<? extends Enum> type;
EnumCaster(Class<? extends Enum<?>> type) {
super();
this.type = type;
}
@Override
protected Enum<?> toObject(EnumValue input) {
String name = input.getName();
if (name.isEmpty()) {
int number = input.getNumber();
return convertByNumber(number);
} else {
return convertByName(name);
}
}
private Enum<?> convertByNumber(int number) {
Enum<?>[] constants = type.getEnumConstants();
for (Enum<?> constant : constants) {
ProtocolMessageEnum asProtoEnum = (ProtocolMessageEnum) constant;
int valueNumber = asProtoEnum.getNumber();
if (number == valueNumber) {
return constant;
}
}
throw unknownNumber(number);
}
@SuppressWarnings("unchecked") // Checked at runtime.
private Enum<?> convertByName(String name) {
return Enum.valueOf(type, name);
}
@Override
protected EnumValue toMessage(Enum<?> input) {
String name = input.name();
ProtocolMessageEnum asProtoEnum = (ProtocolMessageEnum) input;
EnumValue value = EnumValue
.newBuilder()
.setName(name)
.setNumber(asProtoEnum.getNumber())
.build();
return value;
}
private IllegalArgumentException unknownNumber(int number) {
throw newIllegalArgumentException(
"Could not find a enum value of type `%s` for number `%d`.",
type.getCanonicalName(), number);
}
}
private static final class MessageTypeCaster extends MessageCaster<Message, Message> {
@Override
protected Message toObject(Message input) {
return input;
}
@Override
protected Message toMessage(Message input) {
return input;
}
}
@SuppressWarnings("OverlyCoupledClass") // OK, as references a lot of type for casting.
private static final class PrimitiveTypeCaster<M extends Message, T>
extends MessageCaster<M, T> {
private static final ImmutableMap<Class<?>, Converter<? extends Message, ?>>
PROTO_WRAPPER_TO_HANDLER =
ImmutableMap.<Class<?>, Converter<? extends Message, ?>>builder()
.put(Int32Value.class, new Int32Handler())
.put(Int64Value.class, new Int64Handler())
.put(UInt32Value.class, new UInt32Handler())
.put(UInt64Value.class, new UInt64Handler())
.put(FloatValue.class, new FloatHandler())
.put(DoubleValue.class, new DoubleHandler())
.put(BoolValue.class, new BoolHandler())
.put(StringValue.class, new StringHandler())
.build();
private static final ImmutableMap<Class<?>, Converter<? extends Message, ?>>
PRIMITIVE_TO_HANDLER =
ImmutableMap.<Class<?>, Converter<? extends Message, ?>>builder()
.put(Integer.class, new Int32Handler())
.put(Long.class, new Int64Handler())
.put(Float.class, new FloatHandler())
.put(Double.class, new DoubleHandler())
.put(Boolean.class, new BoolHandler())
.put(String.class, new StringHandler())
.build();
@Override
protected T toObject(M input) {
Class<?> boxedType = input.getClass();
@SuppressWarnings("unchecked") Converter<M, T> typeUnpacker =
(Converter<M, T>) PROTO_WRAPPER_TO_HANDLER.get(boxedType);
checkArgument(typeUnpacker != null,
"Could not find a primitive type for %s.",
boxedType.getName());
T result = typeUnpacker.convert(input);
return result;
}
@Override
protected M toMessage(T input) {
Class<?> cls = input.getClass();
@SuppressWarnings("unchecked") Converter<M, T> converter =
(Converter<M, T>) PRIMITIVE_TO_HANDLER.get(cls);
checkArgument(converter != null,
"Could not find a wrapper type for %s.",
cls.getName());
M result = converter.reverse()
.convert(input);
return result;
}
}
/**
* A converter handling the primitive types transformations.
*
* <p>It's sufficient to override methods {@link #pack(Object) pack(T)} and
* {@link #unpack(Message) unpack(M)} when extending this class.
*
* <p>Since the Protobuf and Java primitives differ, there may be more then one
* {@code PrimitiveHandler} for a Java primitive type. In this case, if the resulting Protobuf
* value type is not specified explicitly, the closest type is selected as a target for
* the conversion. The closeness of two types is determined by the lexicographic closeness.
*
* @param <M> the type of the Protobuf primitive wrapper
* @param <T> the type of the Java primitive wrapper
*/
private abstract static class PrimitiveHandler<M extends Message, T> extends Converter<M, T> {
@Override
protected T doForward(M input) {
return unpack(input);
}
@Override
protected M doBackward(T input) {
return pack(input);
}
/**
* Unpacks a primitive value of type {@code T} from the given wrapper value.
*
* @param message packed value
* @return unpacked value
*/
protected abstract T unpack(M message);
/**
* Packs the given primitive value into a Protobuf wrapper of type {@code M}.
*
* @param value primitive value
* @return packed value
*/
protected abstract M pack(T value);
}
private static final class Int32Handler extends PrimitiveHandler<Int32Value, Integer> {
@Override
protected Integer unpack(Int32Value message) {
checkNotNull(message);
return message.getValue();
}
@Override
protected Int32Value pack(Integer value) {
return Int32Value.newBuilder()
.setValue(value)
.build();
}
}
private static final class Int64Handler extends PrimitiveHandler<Int64Value, Long> {
@Override
protected Long unpack(Int64Value message) {
checkNotNull(message);
return message.getValue();
}
@Override
protected Int64Value pack(Long value) {
return Int64Value.newBuilder()
.setValue(value)
.build();
}
}
private static final class UInt32Handler extends PrimitiveHandler<UInt32Value, Integer> {
@Override
protected Integer unpack(UInt32Value message) {
checkNotNull(message);
return message.getValue();
}
@Override
protected UInt32Value pack(Integer value) {
// Hidden by Int32Handler
return UInt32Value.newBuilder()
.setValue(value)
.build();
}
}
private static final class UInt64Handler extends PrimitiveHandler<UInt64Value, Long> {
@Override
protected Long unpack(UInt64Value message) {
checkNotNull(message);
return message.getValue();
}
@Override
protected UInt64Value pack(Long value) {
// Hidden by Int64Handler
return UInt64Value.newBuilder()
.setValue(value)
.build();
}
}
private static final class FloatHandler extends PrimitiveHandler<FloatValue, Float> {
@Override
protected Float unpack(FloatValue message) {
checkNotNull(message);
return message.getValue();
}
@Override
protected FloatValue pack(Float value) {
return FloatValue.newBuilder()
.setValue(value)
.build();
}
}
private static final class DoubleHandler extends PrimitiveHandler<DoubleValue, Double> {
@Override
protected Double unpack(DoubleValue message) {
checkNotNull(message);
return message.getValue();
}
@Override
protected DoubleValue pack(Double value) {
return DoubleValue.newBuilder()
.setValue(value)
.build();
}
}
private static final class BoolHandler extends PrimitiveHandler<BoolValue, Boolean> {
@Override
protected Boolean unpack(BoolValue message) {
checkNotNull(message);
return message.getValue();
}
@Override
protected BoolValue pack(Boolean value) {
return BoolValue.newBuilder()
.setValue(value)
.build();
}
}
private static final class StringHandler extends PrimitiveHandler<StringValue, String> {
@Override
protected String unpack(StringValue message) {
checkNotNull(message);
return message.getValue();
}
@Override
protected StringValue pack(String value) {
return StringValue.newBuilder()
.setValue(value)
.build();
}
}
}
|
package hello;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.concurrent.*;
import javax.annotation.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.*;
/**
* Database connectivity (with a Servlet-container managed pool) test.
*/
@SuppressWarnings("serial")
public class PostgresServlet extends HttpServlet
{
// Database details.
private static final String DB_QUERY = "SELECT * FROM World WHERE id = ?";
private static final int DB_ROWS = 10000;
// Database connection pool.
@Resource(name="jdbc/postgres_hello_world")
private DataSource postgresDataSource;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
// Set content type to JSON
res.setHeader(Common.HEADER_CONTENT_TYPE, Common.CONTENT_TYPE_JSON);
// Reference the data source.
final DataSource source = postgresDataSource;
// Get the count of queries to run.
int count = 1;
try
{
count = Integer.parseInt(req.getParameter("queries"));
// Bounds check.
if (count > 500)
{
count = 500;
}
if (count < 1)
{
count = 1;
}
}
catch (NumberFormatException nfexc)
{
// Do nothing.
}
// Fetch some rows from the database.
final World[] worlds = new World[count];
final Random random = ThreadLocalRandom.current();
try (Connection conn = source.getConnection())
{
try (PreparedStatement statement = conn.prepareStatement(DB_QUERY,
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY))
{
// Run the query the number of times requested.
for (int i = 0; i < count; i++)
{
final int id = random.nextInt(DB_ROWS) + 1;
statement.setInt(1, id);
try (ResultSet results = statement.executeQuery())
{
if (results.next())
{
worlds[i] = new World(id, results.getInt("randomNumber"));
}
}
}
}
}
catch (SQLException sqlex)
{
System.err.println("SQL Exception: " + sqlex);
}
// Write JSON encoded message to the response.
try
{
if (count == 1)
{
Common.MAPPER.writeValue(res.getOutputStream(), worlds[0]);
}
else
{
Common.MAPPER.writeValue(res.getOutputStream(), worlds);
}
}
catch (IOException ioe)
{
// do nothing
}
}
}
|
package org.intermine.bio.web.logic;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.intermine.objectstore.query.BagConstraint;
import org.intermine.objectstore.query.ConstraintOp;
import org.intermine.objectstore.query.ConstraintSet;
import org.intermine.objectstore.query.ContainsConstraint;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QueryClass;
import org.intermine.objectstore.query.QueryField;
import org.intermine.objectstore.query.QueryObjectReference;
import org.intermine.objectstore.query.QueryValue;
import org.intermine.objectstore.query.Results;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.objectstore.query.SimpleConstraint;
import org.intermine.metadata.Model;
import org.intermine.objectstore.ObjectStore;
import org.intermine.web.logic.bag.InterMineBag;
import org.flymine.model.genomic.Chromosome;
import org.flymine.model.genomic.Organism;
/**
* Utility methods for the flymine package.
* @author Julie Sullivan
*/
public abstract class BioUtil
{
/**
* For a bag of objects, returns a list of organisms
* @param os ObjectStore
* @param bag InterMineBag
* @return collection of organism names
*/
public static Collection<String> getOrganisms(ObjectStore os, InterMineBag bag) {
Query q = new Query();
Model model = os.getModel();
QueryClass qcObject = null;
try {
qcObject = new QueryClass(Class.forName(model.getPackageName() + "." + bag.getType()));
} catch (ClassNotFoundException e) {
return null;
}
QueryClass qcOrganism = new QueryClass(Organism.class);
QueryField qfOrganismName = new QueryField(qcOrganism, "name");
QueryField qfGeneId = new QueryField(qcObject, "id");
q.addFrom(qcObject);
q.addFrom(qcOrganism);
q.addToSelect(qfOrganismName);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
BagConstraint bc = new BagConstraint(qfGeneId, ConstraintOp.IN, bag.getOsb());
cs.addConstraint(bc);
QueryObjectReference qr = new QueryObjectReference(qcObject, "organism");
ContainsConstraint cc = new ContainsConstraint(qr, ConstraintOp.CONTAINS, qcOrganism);
cs.addConstraint(cc);
q.setConstraint(cs);
q.addToOrderBy(qfOrganismName);
Results r = os.execute(q);
Iterator<ResultsRow> it = r.iterator();
Collection<String> organismNames = new ArrayList<String>();
while (it.hasNext()) {
ResultsRow rr = it.next();
organismNames.add((String) rr.get(0));
}
return organismNames;
}
/**
* Return a list of chromosomes for specified organism
* @param os ObjectStore
* @param organism Organism name
* @return collection of chromosome names
*/
public static Collection<String> getChromosomes(ObjectStore os, String organism) {
/* TODO put this in a config file */
// TODO this may well go away once chromosomes sorted out in #1186
if (organism.equals("Drosophila melanogaster")) {
ArrayList<String> chromosomes = new ArrayList<String>();
chromosomes.add("2L");
chromosomes.add("2R");
chromosomes.add("3L");
chromosomes.add("3R");
chromosomes.add("4");
chromosomes.add("U");
chromosomes.add("X");
return chromosomes;
}
Query q = new Query();
QueryClass qcChromosome = new QueryClass(Chromosome.class);
QueryClass qcOrganism = new QueryClass(Organism.class);
QueryField qfChromosome = new QueryField(qcChromosome, "primaryIdentifier");
QueryField organismNameQF = new QueryField(qcOrganism, "name");
q.addFrom(qcChromosome);
q.addFrom(qcOrganism);
q.addToSelect(qfChromosome);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
QueryObjectReference qr = new QueryObjectReference(qcChromosome, "organism");
ContainsConstraint cc = new ContainsConstraint(qr, ConstraintOp.CONTAINS, qcOrganism);
cs.addConstraint(cc);
SimpleConstraint sc = new SimpleConstraint(organismNameQF,
ConstraintOp.EQUALS,
new QueryValue(organism));
cs.addConstraint(sc);
q.setConstraint(cs);
q.addToOrderBy(qfChromosome);
Results r = os.execute(q);
Iterator it = r.iterator();
Collection<String> chromosomes = new ArrayList<String>();
while (it.hasNext()) {
ResultsRow rr = (ResultsRow) it.next();
chromosomes.add((String) rr.get(0));
}
return chromosomes;
}
}
|
package nu.validator.io;
import java.io.IOException;
import java.io.InputStream;
/**
* @version $Id$
* @author hsivonen
*/
public class ObservableInputStream extends InputStream {
private StreamObserver observer;
private InputStream delegate;
public ObservableInputStream(InputStream delegate, StreamObserver obs) {
this.delegate = delegate;
this.observer = obs;
}
/**
* @see java.io.InputStream#available()
*/
@Override
public int available() throws IOException {
try {
return delegate.available();
} catch (IOException | RuntimeException e) {
observer.exceptionOccurred(e);
throw new RuntimeException("The observer failed to throw per API contract.");
}
}
/**
* @see java.io.InputStream#close()
*/
@Override
public void close() throws IOException {
try {
observer.closeCalled();
delegate.close();
} catch (IOException | RuntimeException e) {
observer.exceptionOccurred(e);
throw new RuntimeException("The observer failed to throw per API contract.");
}
}
/**
* @see java.io.InputStream#mark(int)
*/
@Override
public void mark(int arg0) {
try {
delegate.mark(arg0);
} catch (RuntimeException e) {
try {
observer.exceptionOccurred(e);
} catch (IOException e1) {
throw new RuntimeException("The observer threw against the API contract.", e1);
}
throw new RuntimeException("The observer failed to throw per API contract.");
}
}
/**
* @see java.io.InputStream#markSupported()
*/
@Override
public boolean markSupported() {
try {
return delegate.markSupported();
} catch (RuntimeException e) {
try {
observer.exceptionOccurred(e);
} catch (IOException e1) {
throw new RuntimeException("The observer threw against the API contract.", e1);
}
throw new RuntimeException("The observer failed to throw per API contract.");
}
}
/**
* @return
* @throws java.io.IOException
*/
@Override
public int read() throws IOException {
try {
return delegate.read();
} catch (IOException | RuntimeException e) {
observer.exceptionOccurred(e);
throw new RuntimeException("The observer failed to throw per API contract.");
}
}
/**
* @see java.io.InputStream#read(byte[])
*/
@Override
public int read(byte[] arg0) throws IOException {
try {
return delegate.read(arg0);
} catch (IOException | RuntimeException e) {
observer.exceptionOccurred(e);
throw new RuntimeException("The observer failed to throw per API contract.");
}
}
/**
* @see java.io.InputStream#read(byte[], int, int)
*/
@Override
public int read(byte[] arg0, int arg1, int arg2) throws IOException {
try {
return delegate.read(arg0, arg1, arg2);
} catch (IOException | RuntimeException e) {
if ("Corrupt GZIP trailer".equals(e.getMessage())) {
return -1;
} else {
observer.exceptionOccurred(e);
throw new RuntimeException("The observer failed to throw per API contract.");
}
}
}
/**
* @see java.io.InputStream#reset()
*/
@Override
public void reset() throws IOException {
try {
delegate.reset();
} catch (IOException | RuntimeException e) {
observer.exceptionOccurred(e);
throw new RuntimeException("The observer failed to throw per API contract.");
}
}
/**
* @see java.io.InputStream#skip(long)
*/
@Override
public long skip(long arg0) throws IOException {
try {
return delegate.skip(arg0);
} catch (IOException | RuntimeException e) {
observer.exceptionOccurred(e);
throw new RuntimeException("The observer failed to throw per API contract.");
}
}
/**
* @see java.lang.Object#finalize()
*/
@SuppressWarnings("deprecation")
@Override
protected void finalize() throws Throwable {
observer.finalizerCalled();
super.finalize();
}
}
|
package org._3pq.jgrapht.graph;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import org._3pq.jgrapht.DirectedGraph;
import org._3pq.jgrapht.Edge;
import org._3pq.jgrapht.EdgeFactory;
import org._3pq.jgrapht.Graph;
import org._3pq.jgrapht.UndirectedGraph;
/**
* A graph backed by the the graph specified at the constructor, which
* delegates all its methods to the backing graph. Operations on this graph
* "pass through" to the to the backing graph. Any modification made to this
* graph or the backing graph is reflected by the other.
*
* <p>
* This graph does <i>not</i> pass the hashCode and equals operations through
* to the backing graph, but relies on <tt>Object</tt>'s <tt>equals</tt> and
* <tt>hashCode</tt> methods.
* </p>
*
* <p>
* This class is mostly used as a base for extending subclasses.
* </p>
*
* @author Barak Naveh
*
* @since Jul 20, 2003
*/
public class GraphDelegator extends AbstractGraph implements Graph,
Serializable {
private static final long serialVersionUID = 3257005445226181425L;
/** The graph to which operations are delegated. */
private Graph m_delegate;
/**
* Constructor for GraphDelegator.
*
* @param g the backing graph (the delegate).
*
* @throws NullPointerException
*/
public GraphDelegator( Graph g ) {
super( );
if( g == null ) {
throw new NullPointerException( );
}
m_delegate = g;
}
/**
* @see Graph#getAllEdges(Object, Object)
*/
public List getAllEdges( Object sourceVertex, Object targetVertex ) {
return m_delegate.getAllEdges( sourceVertex, targetVertex );
}
/**
* @see Graph#getEdge(Object, Object)
*/
public Edge getEdge( Object sourceVertex, Object targetVertex ) {
return m_delegate.getEdge( sourceVertex, targetVertex );
}
/**
* @see Graph#getEdgeFactory()
*/
public EdgeFactory getEdgeFactory( ) {
return m_delegate.getEdgeFactory( );
}
/**
* @see Graph#addEdge(Edge)
*/
public boolean addEdge( Edge e ) {
return m_delegate.addEdge( e );
}
/**
* @see Graph#addEdge(Object, Object)
*/
public Edge addEdge( Object sourceVertex, Object targetVertex ) {
return m_delegate.addEdge( sourceVertex, targetVertex );
}
/**
* @see Graph#addVertex(Object)
*/
public boolean addVertex( Object v ) {
return m_delegate.addVertex( v );
}
/**
* @see Graph#containsEdge(Edge)
*/
public boolean containsEdge( Edge e ) {
return m_delegate.containsEdge( e );
}
/**
* @see Graph#containsVertex(Object)
*/
public boolean containsVertex( Object v ) {
return m_delegate.containsVertex( v );
}
/**
* @see UndirectedGraph#degreeOf(Object)
*/
public int degreeOf( Object vertex ) {
return ( (UndirectedGraph) m_delegate ).degreeOf( vertex );
}
/**
* @see Graph#edgeSet()
*/
public Set edgeSet( ) {
return m_delegate.edgeSet( );
}
/**
* @see Graph#edgesOf(Object)
*/
public List edgesOf( Object vertex ) {
return m_delegate.edgesOf( vertex );
}
/**
* @see DirectedGraph#inDegreeOf(Object)
*/
public int inDegreeOf( Object vertex ) {
return ( (DirectedGraph) m_delegate ).inDegreeOf( vertex );
}
/**
* @see DirectedGraph#incomingEdgesOf(Object)
*/
public List incomingEdgesOf( Object vertex ) {
return ( (DirectedGraph) m_delegate ).incomingEdgesOf( vertex );
}
/**
* @see DirectedGraph#outDegreeOf(Object)
*/
public int outDegreeOf( Object vertex ) {
return ( (DirectedGraph) m_delegate ).outDegreeOf( vertex );
}
/**
* @see DirectedGraph#outgoingEdgesOf(Object)
*/
public List outgoingEdgesOf( Object vertex ) {
return ( (DirectedGraph) m_delegate ).outgoingEdgesOf( vertex );
}
/**
* @see Graph#removeEdge(Edge)
*/
public boolean removeEdge( Edge e ) {
return m_delegate.removeEdge( e );
}
/**
* @see Graph#removeEdge(Object, Object)
*/
public Edge removeEdge( Object sourceVertex, Object targetVertex ) {
return m_delegate.removeEdge( sourceVertex, targetVertex );
}
/**
* @see Graph#removeVertex(Object)
*/
public boolean removeVertex( Object v ) {
return m_delegate.removeVertex( v );
}
/**
* @see java.lang.Object#toString()
*/
public String toString( ) {
return m_delegate.toString( );
}
/**
* @see Graph#vertexSet()
*/
public Set vertexSet( ) {
return m_delegate.vertexSet( );
}
}
|
package org.apache.fop.render.awt;
/*
originally contributed by
Juergen Verwohlt: Juergen.Verwohlt@jCatalog.com,
Rainer Steinkuhle: Rainer.Steinkuhle@jCatalog.com,
Stanislav Gorkhover: Stanislav.Gorkhover@jCatalog.com
*/
import org.apache.fop.layout.*;
import org.apache.fop.layout.inline.*;
import org.apache.fop.messaging.MessageHandler;
import org.apache.fop.datatypes.*;
import org.apache.fop.image.*;
import org.apache.fop.svg.*;
import org.apache.fop.render.pdf.*;
import org.apache.fop.viewer.*;
import org.apache.fop.apps.*;
import org.w3c.dom.svg.*;
import org.w3c.dom.Document;
import org.apache.batik.bridge.*;
import org.apache.batik.swing.svg.*;
import org.apache.batik.swing.gvt.*;
import org.apache.batik.gvt.*;
import org.apache.batik.gvt.renderer.*;
import org.apache.batik.gvt.filter.*;
import org.apache.batik.gvt.event.*;
import java.awt.*;
import java.awt.Image;
import java.awt.image.*;
import java.awt.geom.*;
import java.awt.font.*;
import java.util.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.*;
import java.beans.*;
import javax.swing.*;
import java.awt.print.*;
import java.awt.image.BufferedImage;
import java.text.*;
import org.apache.fop.render.Renderer;
public class AWTRenderer implements Renderer, Printable, Pageable {
protected int pageWidth = 0;
protected int pageHeight = 0;
protected double scaleFactor = 100.0;
protected int pageNumber = 0;
protected AreaTree tree;
protected ProgressListener progressListener = null;
protected Translator res = null;
protected Hashtable fontNames = new Hashtable();
protected Hashtable fontStyles = new Hashtable();
protected Color saveColor = null;
/**
* Image Object and Graphics Object. The Graphics Object is the Graphics
* object that is contained withing the Image Object.
*/
private BufferedImage pageImage = null;
private Graphics2D graphics = null;
/**
* The current (internal) font name
*/
protected String currentFontName;
/**
* The current font size in millipoints
*/
protected int currentFontSize;
/**
* The current colour's red, green and blue component
*/
protected float currentRed = 0;
protected float currentGreen = 0;
protected float currentBlue = 0;
/**
* The parent component, used to set up the font.
* This is needed as FontSetup needs a live AWT component
* in order to generate valid font measures.
*/
protected Component parent;
/**
* The current vertical position in millipoints from bottom
*/
protected int currentYPosition = 0;
/**
* The current horizontal position in millipoints from left
*/
protected int currentXPosition = 0;
/**
* The horizontal position of the current area container
*/
private int currentAreaContainerXPosition = 0;
/** options */
protected Hashtable options;
/** set up renderer options */
public void setOptions(Hashtable options) {
this.options = options;
}
public AWTRenderer(Translator aRes) {
res = aRes;
}
/**
* Sets parent component which is used to set up the font.
* This is needed as FontSetup needs a live AWT component
* in order to generate valid font measures.
* @param parent the live AWT component reference
*/
public void setComponent(Component parent) {
this.parent = parent;
}
public int getPageNumber() {
return pageNumber;
}
public void setPageNumber(int aValue) {
pageNumber = aValue;
}
public void setScaleFactor(double newScaleFactor) {
scaleFactor = newScaleFactor;
}
public double getScaleFactor() {
return scaleFactor;
}
public BufferedImage getLastRenderedPage() {
return pageImage;
}
/**
* add a line to the current stream
*
* @param x1 the start x location in millipoints
* @param y1 the start y location in millipoints
* @param x2 the end x location in millipoints
* @param y2 the end y location in millipoints
* @param th the thickness in millipoints
* @param r the red component
* @param g the green component
* @param b the blue component
*/
// corrected 7/13/01 aml,rlc to properly handle thickness
protected void addLine(int x1, int y1, int x2, int y2, int th,
float r, float g, float b)
{
graphics.setColor(new Color (r, g, b));
int x = x1;
int y = y1;
int height, width;
if (x1 == x2) //vertical line
{
height = y2 - y1;
if (height > 0) //y coordinates are reversed between fo and AWT
{
height = -height;
y = y2;
}
width = th;
if (width < 0)
{
width = -width;
x -= width;
}
}
else //horizontal line
{
width = x2 - x1;
if (width < 0)
{
width = -width;
x = x2;
}
height = th;
if (height > 0) //y coordinates are reversed between fo and AWT
{
height = -height;
y -= height;
}
}
addRect (x, y, width, height, false);
// // graphics.setColor(Color.red);
// graphics.drawLine((int)(x1 / 1000f),
// pageHeight - (int)(y1 / 1000f), (int)(x2 / 1000f),
// pageHeight - (int)(y2 / 1000f));
}
/**
* draw a rectangle
*
* @param x the x position of left edge in millipoints
* @param y the y position of top edge in millipoints
* @param w the width in millipoints
* @param h the height in millipoints
* @param r the red component
* @param g the green component
* @param b the blue component
*/
// changed by aml/rlc to use helper function that
// corrects for integer roundoff, and to remove 3D effect
protected void addRect(int x, int y, int w, int h, float r,
float g, float b) {
graphics.setColor(new Color (r, g, b));
// graphics.setColor(Color.green);
addRect (x, y, w, h, true);
}
/**
* draw a filled rectangle
*
* @param x the x position of left edge in millipoints
* @param y the y position of top edge in millipoints
* @param w the width in millipoints
* @param h the height in millipoints
* @param r the red component of edges
* @param g the green component of edges
* @param b the blue component of edges
* @param fr the red component of the fill
* @param fg the green component of the fill
* @param fb the blue component of the fill
*/
// changed by aml/rlc to use helper function that
// corrects for integer roundoff
protected void addRect(int x, int y, int w, int h, float r,
float g, float b, float fr, float fg, float fb)
{
graphics.setColor(new Color (r, g, b));
addRect (x, y, w, h, true);
graphics.setColor(new Color (fr, fg, fb));
addRect (x, y, w, h, false);
}
/**
* draw a filled rectangle in the current color
*
* @param x the x position of left edge in millipoints
* @param y the y position of top edge in millipoints
* @param w the width in millipoints
* @param h the height in millipoints
* @param drawAsOutline true for draw, false for fill
*/
// helper function by aml/rlc to correct integer roundoff problems
protected void addRect(int x, int y, int w, int h, boolean drawAsOutline)
{
int startx = (x + 500)/ 1000;
int starty = pageHeight - ((y + 500) / 1000);
int endx = (x + w + 500) / 1000;
int endy = pageHeight - ((y + h + 500) / 1000);
if (drawAsOutline)
graphics.drawRect(startx, starty, endx - startx, endy - starty);
else
graphics.fillRect(startx, starty, endx - startx, endy - starty);
}
/**
* To configure before print.
*
* Choose pages
* Zoom factor
* Page format / Landscape or Portrait
**/
public void transform(Graphics2D g2d, double zoomPercent,double angle)
{
AffineTransform at = g2d.getTransform();
at.rotate(angle);
at.scale(zoomPercent / 100.0, zoomPercent / 100.0);
g2d.setTransform(at);
}
protected void drawFrame() {
int width = pageWidth;
int height = pageHeight;
graphics.setColor(Color.white);
graphics.fillRect(0, 0, width, height);
graphics.setColor(Color.black);
graphics.drawRect(-1, -1, width + 2, height + 2);
graphics.drawLine(width + 2, 0, width + 2, height + 2);
graphics.drawLine(width + 3, 1, width + 3, height + 3);
graphics.drawLine(0, height + 2, width + 2, height + 2);
graphics.drawLine(1, height + 3, width + 3, height + 3);
}
/**
* Retrieve the number of pages in this document.
*
* @return the number of pages
*/
public int getPageCount() {
if (tree == null) {
return 0;
}
return tree.getPages().size();
}
public void render(int aPageNumber) {
if (tree != null) {
try {
render(tree, aPageNumber);
} catch (IOException e) {
e.printStackTrace();
// This exception can't occur because we are not dealing with
// any files.
}
}
}
public void render(AreaTree areaTree,
OutputStream stream) throws IOException {
tree = areaTree;
render(areaTree, 0);
}
public void render(AreaTree areaTree,
int aPageNumber) throws IOException {
tree = areaTree;
Page page = (Page) areaTree.getPages().elementAt(aPageNumber);
pageWidth = (int)((float) page.getWidth() / 1000f + .5);
pageHeight = (int)((float) page.getHeight() / 1000f + .5);
pageImage = new BufferedImage(
(int)((pageWidth * (int) scaleFactor) / 100),
(int)((pageHeight * (int) scaleFactor) / 100),
BufferedImage.TYPE_INT_RGB);
graphics = pageImage.createGraphics();
transform(graphics, scaleFactor, 0);
drawFrame();
renderPage(page);
}
public void renderPage(Page page) {
BodyAreaContainer body;
AreaContainer before, after;
body = page.getBody();
before = page.getBefore();
after = page.getAfter();
this.currentFontName = "";
this.currentFontSize = 0;
renderBodyAreaContainer(body);
if (before != null) {
renderAreaContainer(before);
}
if (after != null) {
renderAreaContainer(after);
}
// SG: Wollen wir Links abbilden?
/*
if (page.hasLinks()) {
.
}
*/
}
public void renderAreaContainer(AreaContainer area) {
int saveY = this.currentYPosition;
int saveX = this.currentAreaContainerXPosition;
if (area.getPosition() ==
org.apache.fop.fo.properties.Position.ABSOLUTE) {
// Y position is computed assuming positive Y axis, adjust
//for negative postscript one
this.currentYPosition =
area.getYPosition() - 2 * area.getPaddingTop() -
2 * area.getBorderTopWidth();
this.currentAreaContainerXPosition = area.getXPosition();
} else if (area.getPosition() ==
org.apache.fop.fo.properties.Position.RELATIVE) {
this.currentYPosition -= area.getYPosition();
this.currentAreaContainerXPosition += area.getXPosition();
} else if (area.getPosition() ==
org.apache.fop.fo.properties.Position.STATIC) {
this.currentYPosition -=
area.getPaddingTop() + area.getBorderTopWidth();
this.currentAreaContainerXPosition +=
area.getPaddingLeft() + area.getBorderLeftWidth();
}
doFrame(area);
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
org.apache.fop.layout.Box b =
(org.apache.fop.layout.Box) e.nextElement();
b.render(this);
}
if (area.getPosition() !=
org.apache.fop.fo.properties.Position.STATIC) {
this.currentYPosition = saveY;
this.currentAreaContainerXPosition = saveX;
} else {
this.currentYPosition -= area.getHeight();
}
}
// empty for now
public void renderBodyAreaContainer(BodyAreaContainer area) {
renderAreaContainer(area.getBeforeFloatReferenceArea());
renderAreaContainer(area.getFootnoteReferenceArea());
// main reference area
Enumeration e =
area.getMainReferenceArea().getChildren().elements();
while (e.hasMoreElements()) {
org.apache.fop.layout.Box b =
(org.apache.fop.layout.Box) e.nextElement();
b.render(this); // span areas
}
}
// empty for now
public void renderSpanArea(SpanArea area) {
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
org.apache.fop.layout.Box b =
(org.apache.fop.layout.Box) e.nextElement();
b.render(this); // column areas
}
}
private void doFrame(org.apache.fop.layout.Area area) {
int w, h;
int rx = this.currentAreaContainerXPosition;
w = area.getContentWidth();
if (area instanceof BlockArea) {
rx += ((BlockArea) area).getStartIndent();
}
h = area.getContentHeight();
int ry = this.currentYPosition;
ColorType bg = area.getBackgroundColor();
rx = rx - area.getPaddingLeft();
ry = ry + area.getPaddingTop();
w = w + area.getPaddingLeft() + area.getPaddingRight();
h = h + area.getPaddingTop() + area.getPaddingBottom();
// I'm not sure I should have to check for bg being null
// but I do
if ((bg != null) && (bg.alpha() == 0)) {
this.addRect(rx, ry, w, -h, bg.red(), bg.green(),
bg.blue(), bg.red(), bg.green(), bg.blue());
}
rx = rx - area.getBorderLeftWidth();
ry = ry + area.getBorderTopWidth();
w = w + area.getBorderLeftWidth() + area.getBorderRightWidth();
h = h + area.getBorderTopWidth() + area.getBorderBottomWidth();
BorderAndPadding bp = area.getBorderAndPadding();
ColorType borderColor;
if (area.getBorderTopWidth() != 0) {
borderColor = bp.getBorderColor(BorderAndPadding.TOP);
// addLine(rx, ry, rx + w, ry, area.getBorderTopWidth(), // corrected aml/rlc
addLine(rx, ry, rx + w, ry, -area.getBorderTopWidth(),
borderColor.red(), borderColor.green(),
borderColor.blue());
}
if (area.getBorderLeftWidth() != 0) {
borderColor = bp.getBorderColor(BorderAndPadding.LEFT);
addLine(rx, ry, rx, ry - h, area.getBorderLeftWidth(),
borderColor.red(), borderColor.green(),
borderColor.blue());
}
if (area.getBorderRightWidth() != 0) {
borderColor = bp.getBorderColor(BorderAndPadding.RIGHT);
addLine(rx + w, ry, rx + w, ry - h,
// area.getBorderRightWidth(), borderColor.red(), // corrected aml/rlc
-area.getBorderRightWidth(), borderColor.red(),
borderColor.green(), borderColor.blue());
}
if (area.getBorderBottomWidth() != 0) {
borderColor = bp.getBorderColor(BorderAndPadding.BOTTOM);
addLine(rx, ry - h, rx + w, ry - h,
area.getBorderBottomWidth(), borderColor.red(),
borderColor.green(), borderColor.blue());
}
}
protected Rectangle2D getBounds(org.apache.fop.layout.Area a) {
return new Rectangle2D.Double(currentAreaContainerXPosition,
currentYPosition, a.getAllocationWidth(), a.getHeight());
}
/*
public void renderBlockArea(BlockArea area) {
doFrame(area);
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
org.apache.fop.layout.Box b =
(org.apache.fop.layout.Box) e.nextElement();
b.render(this);
}
}
*/
public void renderBlockArea(BlockArea area) {
this.currentYPosition -= (area.getPaddingTop() + area.getBorderTopWidth());
doFrame(area);
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
org.apache.fop.layout.Box b =
(org.apache.fop.layout.Box) e.nextElement();
b.render(this);
}
this.currentYPosition -= (area.getPaddingBottom() + area.getBorderBottomWidth());
}
public void setupFontInfo(FontInfo fontInfo) {
// create a temp Image to test font metrics on
BufferedImage fontImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
FontSetup.setup(fontInfo, fontImage.createGraphics());
}
public void renderDisplaySpace(DisplaySpace space) {
int d = space.getSize();
this.currentYPosition -= d;
}
// correct integer roundoff (aml/rlc)
public void renderImageArea(ImageArea area)
{
int x = currentAreaContainerXPosition +
area.getXOffset();
int y = currentYPosition;
int w = area.getContentWidth();
int h = area.getHeight();
FopImage img = area.getImage();
if (img == null) {
MessageHandler.logln("Error while loading image : area.getImage() is null");
// correct integer roundoff
// graphics.drawRect(x / 1000, pageHeight - y / 1000,
// w / 1000, h / 1000);
addRect (x, y, w, h, true); // use helper function
java.awt.Font f = graphics.getFont();
java.awt.Font smallFont =
new java.awt.Font(f.getFontName(), f.getStyle(), 8);
graphics.setFont(smallFont);
// correct integer roundoff // aml/rlc
// graphics.drawString("area.getImage() is null", x / 1000,
// pageHeight - y / 1000);
graphics.drawString("area.getImage() is null", (x + 500) / 1000,
pageHeight - (y + 500) / 1000);
graphics.setFont(f);
} else {
if (img instanceof SVGImage) {
try {
SVGDocument svg = ((SVGImage) img).getSVGDocument();
renderSVGDocument(svg, (int) x, (int) y);
} catch (FopImageException e) {
}
} else {
String urlString = img.getURL();
try {
URL url = new URL(urlString);
ImageIcon icon = new ImageIcon(url);
Image image = icon.getImage();
// correct integer roundoff aml/rlc
// graphics.drawImage(image, x / 1000,
// pageHeight - y / 1000, w / 1000, h / 1000,
// null);
int startx = (x + 500)/ 1000;
int starty = pageHeight - ((y + 500) / 1000);
int endx = (x + w + 500) / 1000;
int endy = pageHeight - ((y + h + 500) / 1000);
//reverse start and end y because h is positive
graphics.drawImage(image, startx, starty, endx - startx, starty - endy, null);
} catch (MalformedURLException mue) {
// cannot normally occur because, if URL is wrong, constructing FopImage
// will already have failed earlier on
}
}
}
currentYPosition -= h;
}
public void renderWordArea(WordArea area) {
char ch;
StringBuffer pdf = new StringBuffer();
String name = area.getFontState().getFontName();
int size = area.getFontState().getFontSize();
boolean underlined = area.getUnderlined();
float red = area.getRed();
float green = area.getGreen();
float blue = area.getBlue();
FontMetricsMapper mapper;
try {
mapper = (FontMetricsMapper)
area.getFontState().getFontInfo().getMetricsFor(name);
} catch (FOPException iox) {
mapper = new FontMetricsMapper("MonoSpaced",
java.awt.Font.PLAIN, graphics);
}
if ((!name.equals(this.currentFontName)) ||
(size != this.currentFontSize)) {
this.currentFontName = name;
this.currentFontSize = size;
}
if ((red != this.currentRed) || (green != this.currentGreen) ||
(blue != this.currentBlue)) {
this.currentRed = red;
this.currentGreen = green;
this.currentBlue = blue;
}
int rx = this.currentXPosition;
int bl = this.currentYPosition;
String s;// = area.getText();
if (area.getPageNumberID() != null) { // this text is a page number, so resolve it
s = tree.getIDReferences().getPageNumber(area.getPageNumberID());
if (s == null) {
s = "";
}
} else {
s = area.getText();
}
Color oldColor = graphics.getColor();
java.awt.Font oldFont = graphics.getFont();
java.awt.Font f = mapper.getFont(size);
if (saveColor != null) {
if (saveColor.getRed() != red ||
saveColor.getGreen() != green ||
saveColor.getBlue() != blue) {
saveColor = new Color(red, green, blue);
}
} else {
saveColor = new Color(red, green, blue);
}
graphics.setColor(saveColor);
AttributedString ats = new AttributedString(s);
ats.addAttribute(TextAttribute.FONT, f);
if (underlined) {
ats.addAttribute(TextAttribute.UNDERLINE,
TextAttribute.UNDERLINE_ON);
}
AttributedCharacterIterator iter = ats.getIterator();
// correct integer roundoff
// graphics.drawString(iter, rx / 1000f,
// (int)(pageHeight - bl / 1000f));
graphics.drawString(iter, (rx + 500) / 1000,
(int)(pageHeight - (bl + 500) / 1000));
graphics.setColor(oldColor);
this.currentXPosition += area.getContentWidth();
}
public void renderInlineSpace(InlineSpace space) {
this.currentXPosition += space.getSize();
}
public void renderLineArea(LineArea area) {
int rx = this.currentAreaContainerXPosition + area.getStartIndent();
int ry = this.currentYPosition;
int w = area.getContentWidth();
int h = area.getHeight();
this.currentYPosition -= area.getPlacementOffset();
this.currentXPosition = rx;
int bl = this.currentYPosition;
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
org.apache.fop.layout.Box b =
(org.apache.fop.layout.Box) e.nextElement();
if (b instanceof InlineArea) {
InlineArea ia = (InlineArea) b;
this.currentYPosition = ry - ia.getYOffset();
} else {
this.currentYPosition = ry - area.getPlacementOffset();
}
b.render(this);
}
this.currentYPosition = ry - h;
}
/**
* render leader area into AWT
*
* @param area area to render
*/
// call to addRect corrected by aml/rlc
public void renderLeaderArea(LeaderArea area) {
int rx = this.currentXPosition;
int ry = this.currentYPosition;
int w = area.getLeaderLength();
int h = area.getHeight();
int th = area.getRuleThickness();
int st = area.getRuleStyle(); //not used at the moment
float r = area.getRed();
float g = area.getGreen();
float b = area.getBlue();
Color oldColor = graphics.getColor();
graphics.setColor(new Color(r, g, b));
// use helper function to correct integer roundoff - aml/rlc
// graphics.fillRect((int)(rx / 1000f),
// (int)(pageHeight - ry / 1000f), (int)(w / 1000f),
// (int)(th / 1000f));
addRect (rx, ry, w, -th, false); // NB addRect expects negative height
graphics.setColor(oldColor);
this.currentXPosition += area.getContentWidth();
}
public void renderSVGArea(SVGArea area) {
int x = this.currentXPosition;
int y = this.currentYPosition;
int w = area.getContentWidth();
int h = area.getHeight();
Document doc = area.getSVGDocument();
renderSVGDocument(doc, x, y);
this.currentXPosition += area.getContentWidth();
}
protected void renderSVGDocument(Document doc, int x, int y) {
UserAgent userAgent = new MUserAgent(new AffineTransform());
GVTBuilder builder = new GVTBuilder();
GraphicsNodeRenderContext rc = getRenderContext();
BridgeContext ctx = new BridgeContext(userAgent, rc);
GraphicsNode root;
// correct integer roundoff aml/rlc
// graphics.translate(x / 1000f, pageHeight - y / 1000f);
graphics.translate((x + 500) / 1000, pageHeight - (y + 500) / 1000);
graphics.setRenderingHints(rc.getRenderingHints());
try {
root = builder.build(ctx, doc);
root.paint(graphics, rc);
} catch (Exception e) {
e.printStackTrace();
}
// correct integer roundoff aml/rlc
// graphics.translate(-x / 1000f, y / 1000f - pageHeight);
graphics.translate(-(x + 500) / 1000, (y + 500) / 1000 - pageHeight);
}
public GraphicsNodeRenderContext getRenderContext() {
GraphicsNodeRenderContext nodeRenderContext = null;
if (nodeRenderContext == null) {
RenderingHints hints = new RenderingHints(null);
hints.put(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
hints.put(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
FontRenderContext fontRenderContext =
new FontRenderContext(new AffineTransform(), true,
true);
TextPainter textPainter = new StrokingTextPainter();
GraphicsNodeRableFactory gnrFactory =
new ConcreteGraphicsNodeRableFactory();
nodeRenderContext = new GraphicsNodeRenderContext(
new AffineTransform(), null, hints,
fontRenderContext, textPainter, gnrFactory);
}
return nodeRenderContext;
}
public void setProducer(String producer) {
// defined in Renderer Interface
}
public int print(Graphics g, PageFormat pageFormat,
int pageIndex) throws PrinterException {
if (pageIndex >= tree.getPages().size())
return NO_SUCH_PAGE;
Graphics2D oldGraphics = graphics;
int oldPageNumber = pageNumber;
graphics = (Graphics2D) g;
Page aPage = (Page) tree.getPages().elementAt(pageIndex);
renderPage(aPage);
graphics = oldGraphics;
return PAGE_EXISTS;
}
public int getNumberOfPages() {
return tree.getPages().size();
}
public PageFormat getPageFormat(int pageIndex)
throws IndexOutOfBoundsException {
if (pageIndex >= tree.getPages().size())
return null;
Page page = (Page) tree.getPages().elementAt(pageIndex);
PageFormat pageFormat = new PageFormat();
Paper paper = new Paper();
double width = page.getWidth();
double height = page.getHeight();
// if the width is greater than the height assume lanscape mode
// and swap the width and height values in the paper format
if(width > height)
{
paper.setImageableArea(0, 0, height / 1000d, width / 1000d);
paper.setSize(height / 1000d, width / 1000d);
pageFormat.setOrientation(PageFormat.LANDSCAPE);
}
else
{
paper.setImageableArea(0, 0, width / 1000d, height / 1000d);
paper.setSize(width / 1000d, height / 1000d);
pageFormat.setOrientation(PageFormat.PORTRAIT);
}
pageFormat.setPaper(paper);
return pageFormat;
}
public Printable getPrintable(int pageIndex)
throws IndexOutOfBoundsException {
return this;
}
public void setProgressListener(ProgressListener l) {
progressListener = l;
}
public static Color colorType2Color(ColorType ct) {
if (ct == null) {
return null;
}
return new Color(ct.red(), ct.green(), ct.blue());
}
/**
* Draws an image.
* TODO: protect other image formats (JIMI)
*/
/* public void renderImage(String href, float x, float y, float width,
float height, Vector transform) {
// What is with transformations?
try {
URL url = new URL(href);
ImageIcon imageIcon = new ImageIcon(url);
AffineTransform fullTransform = new AffineTransform();
AffineTransform aTransform;
transform = (transform == null) ? new Vector() : transform;
for (int i = 0; i < transform.size(); i++) {
org.w3c.dom.svg.SVGTransform t =
(org.w3c.dom.svg.SVGTransform)
transform.elementAt(i);
SVGMatrix matrix = t.getMatrix();
aTransform = new AffineTransform(matrix.getA(),
matrix.getB(), matrix.getC(), matrix.getD(),
matrix.getE(), matrix.getF());
fullTransform.concatenate(aTransform);
}
BufferedImage bi = new BufferedImage((int) width, (int) height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bi.createGraphics();
BufferedImageOp bop = new AffineTransformOp(fullTransform,
AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
g2d.drawImage(imageIcon.getImage(), 0, 0, (int) width,
(int) height, imageIcon.getImageObserver());
graphics.drawImage(bi, bop, (int) x, (int) y);
} catch (Exception ex) {
MessageHandler.errorln("AWTRenderer: renderImage(): " +
ex.getMessage());
}
}*/
public void renderForeignObjectArea(ForeignObjectArea area) {
area.getObject().render(this);
}
protected class MUserAgent implements UserAgent {
AffineTransform currentTransform = null;
/**
* Creates a new SVGUserAgent.
*/
protected MUserAgent(AffineTransform at) {
currentTransform = at;
}
/**
* Displays an error message.
*/
public void displayError(String message) {
System.err.println(message);
}
/**
* Displays an error resulting from the specified Exception.
*/
public void displayError(Exception ex) {
ex.printStackTrace(System.err);
}
/**
* Displays a message in the User Agent interface.
* The given message is typically displayed in a status bar.
*/
public void displayMessage(String message) {
System.out.println(message);
}
/**
* Returns a customized the pixel to mm factor.
*/
public float getPixelToMM() {
return 0.264583333333333333333f; // 72 dpi
}
/**
* Returns the language settings.
*/
public String getLanguages() {
return "en";//userLanguages;
}
/**
* Returns the user stylesheet uri.
* @return null if no user style sheet was specified.
*/
public String getUserStyleSheetURI() {
return null;//userStyleSheetURI;
}
/**
* Returns the class name of the XML parser.
*/
public String getXMLParserClassName() {
return Driver.getParserClassName();
}
/**
* Opens a link in a new component.
* @param doc The current document.
* @param uri The document URI.
*/
public void openLink(SVGAElement elt) {
//application.openLink(uri);
}
public Point getClientAreaLocationOnScreen() {
return new Point(0, 0);
}
public void setSVGCursor(java.awt.Cursor cursor) {
}
public AffineTransform getTransform() {
return currentTransform;
}
public Dimension2D getViewportSize() {
return new Dimension(100, 100);
}
public EventDispatcher getEventDispatcher() {
return null;
}
public boolean supportExtension(String str) {
return false;
}
public boolean hasFeature(String str) {
return false;
}
public void registerExtension(BridgeExtension be) {
}
}
}
|
package org.apache.fop.render.awt;
/*
originally contributed by
Juergen Verwohlt: Juergen.Verwohlt@af-software.de,
Rainer Steinkuhle: Rainer.Steinkuhle@af-software.de,
Stanislav Gorkhover: Stanislav.Gorkhover@af-software.de
*/
import org.apache.fop.layout.*;
import org.apache.fop.datatypes.*;
import org.apache.fop.image.*;
import org.apache.fop.svg.*;
import org.apache.fop.render.pdf.*;
import org.apache.fop.viewer.*;
import org.apache.fop.apps.*;
import org.apache.fop.render.Renderer;
import java.awt.*;
import java.awt.image.*;
import java.awt.geom.*;
import java.awt.font.*;
import java.util.*;
import java.io.*;
import java.beans.*;
import javax.swing.*;
import java.awt.print.*;
import java.awt.image.BufferedImage;
public class AWTRenderer implements Renderer, Printable, Pageable {
protected int pageWidth = 0;
protected int pageHeight = 0;
protected double scaleFactor = 100.0;
protected int pageNumber = 0;
protected AreaTree tree;
protected ProgressListener progressListener = null;
protected Translator res = null;
protected Hashtable fontNames = new Hashtable();
protected Hashtable fontStyles = new Hashtable();
protected Color saveColor;
// Key - Font name, Value - java Font name.
protected static Hashtable JAVA_FONT_NAMES;
/**
* Image Object and Graphics Object. The Graphics Object is the Graphics
* object that is contained withing the Image Object.
*/
private BufferedImage pageImage = null;
private Graphics2D graphics = null;
/**
* The current (internal) font name
*/
protected String currentFontName;
/**
* The current font size in millipoints
*/
protected int currentFontSize;
/**
* The current colour's red, green and blue component
*/
protected float currentRed = 0;
protected float currentGreen = 0;
protected float currentBlue = 0;
/**
* The current vertical position in millipoints from bottom
*/
protected int currentYPosition = 0;
/**
* The current horizontal position in millipoints from left
*/
protected int currentXPosition = 0;
/**
* The horizontal position of the current area container
*/
private int currentAreaContainerXPosition = 0;
static {
JAVA_FONT_NAMES = new Hashtable();
JAVA_FONT_NAMES.put("Times", "serif");
JAVA_FONT_NAMES.put("Times-Roman", "serif");
JAVA_FONT_NAMES.put("Courier", "monospaced");
JAVA_FONT_NAMES.put("Helvetica", "sansserif");
// JAVA_FONT_NAMES.put("Serif", "sansserif");
}
public AWTRenderer(Translator aRes) {
res = aRes;
}
public int getPageNumber() {
return pageNumber;
}
public void setPageNumber(int aValue) {
pageNumber = aValue;
}
public void setScaleFactor(double newScaleFactor) {
scaleFactor = newScaleFactor;
}
public double getScaleFactor() {
return scaleFactor;
}
public BufferedImage getLastRenderedPage() {
return pageImage;
}
/**
* add a line to the current stream
*
* @param x1 the start x location in millipoints
* @param y1 the start y location in millipoints
* @param x2 the end x location in millipoints
* @param y2 the end y location in millipoints
* @param th the thickness in millipoints
* @param r the red component
* @param g the green component
* @param b the blue component
*/
protected void addLine(int x1, int y1, int x2, int y2, int th,
float r, float g, float b) {
graphics.setColor(new Color (r,g,b));
graphics.drawLine((int)(x1/1000f), pageHeight - (int)(y1/1000f),
(int)(x2/1000f), pageHeight - (int)(y2/1000f));
}
/**
* draw a filled rectangle
*
* @param x the x position of left edge in millipoints
* @param y the y position of top edge in millipoints
* @param w the width in millipoints
* @param h the height in millipoints
* @param r the red component
* @param g the green component
* @param b the blue component
*/
protected void addRect(int x, int y, int w, int h,
float r, float g, float b) {
graphics.setColor(new Color (r,g,b));
graphics.fill3DRect((int) (x/1000f), pageHeight - (int) (y/1000f),
(int) (w/1000f), -(int) (h/1000f),false);
}
/**
* draw a filled rectangle
*
* @param x the x position of left edge in millipoints
* @param y the y position of top edge in millipoints
* @param w the width in millipoints
* @param h the height in millipoints
* @param r the red component of edges
* @param g the green component of edges
* @param b the blue component of edges
* @param fr the red component of the fill
* @param fg the green component of the fill
* @param fb the blue component of the fill
*/
protected void addRect(int x, int y, int w, int h,
float r, float g, float b,
float fr, float fg, float fb) {
graphics.setColor(new Color (r,g,b));
graphics.fill3DRect((int) (x/1000f), pageHeight - (int) (y/1000f),
(int) (w/1000f), -(int) (h/1000f),true);
}
/**
* Vor dem Druck einzustellen:
*
* Seite/Seiten whlen
* Zoomfaktor
* Seitenformat / Quer- oder Hoch
**/
public void transform(Graphics2D g2d, double zoomPercent, double angle) {
AffineTransform at = g2d.getTransform();
at.rotate(angle);
at.scale(zoomPercent/100.0, zoomPercent/100.0);
g2d.setTransform(at);
}
protected void drawFrame() {
int width = pageWidth;
int height = pageHeight;
graphics.setColor(Color.white);
graphics.fillRect(0, 0, width, height);
graphics.setColor(Color.black);
graphics.drawRect(-1, -1, width+2, height+2);
graphics.drawLine(width+2, 0, width+2, height+2);
graphics.drawLine(width+3, 1, width+3, height+3);
graphics.drawLine(0, height+2, width+2, height+2);
graphics.drawLine(1, height+3, width+3, height+3);
}
/**
* Retrieve the number of pages in this document.
*
* @return the number of pages
*/
public int getPageCount()
{
if (tree == null) {
return 0;
}
return tree.getPages().size();
}
public void render(int aPageNumber) {
if (tree != null) {
try {
render(tree, aPageNumber);
} catch (IOException e) {
// This exception can't occur because we are not dealing with
// any files.
}
}
}
public void render(AreaTree areaTree, PrintWriter writer)
throws IOException {
tree = areaTree;
render(areaTree,0);
}
public void render(AreaTree areaTree, int aPageNumber)
throws IOException {
tree = areaTree;
Page page = (Page)areaTree.getPages().elementAt(aPageNumber);
pageWidth = (int)((float)page.getWidth() / 1000f);
pageHeight = (int)((float)page.getHeight() / 1000f);
pageImage = new BufferedImage((int)((pageWidth * (int)scaleFactor)/100),
(int)((pageHeight * (int)scaleFactor)/100),
BufferedImage.TYPE_INT_RGB);
graphics = pageImage.createGraphics();
transform(graphics, scaleFactor, 0);
drawFrame();
renderPage(page);
}
public void renderPage(Page page) {
AreaContainer body, before, after;
body = page.getBody();
before = page.getBefore();
after = page.getAfter();
this.currentFontName = "";
this.currentFontSize = 0;
renderAreaContainer(body);
if (before != null) {
renderAreaContainer(before);
}
if (after != null) {
renderAreaContainer(after);
}
}
public void renderAreaContainer(AreaContainer area) {
int saveY = this.currentYPosition;
int saveX = this.currentAreaContainerXPosition;
if (area.getPosition() ==
org.apache.fop.fo.properties.Position.ABSOLUTE) {
// Y position is computed assuming positive Y axis, adjust
//for negative postscript one
this.currentYPosition = area.getYPosition() -
2 * area.getPaddingTop() -
2 * area.borderWidthTop;
this.currentAreaContainerXPosition = area.getXPosition();
} else if (area.getPosition() ==
org.apache.fop.fo.properties.Position.RELATIVE) {
this.currentYPosition -= area.getYPosition();
this.currentAreaContainerXPosition += area.getXPosition();
} else if (area.getPosition() ==
org.apache.fop.fo.properties.Position.STATIC) {
this.currentYPosition -= area.getPaddingTop() + area.borderWidthTop;
this.currentAreaContainerXPosition += area.getPaddingLeft() +
area.borderWidthLeft;
}
doFrame(area);
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
org.apache.fop.layout.Box b =
(org.apache.fop.layout.Box) e.nextElement();
b.render(this);
}
if (area.getPosition() !=
org.apache.fop.fo.properties.Position.STATIC) {
this.currentYPosition = saveY;
this.currentAreaContainerXPosition = saveX;
} else {
this.currentYPosition -= area.getHeight();
}
}
private void doFrame(org.apache.fop.layout.Area area) {
int w, h;
int rx = this.currentAreaContainerXPosition;
w = area.getContentWidth();
if (area instanceof BlockArea) {
rx += ((BlockArea)area).getStartIndent();
}
h = area.getContentHeight();
int ry = this.currentYPosition;
ColorType bg = area.getBackgroundColor();
rx = rx - area.getPaddingLeft();
ry = ry + area.getPaddingTop();
w = w + area.getPaddingLeft() + area.getPaddingRight();
h = h + area.getPaddingTop() + area.getPaddingBottom();
// I'm not sure I should have to check for bg being null
// but I do
if ((bg != null) && (bg.alpha() == 0)) {
this.addRect(rx, ry, w, -h,
bg.red(), bg.green(), bg.blue(),
bg.red(), bg.green(), bg.blue());
}
rx = rx - area.borderWidthLeft;
ry = ry + area.borderWidthTop;
w = w + area.borderWidthLeft + area.borderWidthRight;
h = h + area.borderWidthTop + area.borderWidthBottom;
if (area.borderWidthTop != 0) {
addLine(rx, ry, rx + w, ry,
area.borderWidthTop,
area.borderColorTop.red(), area.borderColorTop.green(),
area.borderColorTop.blue());
}
if (area.borderWidthLeft != 0) {
addLine(rx, ry, rx, ry - h,
area.borderWidthLeft,
area.borderColorLeft.red(), area.borderColorLeft.green(),
area.borderColorLeft.blue());
}
if (area.borderWidthRight != 0) {
addLine(rx + w, ry, rx + w, ry - h,
area.borderWidthRight,
area.borderColorRight.red(), area.borderColorRight.green(),
area.borderColorRight.blue());
}
if (area.borderWidthBottom != 0) {
addLine(rx, ry - h, rx + w, ry - h,
area.borderWidthBottom,
area.borderColorBottom.red(), area.borderColorBottom.green(),
area.borderColorBottom.blue());
}
}
protected Rectangle2D getBounds(org.apache.fop.layout.Area a) {
return new Rectangle2D.Double(currentAreaContainerXPosition,
currentYPosition,
a.getAllocationWidth(),
a.getHeight());
}
public void renderBlockArea(BlockArea area) {
doFrame(area);
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
org.apache.fop.layout.Box b =
(org.apache.fop.layout.Box) e.nextElement();
b.render(this);
}
}
public void setupFontInfo(FontInfo fontInfo) {
FontSetup.setup(fontInfo);
Hashtable hash = fontInfo.getFonts();
org.apache.fop.render.pdf.Font f;
String name;
Object key;
int fontStyle;
for (Enumeration e = hash.keys(); e.hasMoreElements();) {
fontStyle = java.awt.Font.PLAIN;
key = e.nextElement();
f = (org.apache.fop.render.pdf.Font)hash.get(key);
name = f.fontName();
if (name.toUpperCase().indexOf("BOLD") > 0) {
fontStyle += java.awt.Font.BOLD;
}
if (name.toUpperCase().indexOf("ITALIC") > 0 ||
name.toUpperCase().indexOf("OBLIQUE") > 0) {
fontStyle += java.awt.Font.ITALIC;
}
int hyphenIndex = name.indexOf("-");
hyphenIndex = (hyphenIndex < 0) ? name.length() : hyphenIndex;
fontNames.put(key, name.substring(0, hyphenIndex));
fontStyles.put(key, new Integer(fontStyle));
}
}
public void renderDisplaySpace(DisplaySpace space) {
int d = space.getSize();
this.currentYPosition -= d;
}
public void renderImageArea(ImageArea area) {
int x = this.currentAreaContainerXPosition +
area.getXOffset();
int y = this.currentYPosition;
int w = area.getContentWidth();
int h = area.getHeight();
FopImage img = area.getImage();
if (img == null) {
System.out.println("area.getImage() is null");
}
int[] map = img.getimagemap();
String path = img.gethref();
ImageIcon icon = new ImageIcon(path);
Image imgage = icon.getImage();
graphics.drawImage(imgage, currentXPosition / 1000,
pageHeight - y / 1000,
img.getWidth() / 1000,
img.getHeight() / 1000,
null);
currentYPosition -= h;
}
public void renderInlineArea(InlineArea area) {
char ch;
StringBuffer pdf = new StringBuffer();
String name = area.getFontState().getFontName();
int size = area.getFontState().getFontSize();
float red = area.getRed();
float green = area.getGreen();
float blue = area.getBlue();
if ((!name.equals(this.currentFontName))
|| (size != this.currentFontSize)) {
this.currentFontName = name;
this.currentFontSize = size;
}
if ((red != this.currentRed)
|| (green != this.currentGreen)
|| (blue != this.currentBlue)) {
this.currentRed = red;
this.currentGreen = green;
this.currentBlue = blue;
}
int rx = this.currentXPosition;
int bl = this.currentYPosition;
String s = area.getText();
Color oldColor = graphics.getColor();
java.awt.Font oldFont = graphics.getFont();
String aFontName = fontNames.get(name).toString();
aFontName = getJavaFontName(aFontName);
java.awt.Font f =
new java.awt.Font(aFontName,
((Integer)fontStyles.get(name)).intValue(),
(int)(size / 1000f));
graphics.setColor(new Color(red, green, blue));
/*
Die KLasse TextLayout nimmt fr die Ausgabe eigenen Schriftsatz,
der i.R. breiter ist. Deshalb wird bis diese Tatsache sich geklrt/
geregelt hat weniger schne Ausgabe ber Graphics benutzt.
*/
// Fonts in bold still have trouble displaying!
FontRenderContext newContext = new FontRenderContext(null, true, true);
TextLayout layout = new TextLayout(s, f, newContext);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
layout.draw(graphics, rx / 1000f, (int)(pageHeight - bl / 1000f));
graphics.setColor(oldColor);
this.currentXPosition += area.getContentWidth();
}
public void renderInlineSpace(InlineSpace space) {
this.currentXPosition += space.getSize();
}
public void renderLineArea(LineArea area) {
int rx = this.currentAreaContainerXPosition
+ area.getStartIndent();
int ry = this.currentYPosition;
int w = area.getContentWidth();
int h = area.getHeight();
this.currentYPosition -= area.getPlacementOffset();
this.currentXPosition = rx;
int bl = this.currentYPosition;
Enumeration e = area.getChildren().elements();
while (e.hasMoreElements()) {
org.apache.fop.layout.Box b =
(org.apache.fop.layout.Box) e.nextElement();
b.render(this);
}
this.currentYPosition = ry-h;
}
/**
* render rule area into PDF
*
* @param area area to render
*/
public void renderRuleArea(RuleArea area) {
int rx = this.currentAreaContainerXPosition
+ area.getStartIndent();
int ry = this.currentYPosition;
int w = area.getContentWidth();
int h = area.getHeight();
int th = area.getRuleThickness();
float r = area.getRed();
float g = area.getGreen();
float b = area.getBlue();
Color oldColor = graphics.getColor();
graphics.setColor(new Color(r, g, b));
graphics.fillRect((int)(rx / 1000f), (int)(pageHeight - ry / 1000f),
(int)(w / 1000f), (int)(th / 1000f));
graphics.setColor(oldColor);
}
public void renderSVGArea(SVGArea area) {
int x = this.currentAreaContainerXPosition;
int y = this.currentYPosition;
int w = area.getContentWidth();
int h = area.getHeight();
this.currentYPosition -= h;
// Enumeration e = area.getChildren().elements();
// while (e.hasMoreElements()) {
// Object o = e.nextElement();
// if (o instanceof RectGraphic) {
// int rx = ((RectGraphic)o).x;
// int ry = ((RectGraphic)o).y;
// int rw = ((RectGraphic)o).width;
// int rh = ((RectGraphic)o).height;
// addRect(x+rx,y-ry,rw,-rh,0,0,0);
// } else if (o instanceof LineGraphic) {
// int x1 = ((LineGraphic)o).x1;
// int y1 = ((LineGraphic)o).y1;
// int x2 = ((LineGraphic)o).x2;
// int y2 = ((LineGraphic)o).y2;
// addLine(x+x1,y-y1,x+x2,y-y2,0,0,0,0);
// } else if (o instanceof TextGraphic) {
// int tx = ((TextGraphic)o).x;
// int ty = ((TextGraphic)o).y;
// String s = ((TextGraphic)o).s;
// currentStream.add("1 0 0 1 "
// + ((x+tx)/1000f) + " "
// + ((y-ty)/1000f) + " Tm "
// + "(" + s + ") Tj\n");
}
protected String getJavaFontName(String aName) {
if (aName == null)
return null;
Object o = JAVA_FONT_NAMES.get(aName);
return (o == null) ? aName : o.toString();
}
public void setProducer(String producer) {
// defined in Renderer Interface
}
public int print(Graphics g, PageFormat pageFormat, int pageIndex)
throws PrinterException {
if (pageIndex >= tree.getPages().size())
return NO_SUCH_PAGE;
Graphics2D oldGraphics = graphics;
int oldPageNumber = pageNumber;
graphics = (Graphics2D)g;
Page aPage = (Page)tree.getPages().elementAt(pageIndex);
renderPage(aPage);
graphics = oldGraphics;
return PAGE_EXISTS;
}
public int getNumberOfPages() {
return tree.getPages().size();
}
public PageFormat getPageFormat(int pageIndex)
throws IndexOutOfBoundsException {
if (pageIndex >= tree.getPages().size())
return null;
Page page = (Page)tree.getPages().elementAt(pageIndex);
PageFormat pageFormat = new PageFormat();
Paper paper = new Paper();
paper.setImageableArea(0, 0,
page.getWidth() / 1000d, page.getHeight() / 1000d);
paper.setSize(page.getWidth() / 1000d, page.getHeight() / 1000d);
pageFormat.setPaper(paper);
return pageFormat;
}
public Printable getPrintable(int pageIndex)
throws IndexOutOfBoundsException {
return this;
}
public void setProgressListener(ProgressListener l) {
progressListener = l;
}
public static Color colorType2Color(ColorType ct) {
if (ct == null) {
return null;
}
return new Color(ct.red(), ct.green(), ct.blue());
}
}
|
package org.apache.fop.render.pdf;
// FOP
import org.apache.fop.render.PrintRenderer;
import org.apache.fop.messaging.MessageHandler;
import org.apache.fop.image.ImageArea;
import org.apache.fop.image.FopImage;
import org.apache.fop.apps.FOPException;
import org.apache.fop.fo.properties.*;
import org.apache.fop.layout.inline.*;
import org.apache.fop.datatypes.*;
import org.apache.fop.svg.*;
import org.apache.fop.pdf.*;
import org.apache.fop.layout.*;
import org.apache.fop.image.*;
import org.apache.fop.extensions.*;
import org.apache.fop.datatypes.IDReferences;
import org.apache.batik.bridge.*;
import org.apache.batik.swing.svg.*;
import org.apache.batik.swing.gvt.*;
import org.apache.batik.gvt.*;
import org.apache.batik.gvt.renderer.*;
import org.apache.batik.gvt.filter.*;
import org.apache.batik.gvt.event.*;
import org.w3c.dom.*;
import org.w3c.dom.svg.*;
import org.w3c.dom.css.*;
import org.w3c.dom.svg.SVGLength;
// Java
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Vector;
import java.util.Hashtable;
import java.awt.geom.AffineTransform;
import java.awt.geom.Dimension2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.Dimension;
/**
* Renderer that renders areas to PDF
*/
public class PDFRenderer extends PrintRenderer {
/** the PDF Document being created */
protected PDFDocument pdfDoc;
/** the /Resources object of the PDF document being created */
protected PDFResources pdfResources;
/** the current stream to add PDF commands to */
PDFStream currentStream;
/** the current annotation list to add annotations to */
PDFAnnotList currentAnnotList;
/** the current page to add annotations to */
PDFPage currentPage;
PDFColor currentColor;
/** true if a TJ command is left to be written */
boolean textOpen = false;
/** the previous Y coordinate of the last word written.
Used to decide if we can draw the next word on the same line. */
int prevWordY = 0;
/** the previous X coordinate of the last word written.
used to calculate how much space between two words */
int prevWordX = 0;
/** The width of the previous word. Used to calculate space between */
int prevWordWidth = 0;
private PDFOutline rootOutline;
/** reusable word area string buffer to reduce memory usage */
private StringBuffer _wordAreaPDF = new StringBuffer();
/** options */
protected Hashtable options;
/**
* create the PDF renderer
*/
public PDFRenderer() {
this.pdfDoc = new PDFDocument();
}
/** set up renderer options */
public void setOptions(Hashtable options) {
this.options = options;
}
/**
* set the PDF document's producer
*
* @param producer string indicating application producing PDF
*/
public void setProducer(String producer) {
this.pdfDoc.setProducer(producer);
}
/**
* render the areas into PDF
*
* @param areaTree the laid-out area tree
* @param stream the OutputStream to write the PDF to
*/
public void render(AreaTree areaTree,
OutputStream stream) throws IOException, FOPException {
MessageHandler.logln("rendering areas to PDF");
idReferences = areaTree.getIDReferences();
this.pdfResources = this.pdfDoc.getResources();
this.pdfDoc.setIDReferences(idReferences);
Enumeration e = areaTree.getPages().elements();
while (e.hasMoreElements()) {
this.renderPage((Page) e.nextElement());
}
if (!idReferences.isEveryIdValid()) {
// throw new FOPException("The following id's were referenced but not found: "+idReferences.getInvalidIds()+"\n");
MessageHandler.errorln("WARNING: The following id's were referenced but not found: "+
idReferences.getInvalidIds() + "\n");
}
renderRootExtensions(areaTree);
FontSetup.addToResources(this.pdfDoc, fontInfo);
MessageHandler.logln("writing out PDF");
this.pdfDoc.output(stream);
}
/**
* add a line to the current stream
*
* @param x1 the start x location in millipoints
* @param y1 the start y location in millipoints
* @param x2 the end x location in millipoints
* @param y2 the end y location in millipoints
* @param th the thickness in millipoints
* @param r the red component
* @param g the green component
* @param b the blue component
*/
protected void addLine(int x1, int y1, int x2, int y2, int th,
PDFPathPaint stroke) {
closeText();
currentStream.add("ET\nq\n" + stroke.getColorSpaceOut(false) +
(x1 / 1000f) + " "+ (y1 / 1000f) + " m " +
(x2 / 1000f) + " "+ (y2 / 1000f) + " l " +
(th / 1000f) + " w S\n" + "Q\nBT\n");
}
/**
* add a line to the current stream
*
* @param x1 the start x location in millipoints
* @param y1 the start y location in millipoints
* @param x2 the end x location in millipoints
* @param y2 the end y location in millipoints
* @param th the thickness in millipoints
* @param rs the rule style
* @param r the red component
* @param g the green component
* @param b the blue component
*/
protected void addLine(int x1, int y1, int x2, int y2, int th,
int rs, PDFPathPaint stroke) {
closeText();
currentStream.add("ET\nq\n" + stroke.getColorSpaceOut(false) +
setRuleStylePattern(rs) + (x1 / 1000f) + " "+
(y1 / 1000f) + " m " + (x2 / 1000f) + " "+
(y2 / 1000f) + " l " + (th / 1000f) + " w S\n" + "Q\nBT\n");
}
/**
* add a rectangle to the current stream
*
* @param x the x position of left edge in millipoints
* @param y the y position of top edge in millipoints
* @param w the width in millipoints
* @param h the height in millipoints
* @param stroke the stroke color/gradient
*/
protected void addRect(int x, int y, int w, int h,
PDFPathPaint stroke) {
closeText();
currentStream.add("ET\nq\n" + stroke.getColorSpaceOut(false) +
(x / 1000f) + " " + (y / 1000f) + " " + (w / 1000f) +
" " + (h / 1000f) + " re s\n" + "Q\nBT\n");
}
/**
* add a filled rectangle to the current stream
*
* @param x the x position of left edge in millipoints
* @param y the y position of top edge in millipoints
* @param w the width in millipoints
* @param h the height in millipoints
* @param fill the fill color/gradient
* @param stroke the stroke color/gradient
*/
protected void addRect(int x, int y, int w, int h,
PDFPathPaint stroke, PDFPathPaint fill) {
closeText();
currentStream.add("ET\nq\n" + fill.getColorSpaceOut(true) +
stroke.getColorSpaceOut(false) + (x / 1000f) + " " +
(y / 1000f) + " " + (w / 1000f) + " " + (h / 1000f) +
" re b\n" + "Q\nBT\n");
}
/**
* render image area to PDF
*
* @param area the image area to render
*/
public void renderImageArea(ImageArea area) {
// adapted from contribution by BoBoGi
int x = this.currentXPosition + area.getXOffset();
int y = this.currentYPosition;
int w = area.getContentWidth();
int h = area.getHeight();
this.currentYPosition -= h;
FopImage img = area.getImage();
if (img instanceof SVGImage) {
try {
closeText();
SVGDocument svg =
((SVGImage) img).getSVGDocument();
currentStream.add("ET\nq\n");
renderSVGDocument(svg, (int) x, (int) y, area.getFontState());
currentStream.add("Q\nBT\n");
} catch (FopImageException e) {
}
} else {
int xObjectNum = this.pdfDoc.addImage(img);
closeText();
currentStream.add("ET\nq\n" + (((float) w) / 1000f) +
" 0 0 " + (((float) h) / 1000f) + " " +
(((float) x) / 1000f) + " " +
(((float)(y - h)) / 1000f) + " cm\n" + "/Im" +
xObjectNum + " Do\nQ\nBT\n");
}
this.currentXPosition += area.getContentWidth();
}
/** render a foreign object area */
public void renderForeignObjectArea(ForeignObjectArea area) {
// if necessary need to scale and align the content
this.currentXPosition = this.currentXPosition + area.getXOffset();
this.currentYPosition = this.currentYPosition;
switch (area.getAlign()) {
case TextAlign.START:
break;
case TextAlign.END:
break;
case TextAlign.CENTER:
case TextAlign.JUSTIFY:
break;
}
switch (area.getVerticalAlign()) {
case VerticalAlign.BASELINE:
break;
case VerticalAlign.MIDDLE:
break;
case VerticalAlign.SUB:
break;
case VerticalAlign.SUPER:
break;
case VerticalAlign.TEXT_TOP:
break;
case VerticalAlign.TEXT_BOTTOM:
break;
case VerticalAlign.TOP:
break;
case VerticalAlign.BOTTOM:
break;
}
closeText();
// in general the content will not be text
currentStream.add("ET\n");
// align and scale
currentStream.add("q\n");
switch (area.scalingMethod()) {
case Scaling.UNIFORM:
break;
case Scaling.NON_UNIFORM:
break;
}
// if the overflow is auto (default), scroll or visible
// then the contents should not be clipped, since this
// is considered a printing medium.
switch (area.getOverflow()) {
case Overflow.VISIBLE:
case Overflow.SCROLL:
case Overflow.AUTO:
break;
case Overflow.HIDDEN:
break;
}
area.getObject().render(this);
currentStream.add("Q\n");
currentStream.add("BT\n");
this.currentXPosition += area.getEffectiveWidth();
// this.currentYPosition -= area.getEffectiveHeight();
}
/**
* render SVG area to PDF
*
* @param area the SVG area to render
*/
public void renderSVGArea(SVGArea area) {
// place at the current instream offset
int x = this.currentXPosition;
int y = this.currentYPosition;
renderSVGDocument(area.getSVGDocument(), x, y, area.getFontState());
}
protected void renderSVGDocument(Document doc, int x, int y, FontState fs) {
SVGSVGElement svg = ((SVGDocument)doc).getRootElement();
int w = (int)(svg.getWidth().getBaseVal().getValue() * 1000);
int h = (int)(svg.getHeight().getBaseVal().getValue() * 1000);
float sx = 1, sy = -1;
int xOffset = x, yOffset = y;
/*
* Clip to the svg area.
* Note: To have the svg overlay (under) a text area then use
* an fo:block-container
*/
currentStream.add("q\n");
if (w != 0 && h != 0) {
currentStream.add(x / 1000f + " " + y / 1000f + " m\n");
currentStream.add((x + w) / 1000f + " " + y / 1000f + " l\n");
currentStream.add((x + w) / 1000f + " " + (y - h) / 1000f +
" l\n");
currentStream.add(x / 1000f + " " + (y - h) / 1000f + " l\n");
currentStream.add("h\n");
currentStream.add("W\n");
currentStream.add("n\n");
}
// transform so that the coordinates (0,0) is from the top left
// and positive is down and to the right. (0,0) is where the
// viewBox puts it.
currentStream.add(sx + " 0 0 " + sy + " " + xOffset / 1000f +
" " + yOffset / 1000f + " cm\n");
UserAgent userAgent = new MUserAgent(new AffineTransform());
GVTBuilder builder = new GVTBuilder();
GraphicsNodeRenderContext rc = getRenderContext();
BridgeContext ctx = new BridgeContext(userAgent, rc);
GraphicsNode root;
PDFGraphics2D graphics =
new PDFGraphics2D(true, fs, pdfDoc,
currentFontName, currentFontSize, currentXPosition,
currentYPosition);
graphics.setGraphicContext(
new org.apache.batik.ext.awt.g2d.GraphicContext());
graphics.setRenderingHints(rc.getRenderingHints());
try {
root = builder.build(ctx, doc);
root.paint(graphics, rc);
currentStream.add(graphics.getString());
} catch (Exception e) {
MessageHandler.errorln("Error: svg graphic could not be rendered: " + e.getMessage());
}
currentStream.add("Q\n");
}
public GraphicsNodeRenderContext getRenderContext() {
GraphicsNodeRenderContext nodeRenderContext = null;
if (nodeRenderContext == null) {
RenderingHints hints = new RenderingHints(null);
hints.put(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
hints.put(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
FontRenderContext fontRenderContext =
new FontRenderContext(new AffineTransform(), true,
true);
TextPainter textPainter = new StrokingTextPainter();
//TextPainter textPainter = new PDFTextPainter();
GraphicsNodeRableFactory gnrFactory =
new ConcreteGraphicsNodeRableFactory();
nodeRenderContext = new GraphicsNodeRenderContext(
new AffineTransform(), null, hints,
fontRenderContext, textPainter, gnrFactory);
nodeRenderContext.setTextPainter(textPainter);
}
return nodeRenderContext;
}
/**
* render inline area to PDF
*
* @param area inline area to render
*/
public void renderWordArea(WordArea area) {
synchronized (_wordAreaPDF) {
StringBuffer pdf = _wordAreaPDF;
pdf.setLength(0);
Hashtable kerning = null;
boolean kerningAvailable = false;
kerning = area.getFontState().getKerning();
if (kerning != null && !kerning.isEmpty()) {
kerningAvailable = true;
}
String name = area.getFontState().getFontName();
int size = area.getFontState().getFontSize();
// This assumes that *all* CIDFonts use a /ToUnicode mapping
boolean useMultiByte = false;
Font f = (Font) area.getFontState().getFontInfo().getFonts().
get(name);
if (f instanceof CIDFont)
useMultiByte = true;
//String startText = useMultiByte ? "<FEFF" : "(";
String startText = useMultiByte ? "<" : "(";
String endText = useMultiByte ? "> " : ") ";
if ((!name.equals(this.currentFontName)) ||
(size != this.currentFontSize)) {
closeText();
this.currentFontName = name;
this.currentFontSize = size;
pdf = pdf.append("/" + name + " " + (size / 1000) + " Tf\n");
}
PDFColor areaColor = null;
if (this.currentFill instanceof PDFColor) {
areaColor = (PDFColor) this.currentFill;
}
if (areaColor == null ||
areaColor.red() != (double) area.getRed() ||
areaColor.green() != (double) area.getGreen() ||
areaColor.blue() != (double) area.getBlue()) {
areaColor = new PDFColor((double) area.getRed(),
(double) area.getGreen(), (double) area.getBlue());
closeText();
this.currentFill = areaColor;
pdf.append(this.currentFill.getColorSpaceOut(true));
}
int rx = this.currentXPosition;
int bl = this.currentYPosition;
addWordLines(area, rx, bl, size, areaColor);
if (!textOpen || bl != prevWordY) {
closeText();
pdf.append("1 0 0 1 " +(rx / 1000f) + " " +
(bl / 1000f) + " Tm [" + startText);
prevWordY = bl;
textOpen = true;
} else {
// express the space between words in thousandths of an em
int space = prevWordX - rx + prevWordWidth;
float emDiff =
(float) space / (float) currentFontSize * 1000f;
// this prevents a problem in Acrobat Reader where large
// numbers cause text to disappear or default to a limit
if(emDiff < -33000) {
closeText();
pdf.append("1 0 0 1 " +(rx / 1000f) + " " +
(bl / 1000f) + " Tm [" + startText);
textOpen = true;
} else {
pdf.append(Float.toString(emDiff));
pdf.append(" ");
pdf.append(startText);
}
}
prevWordWidth = area.getContentWidth();
prevWordX = rx;
String s;
if (area.getPageNumberID() != null) { // this text is a page number, so resolve it
s = idReferences.getPageNumber(area.getPageNumberID());
if (s == null) {
s = "";
}
} else {
s = area.getText();
}
int l = s.length();
for (int i = 0; i < l; i++) {
char ch = area.getFontState().mapChar(s.charAt(i));
if (!useMultiByte) {
if (ch > 127) {
pdf.append("\\");
pdf.append(Integer.toOctalString((int) ch));
} else {
switch (ch) {
case '(':
case ')':
case '\\':
pdf.append("\\");
break;
}
pdf.append(ch);
}
} else {
pdf.append(getUnicodeString(ch));
}
if (kerningAvailable && (i + 1) < l) {
addKerning(pdf, (new Integer((int) ch)),
(new Integer((int) area.getFontState().mapChar(s.charAt(i + 1)))),
kerning, startText, endText);
}
}
pdf.append(endText);
currentStream.add(pdf.toString());
this.currentXPosition += area.getContentWidth();
}
}
/**
* Convert a char to a multibyte hex representation
*/
private String getUnicodeString(char c) {
StringBuffer buf = new StringBuffer(4);
byte[] uniBytes = null;
try {
char[] a = {c};
uniBytes = new String(a).getBytes("UnicodeBigUnmarked");
} catch (Exception e) {
// This should never fail
}
for (int i = 0; i < uniBytes.length; i++) {
int b = (uniBytes[i] < 0) ? (int)(256 + uniBytes[i]) :
(int) uniBytes[i];
String hexString = Integer.toHexString(b);
if (hexString.length() == 1)
buf = buf.append("0"+hexString);
else
buf = buf.append(hexString);
}
return buf.toString();
}
/** Checks to see if we have some text rendering commands open
* still and writes out the TJ command to the stream if we do
*/
private void closeText() {
if (textOpen) {
currentStream.add("] TJ\n");
textOpen = false;
prevWordX = 0;
prevWordY = 0;
}
}
private void addKerning(StringBuffer buf, Integer ch1, Integer ch2,
Hashtable kerning, String startText, String endText) {
Hashtable kernPair = (Hashtable) kerning.get(ch1);
if (kernPair != null) {
Integer width = (Integer) kernPair.get(ch2);
if (width != null) {
buf.append(endText).append(-
(width.intValue())).append(' ').append(startText);
}
}
}
/**
* render page into PDF
*
* @param page page to render
*/
public void renderPage(Page page) {
BodyAreaContainer body;
AreaContainer before, after, start, end;
currentStream = this.pdfDoc.makeStream();
body = page.getBody();
before = page.getBefore();
after = page.getAfter();
start = page.getStart();
end = page.getEnd();
this.currentFontName = "";
this.currentFontSize = 0;
currentStream.add("BT\n");
renderBodyAreaContainer(body);
if (before != null) {
renderAreaContainer(before);
}
if (after != null) {
renderAreaContainer(after);
}
if (start != null) {
renderAreaContainer(start);
}
if (end != null) {
renderAreaContainer(end);
}
closeText();
currentStream.add("ET\n");
currentPage = this.pdfDoc.makePage(this.pdfResources, currentStream,
page.getWidth() / 1000, page.getHeight() / 1000, page);
if (page.hasLinks()) {
currentAnnotList = this.pdfDoc.makeAnnotList();
currentPage.setAnnotList(currentAnnotList);
Enumeration e = page.getLinkSets().elements();
while (e.hasMoreElements()) {
LinkSet linkSet = (LinkSet) e.nextElement();
linkSet.align();
String dest = linkSet.getDest();
int linkType = linkSet.getLinkType();
Enumeration f = linkSet.getRects().elements();
while (f.hasMoreElements()) {
LinkedRectangle lrect =
(LinkedRectangle) f.nextElement();
currentAnnotList.addLink(
this.pdfDoc.makeLink(lrect.getRectangle(),
dest, linkType));
}
}
} else {
// just to be on the safe side
currentAnnotList = null;
}
// ensures that color is properly reset for blocks that carry over pages
this.currentFill = null;
}
/**
* defines a string containing dashArray and dashPhase for the rule style
*/
private String setRuleStylePattern (int style) {
String rs = "";
switch (style) {
case org.apache.fop.fo.properties.RuleStyle.SOLID:
rs = "[] 0 d ";
break;
case org.apache.fop.fo.properties.RuleStyle.DASHED:
rs = "[3 3] 0 d ";
break;
case org.apache.fop.fo.properties.RuleStyle.DOTTED:
rs = "[1 3] 0 d ";
break;
case org.apache.fop.fo.properties.RuleStyle.DOUBLE:
rs = "[] 0 d ";
break;
default:
rs = "[] 0 d ";
}
return rs;
}
protected void renderRootExtensions(AreaTree areaTree) {
Vector v = areaTree.getExtensions();
if (v != null) {
Enumeration e = v.elements();
while (e.hasMoreElements()) {
ExtensionObj ext = (ExtensionObj) e.nextElement();
if (ext instanceof Outline) {
renderOutline((Outline) ext);
}
}
}
}
private void renderOutline(Outline outline) {
if (rootOutline == null) {
rootOutline = this.pdfDoc.makeOutlineRoot();
}
PDFOutline pdfOutline = null;
Outline parent = outline.getParentOutline();
if (parent == null) {
pdfOutline = this.pdfDoc.makeOutline(rootOutline,
outline.getLabel().toString(),
outline.getInternalDestination());
} else {
PDFOutline pdfParentOutline =
(PDFOutline) parent.getRendererObject();
if (pdfParentOutline == null) {
MessageHandler.errorln("Error: pdfParentOutline is null");
} else {
pdfOutline = this.pdfDoc.makeOutline(pdfParentOutline,
outline.getLabel().toString(),
outline.getInternalDestination());
}
}
outline.setRendererObject(pdfOutline);
// handle sub outlines
Vector v = outline.getOutlines();
Enumeration e = v.elements();
while (e.hasMoreElements()) {
renderOutline((Outline) e.nextElement());
}
}
protected class MUserAgent implements UserAgent {
AffineTransform currentTransform = null;
/**
* Creates a new SVGUserAgent.
*/
protected MUserAgent(AffineTransform at) {
currentTransform = at;
}
/**
* Displays an error message.
*/
public void displayError(String message) {
System.err.println(message);
}
/**
* Displays an error resulting from the specified Exception.
*/
public void displayError(Exception ex) {
ex.printStackTrace(System.err);
}
/**
* Displays a message in the User Agent interface.
* The given message is typically displayed in a status bar.
*/
public void displayMessage(String message) {
System.out.println(message);
}
/**
* Returns a customized the pixel to mm factor.
*/
public float getPixelToMM() {
return 0.264583333333333333333f; // 72 dpi
}
/**
* Returns the language settings.
*/
public String getLanguages() {
return "en";//userLanguages;
}
/**
* Returns the user stylesheet uri.
* @return null if no user style sheet was specified.
*/
public String getUserStyleSheetURI() {
return null;//userStyleSheetURI;
}
/**
* Returns the class name of the XML parser.
*/
public String getXMLParserClassName() {
String parserClassName = System.getProperty("org.xml.sax.parser");
if (parserClassName == null) {
parserClassName = "org.apache.xerces.parsers.SAXParser";
}
return parserClassName;//application.getXMLParserClassName();
}
/**
* Opens a link in a new component.
* @param doc The current document.
* @param uri The document URI.
*/
public void openLink(SVGAElement elt) {
//application.openLink(uri);
}
public Point getClientAreaLocationOnScreen() {
return new Point(0, 0);
}
public void setSVGCursor(java.awt.Cursor cursor) {
}
public AffineTransform getTransform() {
return currentTransform;
}
public Dimension2D getViewportSize() {
return new Dimension(100, 100);
}
public EventDispatcher getEventDispatcher() {
return null;
}
public boolean supportExtension(String str) {
return false;
}
public boolean hasFeature(String str) {
return false;
}
public void registerExtension(BridgeExtension be) {
}
}
}
|
package org.apache.xerces.framework;
import java.io.InputStream;
import java.io.IOException;
import java.io.Reader;
import java.util.Locale;
import org.apache.xerces.readers.DefaultEntityHandler;
import org.apache.xerces.readers.XMLDeclRecognizer;
import org.apache.xerces.readers.XMLEntityHandler;
import org.apache.xerces.readers.XMLEntityReaderFactory;
import org.apache.xerces.utils.ChunkyCharArray;
import org.apache.xerces.utils.StringPool;
import org.apache.xerces.utils.XMLMessageProvider;
import org.apache.xerces.utils.XMLMessages;
import org.apache.xerces.utils.ImplementationMessages;
import org.apache.xerces.validators.common.GrammarResolver;
import org.apache.xerces.validators.common.GrammarResolverImpl;
import org.apache.xerces.validators.common.XMLValidator;
import org.apache.xerces.validators.datatype.DatatypeMessageProvider;
import org.apache.xerces.validators.datatype.DatatypeValidatorFactoryImpl;
import org.apache.xerces.validators.schema.SchemaMessageProvider;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;
/**
* This is the base class of all standard parsers.
*
* @version $Id$
*/
public abstract class XMLParser
implements XMLErrorReporter, XMLDocumentHandler.DTDHandler {
// Constants
// protected
protected static final String SAX2_FEATURES_PREFIX = "http://xml.org/sax/features/";
protected static final String SAX2_PROPERTIES_PREFIX = "http://xml.org/sax/properties/";
protected static final String XERCES_FEATURES_PREFIX = "http://apache.org/xml/features/";
protected static final String XERCES_PROPERTIES_PREFIX = "http://apache.org/xml/properties/";
// private
/** Features recognized by this parser. */
private static final String RECOGNIZED_FEATURES[] = {
// SAX2 core
"http://xml.org/sax/features/validation",
"http://xml.org/sax/features/external-general-entities",
"http://xml.org/sax/features/external-parameter-entities",
"http://xml.org/sax/features/namespaces",
// Xerces
"http://apache.org/xml/features/validation/schema",
"http://apache.org/xml/features/validation/dynamic",
"http://apache.org/xml/features/validation/default-attribute-values",
"http://apache.org/xml/features/validation/validate-content-models",
"http://apache.org/xml/features/validation/validate-datatypes",
"http://apache.org/xml/features/validation/warn-on-duplicate-attdef",
"http://apache.org/xml/features/validation/warn-on-undeclared-elemdef",
"http://apache.org/xml/features/allow-java-encodings",
"http://apache.org/xml/features/continue-after-fatal-error",
"http://apache.org/xml/features/nonvalidating/load-dtd-grammar",
"http://apache.org/xml/features/nonvalidating/load-external-dtd"
};
/** Properties recognized by this parser. */
private static final String RECOGNIZED_PROPERTIES[] = {
// SAX2 core
"http://xml.org/sax/properties/xml-string",
// Xerces
};
// debugging
/** Set to true and recompile to print exception stack trace. */
private static final boolean PRINT_EXCEPTION_STACK_TRACE = false;
// Data
protected GrammarResolver fGrammarResolver = null;
// state
protected boolean fParseInProgress = false;
private boolean fNeedReset = false;
// features
/** Continue after fatal error. */
private boolean fContinueAfterFatalError = false;
// properties
/** Error handler. */
private ErrorHandler fErrorHandler = null;
// other
private Locale fLocale = null;
// error information
private static XMLMessageProvider fgXMLMessages = new XMLMessages();
private static XMLMessageProvider fgImplementationMessages = new ImplementationMessages();
private static XMLMessageProvider fgSchemaMessages = new SchemaMessageProvider();
private static XMLMessageProvider fgDatatypeMessages= new DatatypeMessageProvider();
protected StringPool fStringPool = null;
protected XMLErrorReporter fErrorReporter = null;
protected DefaultEntityHandler fEntityHandler = null;
protected XMLDocumentScanner fScanner = null;
protected XMLValidator fValidator = null;
// Constructors
/**
* Constructor
*/
protected XMLParser() {
this(new StringPool());
}
protected XMLParser(StringPool stringPool) {
fStringPool = stringPool;
fErrorReporter = this;
fEntityHandler = new DefaultEntityHandler(fStringPool, fErrorReporter);
fScanner = new XMLDocumentScanner(fStringPool, fErrorReporter, fEntityHandler, new ChunkyCharArray(fStringPool));
fValidator = new XMLValidator(fStringPool, fErrorReporter, fEntityHandler, fScanner);
fGrammarResolver = new GrammarResolverImpl();
fScanner.setGrammarResolver(fGrammarResolver);
fValidator.setGrammarResolver(fGrammarResolver);
try {
//JR-defect 48 fix - turn on Namespaces
setNamespaces(true);
}
catch (Exception e) {
// ignore
}
}
/**
* Set char data processing preference and handlers.
*/
protected void initHandlers(boolean sendCharDataAsCharArray,
XMLDocumentHandler docHandler,
XMLDocumentHandler.DTDHandler dtdHandler)
{
fValidator.initHandlers(sendCharDataAsCharArray, docHandler, dtdHandler);
fScanner.setDTDHandler(this);
}
// Public methods
// features and properties
/**
* Returns a list of features that this parser recognizes.
* This method will never return null; if no features are
* recognized, this method will return a zero length array.
*
* @see #isFeatureRecognized
* @see #setFeature
* @see #getFeature
*/
public String[] getFeaturesRecognized() {
return RECOGNIZED_FEATURES;
}
/**
* Returns true if the specified feature is recognized.
*
* @see #getFeaturesRecognized
* @see #setFeature
* @see #getFeature
*/
public boolean isFeatureRecognized(String featureId) {
String[] recognizedFeatures = getFeaturesRecognized();
for (int i = 0; i < recognizedFeatures.length; i++) {
if (featureId.equals(recognizedFeatures[i]))
return true;
}
return false;
}
/**
* Returns a list of properties that this parser recognizes.
* This method will never return null; if no properties are
* recognized, this method will return a zero length array.
*
* @see #isPropertyRecognized
* @see #setProperty
* @see #getProperty
*/
public String[] getPropertiesRecognized() {
return RECOGNIZED_PROPERTIES;
}
/**
* Returns true if the specified property is recognized.
*
* @see #getPropertiesRecognized
* @see #setProperty
* @see #getProperty
*/
public boolean isPropertyRecognized(String propertyId) {
String[] recognizedProperties = getPropertiesRecognized();
for (int i = 0; i < recognizedProperties.length; i++) {
if (propertyId.equals(recognizedProperties[i]))
return true;
}
return false;
}
// initialization
/**
* Setup for application-driven parsing.
*
* @param source the input source to be parsed.
* @see #parseSome
*/
public boolean parseSomeSetup(InputSource source) throws Exception {
if (fNeedReset)
resetOrCopy();
fParseInProgress = true;
fNeedReset = true;
return fEntityHandler.startReadingFromDocument(source);
}
/**
* Application-driven parsing.
*
* @see #parseSomeSetup
*/
public boolean parseSome() throws Exception {
if (!fScanner.parseSome(false)) {
fParseInProgress = false;
return false;
}
return true;
}
// resetting
/** Reset parser instance so that it can be reused. */
public void reset() throws Exception {
fGrammarResolver.clearGrammarResolver();
fStringPool.reset();
fEntityHandler.reset(fStringPool);
fScanner.reset(fStringPool, new ChunkyCharArray(fStringPool));
fValidator.reset(fStringPool);
fNeedReset = false;
}
// properties (the normal kind)
/**
* return the locator being used by the parser
*
* @return the parser's active locator
*/
public final Locator getLocator() {
return fEntityHandler;
}
/**
* Set the reader factory.
*/
public void setReaderFactory(XMLEntityReaderFactory readerFactory) {
fEntityHandler.setReaderFactory(readerFactory);
}
/**
* Adds a recognizer.
*
* @param recognizer The XML recognizer to add.
*/
public void addRecognizer(XMLDeclRecognizer recognizer) {
fEntityHandler.addRecognizer(recognizer);
}
// Protected methods
// SAX2 core features
protected void setValidation(boolean validate)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (fParseInProgress) {
throw new SAXNotSupportedException("PAR004 Cannot setFeature(http://xml.org/sax/features/validation): parse is in progress.\n"+
"http://xml.org/sax/features/validation");
}
try {
// REVISIT: [Q] Should the scanner tell the validator that
// validation is on? -Ac
fScanner.setValidationEnabled(validate);
fValidator.setValidationEnabled(validate);
}
catch (Exception ex) {
throw new SAXNotSupportedException(ex.getMessage());
}
}
/**
* Returns true if validation is turned on.
*
* @see #setValidation
*/
protected boolean getValidation()
throws SAXNotRecognizedException, SAXNotSupportedException {
return fValidator.getValidationEnabled();
}
protected void setExternalGeneralEntities(boolean expand)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (fParseInProgress) {
throw new SAXNotSupportedException("PAR004 Cannot setFeature(http://xml.org/sax/features/external-general-entities): parse is in progress.\n"+
"http://xml.org/sax/features/external-general-entities");
}
if (!expand) {
throw new SAXNotSupportedException("http://xml.org/sax/features/external-general-entities");
}
}
/**
* <b>Note: This feature is always true.</b>
* <p>
* Returns true if external general entities are expanded.
*
* @see #setExternalGeneralEntities
*/
protected boolean getExternalGeneralEntities()
throws SAXNotRecognizedException, SAXNotSupportedException {
return true;
}
protected void setExternalParameterEntities(boolean expand)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (fParseInProgress) {
throw new SAXNotSupportedException("PAR004 Cannot setFeature(http://xml.org/sax/features/external-general-entities): parse is in progress.\n"+
"http://xml.org/sax/features/external-general-entities");
}
if (!expand) {
throw new SAXNotSupportedException("http://xml.org/sax/features/external-parameter-entities");
}
}
/**
* <b>Note: This feature is always true.</b>
* <p>
* Returns true if external parameter entities are expanded.
*
* @see #setExternalParameterEntities
*/
protected boolean getExternalParameterEntities()
throws SAXNotRecognizedException, SAXNotSupportedException {
return true;
}
protected void setNamespaces(boolean process)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (fParseInProgress) {
throw new SAXNotSupportedException("PAR004 Cannot setFeature(http://xml.org/sax/features/namespaces): parse is in progress.\n"+
"http://xml.org/sax/features/namespaces");
}
fScanner.setNamespacesEnabled(process);
// REVISIT: [Q] Should the scanner tell the validator that namespace
// processing is on? -Ac
fValidator.setNamespacesEnabled(process);
}
/**
* Returns true if the parser preprocesses namespaces.
*
* @see #setNamespaces
*/
protected boolean getNamespaces()
throws SAXNotRecognizedException, SAXNotSupportedException {
return fValidator.getNamespacesEnabled();
}
// Xerces features
protected void setValidationSchema(boolean schema)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (fParseInProgress) {
// REVISIT: Localize message
throw new SAXNotSupportedException("http://apache.org/xml/features/validation/schema: parse is in progress");
}
fValidator.setSchemaValidationEnabled(schema);
}
/**
* Returns true if Schema support is turned on.
*
* @see #setValidationSchema
*/
protected boolean getValidationSchema()
throws SAXNotRecognizedException, SAXNotSupportedException {
return fValidator.getSchemaValidationEnabled();
}
protected void setValidationDynamic(boolean dynamic)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (fParseInProgress) {
// REVISIT: Localize message
throw new SAXNotSupportedException("http://apache.org/xml/features/validation/dynamic: parse is in progress");
}
try {
fValidator.setDynamicValidationEnabled(dynamic);
}
catch (Exception ex) {
throw new SAXNotSupportedException(ex.getMessage());
}
}
/**
* Returns true if validation is based on whether a document
* contains a grammar.
*
* @see #setValidationDynamic
*/
protected boolean getValidationDynamic()
throws SAXNotRecognizedException, SAXNotSupportedException {
return fValidator.getDynamicValidationEnabled();
}
protected void setNormalizeAttributeValues(boolean normalize) {
fValidator.setNormalizeAttributeValues(normalize);
}
protected void setLoadDTDGrammar(boolean loadDTDGrammar)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (fParseInProgress) {
// REVISIT: Localize message
throw new SAXNotSupportedException("http://apache.org/xml/features/nonvalidating/load-dtd-grammar: parse is in progress");
}
try {
fValidator.setLoadDTDGrammar(loadDTDGrammar);
}
catch (Exception ex) {
throw new SAXNotSupportedException(ex.getMessage());
}
}
/**
* Returns true if load DTD grammar is turned on in the XMLValiator.
*
* @see #setLoadDTDGrammar
*/
protected boolean getLoadDTDGrammar()
throws SAXNotRecognizedException, SAXNotSupportedException {
return fValidator.getLoadDTDGrammar();
}
protected void setLoadExternalDTD(boolean loadExternalDTD)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (fParseInProgress) {
// REVISIT: Localize message
throw new SAXNotSupportedException("http://apache.org/xml/features/nonvalidating/load-external-dtd: parse is in progress");
}
try {
fScanner.setLoadExternalDTD(loadExternalDTD);
}
catch (Exception ex) {
throw new SAXNotSupportedException(ex.getMessage());
}
}
/**
* Returns true if loading of the external DTD is on.
*
* @see #setLoadExternalDTD
*/
protected boolean getLoadExternalDTD()
throws SAXNotRecognizedException, SAXNotSupportedException {
return fScanner.getLoadExternalDTD();
}
protected void setValidationWarnOnDuplicateAttdef(boolean warn)
throws SAXNotRecognizedException, SAXNotSupportedException {
fValidator.setWarningOnDuplicateAttDef(warn);
}
/**
* Returns true if an error is emitted when an attribute is redefined
* in the grammar.
*
* @see #setValidationWarnOnDuplicateAttdef
*/
protected boolean getValidationWarnOnDuplicateAttdef()
throws SAXNotRecognizedException, SAXNotSupportedException {
return fValidator.getWarningOnDuplicateAttDef();
}
protected void setValidationWarnOnUndeclaredElemdef(boolean warn)
throws SAXNotRecognizedException, SAXNotSupportedException {
fValidator.setWarningOnUndeclaredElements(warn);
}
/**
* Returns true if the parser emits an error when an undeclared
* element is referenced in the grammar.
*
* @see #setValidationWarnOnUndeclaredElemdef
*/
protected boolean getValidationWarnOnUndeclaredElemdef()
throws SAXNotRecognizedException, SAXNotSupportedException {
return fValidator.getWarningOnUndeclaredElements();
}
protected void setAllowJavaEncodings(boolean allow)
throws SAXNotRecognizedException, SAXNotSupportedException {
fEntityHandler.setAllowJavaEncodings(allow);
}
/**
* Returns true if Java encoding names are allowed in the XML document.
*
* @see #setAllowJavaEncodings
*/
protected boolean getAllowJavaEncodings()
throws SAXNotRecognizedException, SAXNotSupportedException {
return fEntityHandler.getAllowJavaEncodings();
}
protected void setContinueAfterFatalError(boolean continueAfterFatalError)
throws SAXNotRecognizedException, SAXNotSupportedException {
fContinueAfterFatalError = continueAfterFatalError;
}
/**
* Returns true if the parser continues after a fatal error.
*
* @see #setContinueAfterFatalError
*/
protected boolean getContinueAfterFatalError()
throws SAXNotRecognizedException, SAXNotSupportedException {
return fContinueAfterFatalError;
}
// SAX2 core properties
/**
* Returns the namespace separator.
*
* @see #setNamespaceSep
*/
protected String getXMLString()
throws SAXNotRecognizedException, SAXNotSupportedException {
throw new SAXNotSupportedException("http://xml.org/sax/properties/xml-string");
}
// resetting
/**
* Reset or copy parser
* Allows parser instance reuse
*/
protected void resetOrCopy() throws Exception {
fStringPool = new StringPool();
fEntityHandler.reset(fStringPool);
fScanner.reset(fStringPool, new ChunkyCharArray(fStringPool));
fValidator.resetOrCopy(fStringPool);
fNeedReset = false;
fGrammarResolver = new GrammarResolverImpl();
fGrammarResolver.clearGrammarResolver();
fScanner.setGrammarResolver(fGrammarResolver);
fValidator.setGrammarResolver(fGrammarResolver);
}
// Parser/XMLReader methods
// NOTE: This class does *not* implement the org.xml.sax.Parser
// interface but it does share some common methods. -Ac
// handlers
/**
* Sets the resolver used to resolve external entities. The EntityResolver
* interface supports resolution of public and system identifiers.
*
* @param resolver The new entity resolver. Passing a null value will
* uninstall the currently installed resolver.
*/
public void setEntityResolver(EntityResolver resolver) {
fEntityHandler.setEntityResolver(resolver);
}
/**
* Return the current entity resolver.
*
* @return The current entity resolver, or null if none
* has been registered.
* @see #setEntityResolver
*/
public EntityResolver getEntityResolver() {
return fEntityHandler.getEntityResolver();
}
/**
* Sets the error handler.
*
* @param handler The new error handler.
*/
public void setErrorHandler(ErrorHandler handler) {
fErrorHandler = handler;
}
/**
* Return the current error handler.
*
* @return The current error handler, or null if none
* has been registered.
* @see #setErrorHandler
*/
public ErrorHandler getErrorHandler() {
return fErrorHandler;
}
// parsing
/**
* Parses the specified input source.
*
* @param source The input source.
*
* @exception org.xml.sax.SAXException Throws exception on SAX error.
* @exception java.io.IOException Throws exception on i/o error.
*/
public void parse(InputSource source)
throws SAXException, IOException {
if (fParseInProgress) {
throw new org.xml.sax.SAXException("FWK005 parse may not be called while parsing."); // REVISIT - need to add new error message
}
try {
if (parseSomeSetup(source)) {
fScanner.parseSome(true);
}
} catch (org.xml.sax.SAXException ex) {
if (PRINT_EXCEPTION_STACK_TRACE)
ex.printStackTrace();
throw ex;
} catch (IOException ex) {
if (PRINT_EXCEPTION_STACK_TRACE)
ex.printStackTrace();
throw ex;
} catch (Exception ex) {
if (PRINT_EXCEPTION_STACK_TRACE)
ex.printStackTrace();
throw new org.xml.sax.SAXException(ex);
}
finally {
fParseInProgress = false;
}
} // parse(InputSource)
/**
* Parses the input source specified by the given system identifier.
* <p>
* This method is <em>almost</em> equivalent to the following:
* <pre>
* parse(new InputSource(systemId));
* </pre>
* The only difference is that this method will attempt to close
* the stream that was opened.
*
* @param source The input source.
*
* @exception org.xml.sax.SAXException Throws exception on SAX error.
* @exception java.io.IOException Throws exception on i/o error.
*/
public void parse(String systemId)
throws SAXException, IOException {
InputSource source = new InputSource(systemId);
try {
parse(source);
}
finally {
// NOTE: Changed code to attempt to close the stream
// even after parsing failure. -Ac
try {
Reader reader = source.getCharacterStream();
if (reader != null) {
reader.close();
}
else {
InputStream is = source.getByteStream();
if (is != null) {
is.close();
}
}
}
catch (IOException e) {
// ignore
}
}
} // parse(String)
// locale
/**
* Set the locale to use for messages.
*
* @param locale The locale object to use for localization of messages.
*
* @exception SAXException An exception thrown if the parser does not
* support the specified locale.
*
* @see org.xml.sax.Parser
*/
public void setLocale(Locale locale) throws SAXException {
if (fParseInProgress) {
throw new org.xml.sax.SAXException("FWK006 setLocale may not be called while parsing"); // REVISIT - need to add new error message
}
fLocale = locale;
fgXMLMessages.setLocale(locale);
fgImplementationMessages.setLocale(locale);
} // setLocale(Locale)
// XMLErrorReporter methods
/**
* Report an error.
*
* @param locator Location of error.
* @param errorDomain The error domain.
* @param majorCode The major code of the error.
* @param minorCode The minor code of the error.
* @param args Arguments for replacement text.
* @param errorType The type of the error.
*
* @exception Exception Thrown on error.
*
* @see XMLErrorReporter#ERRORTYPE_WARNING
* @see XMLErrorReporter#ERRORTYPE_FATAL_ERROR
*/
public void reportError(Locator locator, String errorDomain,
int majorCode, int minorCode, Object args[],
int errorType) throws Exception {
// create the appropriate message
SAXParseException spe;
if (errorDomain.equals(XMLMessages.XML_DOMAIN)) {
spe = new SAXParseException(fgXMLMessages.createMessage(fLocale, majorCode, minorCode, args), locator);
}
else if (errorDomain.equals(XMLMessages.XMLNS_DOMAIN)) {
spe = new SAXParseException(fgXMLMessages.createMessage(fLocale, majorCode, minorCode, args), locator);
}
else if (errorDomain.equals(ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN)) {
spe = new SAXParseException(fgImplementationMessages.createMessage(fLocale, majorCode, minorCode, args), locator);
} else if (errorDomain.equals(SchemaMessageProvider.SCHEMA_DOMAIN)) {
spe = new SAXParseException(fgSchemaMessages.createMessage(fLocale, majorCode, minorCode, args), locator);
} else if (errorDomain.equals(DatatypeMessageProvider.DATATYPE_DOMAIN)) {
spe = new SAXParseException(fgDatatypeMessages.createMessage(fLocale, majorCode, minorCode, args), locator);
} else {
throw new RuntimeException("FWK007 Unknown error domain \"" + errorDomain + "\"."+"\n"+errorDomain);
}
// default error handling
if (fErrorHandler == null) {
if (errorType == XMLErrorReporter.ERRORTYPE_FATAL_ERROR &&
!fContinueAfterFatalError) {
throw spe;
}
return;
}
// make appropriate callback
if (errorType == XMLErrorReporter.ERRORTYPE_WARNING) {
fErrorHandler.warning(spe);
}
else if (errorType == XMLErrorReporter.ERRORTYPE_FATAL_ERROR) {
fErrorHandler.fatalError(spe);
if (!fContinueAfterFatalError) {
Object[] fatalArgs = { spe.getMessage() };
throw new SAXException(fgImplementationMessages.createMessage(fLocale, ImplementationMessages.FATAL_ERROR, 0, fatalArgs));
}
}
else {
fErrorHandler.error(spe);
}
} // reportError(Locator,String,int,int,Object[],int)
// XMLReader methods
/**
* Set the state of a feature.
*
* Set the state of any feature in a SAX2 parser. The parser
* might not recognize the feature, and if it does recognize
* it, it might not be able to fulfill the request.
*
* @param featureId The unique identifier (URI) of the feature.
* @param state The requested state of the feature (true or false).
*
* @exception org.xml.sax.SAXNotRecognizedException If the
* requested feature is not known.
* @exception org.xml.sax.SAXNotSupportedException If the
* requested feature is known, but the requested
* state is not supported.
* @exception org.xml.sax.SAXException If there is any other
* problem fulfilling the request.
*/
public void setFeature(String featureId, boolean state)
throws SAXNotRecognizedException, SAXNotSupportedException {
// SAX2 Features
if (featureId.startsWith(SAX2_FEATURES_PREFIX)) {
String feature = featureId.substring(SAX2_FEATURES_PREFIX.length());
// Validate (true) or don't validate (false).
if (feature.equals("validation")) {
setValidation(state);
return;
}
// Expand external general entities (true) or don't expand (false).
if (feature.equals("external-general-entities")) {
setExternalGeneralEntities(state);
return;
}
// Expand external parameter entities (true) or don't expand (false).
if (feature.equals("external-parameter-entities")) {
setExternalParameterEntities(state);
return;
}
// Preprocess namespaces (true) or don't preprocess (false). See also
if (feature.equals("namespaces")) {
setNamespaces(state);
return;
}
// Not recognized
}
// Xerces Features
else if (featureId.startsWith(XERCES_FEATURES_PREFIX)) {
String feature = featureId.substring(XERCES_FEATURES_PREFIX.length());
// Lets the user turn Schema validation support on/off.
if (feature.equals("validation/schema")) {
setValidationSchema(state);
return;
}
// Allows the parser to validate a document only when it
// contains a grammar. Validation is turned on/off based
// on each document instance, automatically.
if (feature.equals("validation/dynamic")) {
setValidationDynamic(state);
return;
}
if (feature.equals("validation/default-attribute-values")) {
// REVISIT
throw new SAXNotSupportedException(featureId);
}
if (feature.equals("validation/normalize-attribute-values")) {
setNormalizeAttributeValues(state);
}
if (feature.equals("validation/validate-content-models")) {
// REVISIT
throw new SAXNotSupportedException(featureId);
}
if (feature.equals("nonvalidating/load-dtd-grammar")) {
setLoadDTDGrammar(state);
return;
}
if (feature.equals("nonvalidating/load-external-dtd")) {
setLoadExternalDTD(state);
return;
}
if (feature.equals("validation/validate-datatypes")) {
// REVISIT
throw new SAXNotSupportedException(featureId);
}
// Emits an error when an attribute is redefined.
if (feature.equals("validation/warn-on-duplicate-attdef")) {
setValidationWarnOnDuplicateAttdef(state);
return;
}
// Emits an error when an element's content model
// references an element, by name, that is not declared
// in the grammar.
if (feature.equals("validation/warn-on-undeclared-elemdef")) {
setValidationWarnOnUndeclaredElemdef(state);
return;
}
// Allows the use of Java encoding names in the XML
// and TextDecl lines.
if (feature.equals("allow-java-encodings")) {
setAllowJavaEncodings(state);
return;
}
// Allows the parser to continue after a fatal error.
// Normally, a fatal error would stop the parse.
if (feature.equals("continue-after-fatal-error")) {
setContinueAfterFatalError(state);
return;
}
// Not recognized
}
// Not recognized
throw new SAXNotRecognizedException(featureId);
} // setFeature(String,boolean)
/**
* Query the state of a feature.
*
* Query the current state of any feature in a SAX2 parser. The
* parser might not recognize the feature.
*
* @param featureId The unique identifier (URI) of the feature
* being set.
* @return The current state of the feature.
* @exception org.xml.sax.SAXNotRecognizedException If the
* requested feature is not known.
* @exception org.xml.sax.SAXException If there is any other
* problem fulfilling the request.
*/
public boolean getFeature(String featureId)
throws SAXNotRecognizedException, SAXNotSupportedException {
// SAX2 Features
if (featureId.startsWith(SAX2_FEATURES_PREFIX)) {
String feature = featureId.substring(SAX2_FEATURES_PREFIX.length());
// Validate (true) or don't validate (false).
if (feature.equals("validation")) {
return getValidation();
}
// Expand external general entities (true) or don't expand (false).
if (feature.equals("external-general-entities")) {
return getExternalGeneralEntities();
}
// Expand external parameter entities (true) or don't expand (false).
if (feature.equals("external-parameter-entities")) {
return getExternalParameterEntities();
}
// Preprocess namespaces (true) or don't preprocess (false). See also
if (feature.equals("namespaces")) {
return getNamespaces();
}
// Not recognized
}
// Xerces Features
else if (featureId.startsWith(XERCES_FEATURES_PREFIX)) {
String feature = featureId.substring(XERCES_FEATURES_PREFIX.length());
// Lets the user turn Schema validation support on/off.
if (feature.equals("validation/schema")) {
return getValidationSchema();
}
// Allows the parser to validate a document only when it
// contains a grammar. Validation is turned on/off based
// on each document instance, automatically.
if (feature.equals("validation/dynamic")) {
return getValidationDynamic();
}
if (feature.equals("validation/default-attribute-values")) {
// REVISIT
throw new SAXNotRecognizedException(featureId);
}
if (feature.equals("validation/validate-content-models")) {
// REVISIT
throw new SAXNotRecognizedException(featureId);
}
if (feature.equals("nonvalidating/load-dtd-grammar")) {
return getLoadDTDGrammar();
}
if (feature.equals("nonvalidating/load-external-dtd")) {
return getLoadExternalDTD();
}
if (feature.equals("validation/validate-datatypes")) {
// REVISIT
throw new SAXNotRecognizedException(featureId);
}
// Emits an error when an attribute is redefined.
if (feature.equals("validation/warn-on-duplicate-attdef")) {
return getValidationWarnOnDuplicateAttdef();
}
// Emits an error when an element's content model
// references an element, by name, that is not declared
// in the grammar.
if (feature.equals("validation/warn-on-undeclared-elemdef")) {
return getValidationWarnOnUndeclaredElemdef();
}
// Allows the use of Java encoding names in the XML
// and TextDecl lines.
if (feature.equals("allow-java-encodings")) {
return getAllowJavaEncodings();
}
// Allows the parser to continue after a fatal error.
// Normally, a fatal error would stop the parse.
if (feature.equals("continue-after-fatal-error")) {
return getContinueAfterFatalError();
}
// Not recognized
}
// Not recognized
throw new SAXNotRecognizedException(featureId);
} // getFeature(String):boolean
/**
* Set the value of a property.
*
* Set the value of any property in a SAX2 parser. The parser
* might not recognize the property, and if it does recognize
* it, it might not support the requested value.
*
* @param propertyId The unique identifier (URI) of the property
* being set.
* @param Object The value to which the property is being set.
* @exception org.xml.sax.SAXNotRecognizedException If the
* requested property is not known.
* @exception org.xml.sax.SAXNotSupportedException If the
* requested property is known, but the requested
* value is not supported.
* @exception org.xml.sax.SAXException If there is any other
* problem fulfilling the request.
*/
public void setProperty(String propertyId, Object value)
throws SAXNotRecognizedException, SAXNotSupportedException {
// SAX2 Properties
if (propertyId.startsWith(SAX2_PROPERTIES_PREFIX)) {
String property = propertyId.substring(SAX2_PROPERTIES_PREFIX.length());
// Value type: String
// Access: read/write, pre-parse only
// Set the separator to be used between the URI part of a name and the
// local part of a name when namespace processing is being performed
// default, the separator is a single space. This property may not be
// set while a parse is in progress (throws a SAXNotSupportedException).
/*
else if (propertyId.startsWith(XERCES_PROPERTIES_PREFIX)) {
//
// No properties defined yet that are common to all parsers.
//
}
*/
// Not recognized
throw new SAXNotRecognizedException(propertyId);
} // setProperty(String,Object)
/**
* Query the value of a property.
*
* Return the current value of a property in a SAX2 parser.
* The parser might not recognize the property.
*
* @param propertyId The unique identifier (URI) of the property
* being set.
* @return The current value of the property.
* @exception org.xml.sax.SAXNotRecognizedException If the
* requested property is not known.
* @exception org.xml.sax.SAXException If there is any other
* problem fulfilling the request.
* @see org.xml.sax.XMLReader#getProperty
*/
public Object getProperty(String propertyId)
throws SAXNotRecognizedException, SAXNotSupportedException {
// SAX2 Properties
if (propertyId.startsWith(SAX2_PROPERTIES_PREFIX)) {
String property = propertyId.substring(SAX2_PROPERTIES_PREFIX.length());
// Value type: String
// Access: read/write, pre-parse only
// Set the separator to be used between the URI part of a name and the
// local part of a name when namespace processing is being performed
// default, the separator is a single space. This property may not be
// set while a parse is in progress (throws a SAXNotSupportedException).
/*
else if (propertyId.startsWith(XERCES_PROPERTIES_PREFIX)) {
//
// No properties defined yet that are common to all parsers.
//
}
*/
// Not recognized
throw new SAXNotRecognizedException(propertyId);
} // getProperty(String):Object
}
|
package org.bouncycastle.bcpg;
import java.io.*;
/**
* reader for PGP objects
*/
public class BCPGInputStream
extends InputStream implements PacketTags
{
InputStream in;
boolean next = false;
int nextB;
public BCPGInputStream(
InputStream in)
{
this.in = in;
}
public int available()
throws IOException
{
return in.available();
}
public int read()
throws IOException
{
if (next)
{
next = false;
return nextB;
}
else
{
return in.read();
}
}
public int read(
byte[] buf,
int off,
int len)
throws IOException
{
// make sure we pick up nextB if set.
if (len > 0)
{
int b = this.read();
if (b < 0)
{
return -1;
}
buf[off] = (byte)b;
off++;
len
}
if (len != 0)
{
return in.read(buf, off, len) + 1;
}
return 1;
}
public void readFully(
byte[] buf,
int off,
int len)
throws IOException
{
// make sure we pick up nextB if set.
if (len > 0)
{
int b = this.read();
if (b < 0)
{
throw new EOFException();
}
buf[off] = (byte)b;
off++;
len
}
while (len > 0)
{
int l = in.read(buf, off, len);
if (l < 0)
{
throw new EOFException();
}
off += l;
len -= l;
}
}
public void readFully(
byte[] buf)
throws IOException
{
readFully(buf, 0, buf.length);
}
/**
* returns the nest packet tag in the stream.
*
* @return the tag number.
*
* @throws IOException
*/
public int nextPacketTag()
throws IOException
{
if (!next)
{
try
{
nextB = in.read();
}
catch (EOFException e)
{
nextB = -1;
}
}
next = true;
if (nextB >= 0)
{
if ((nextB & 0x40) != 0) // new
{
return (nextB & 0x3f);
}
else // old
{
return ((nextB & 0x3f) >> 2);
}
}
return nextB;
}
public Packet readPacket()
throws IOException
{
int hdr = this.read();
if (hdr < 0)
{
return null;
}
if ((hdr & 0x80) == 0)
{
throw new IOException("invalid header encountered");
}
boolean newPacket = (hdr & 0x40) != 0;
int tag = 0;
int bodyLen = 0;
boolean partial = false;
if (newPacket)
{
tag = hdr & 0x3f;
int l = this.read();
if (l < 192)
{
bodyLen = l;
}
else if (l <= 223)
{
int b = in.read();
bodyLen = ((l - 192) << 8) + (b) + 192;
}
else if (l == 255)
{
bodyLen = (in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read();
}
else
{
partial = true;
bodyLen = 1 << (l & 0x1f);
}
}
else
{
int lengthType = hdr & 0x3;
tag = (hdr & 0x3f) >> 2;
switch (lengthType)
{
case 0:
bodyLen = this.read();
break;
case 1:
bodyLen = (this.read() << 8) | this.read();
break;
case 2:
bodyLen = (this.read() << 24) | (this.read() << 16) | (this.read() << 8) | this.read();
break;
case 3:
partial = true;
break;
default:
throw new IOException("unknown length type encountered");
}
}
BCPGInputStream objStream;
if (bodyLen == 0 && partial)
{
objStream = this;
}
else
{
objStream = new BCPGInputStream(new PartialInputStream(this, partial, bodyLen));
}
switch (tag)
{
case RESERVED:
return new InputStreamPacket(objStream);
case PUBLIC_KEY_ENC_SESSION:
return new PublicKeyEncSessionPacket(objStream);
case SIGNATURE:
return new SignaturePacket(objStream);
case SYMMETRIC_KEY_ENC_SESSION:
return new SymmetricKeyEncSessionPacket(objStream);
case ONE_PASS_SIGNATURE:
return new OnePassSignaturePacket(objStream);
case SECRET_KEY:
return new SecretKeyPacket(objStream);
case PUBLIC_KEY:
return new PublicKeyPacket(objStream);
case SECRET_SUBKEY:
return new SecretSubkeyPacket(objStream);
case COMPRESSED_DATA:
return new CompressedDataPacket(objStream);
case SYMMETRIC_KEY_ENC:
return new SymmetricEncDataPacket(objStream);
case MARKER:
return new MarkerPacket(objStream);
case LITERAL_DATA:
return new LiteralDataPacket(objStream);
case TRUST:
return new TrustPacket(objStream);
case USER_ID:
return new UserIDPacket(objStream);
case USER_ATTRIBUTE:
return new UserAttributePacket(objStream);
case PUBLIC_SUBKEY:
return new PublicSubkeyPacket(objStream);
case SYM_ENC_INTEGRITY_PRO:
return new SymmetricEncIntegrityPacket(objStream);
case MOD_DETECTION_CODE:
return new ModDetectionCodePacket(objStream);
case EXPERIMENTAL_1:
case EXPERIMENTAL_2:
case EXPERIMENTAL_3:
case EXPERIMENTAL_4:
return new ExperimentalPacket(tag, objStream);
default:
throw new IOException("unknown packet type encountered: " + tag);
}
}
public void close()
throws IOException
{
in.close();
}
/**
* a stream that overlays our input stream, allowing the user to only read a segment of it.
*/
private static class PartialInputStream
extends InputStream
{
private BCPGInputStream in;
private boolean partial;
private int dataLength;
PartialInputStream(
BCPGInputStream in,
boolean partial,
int dataLength)
{
this.in = in;
this.partial = partial;
this.dataLength = dataLength;
}
public int available()
throws IOException
{
int avail = in.available();
if (avail <= dataLength)
{
return avail;
}
else
{
if (partial && dataLength == 0)
{
return 1;
}
return dataLength;
}
}
private int loadDataLength()
throws IOException
{
int l = in.read();
if (l < 0)
{
return -1;
}
partial = false;
if (l < 192)
{
dataLength = l;
}
else if (l <= 223)
{
dataLength = ((l - 192) << 8) + (in.read()) + 192;
}
else if (l == 255)
{
dataLength = (in.read() << 24) | (in.read() << 16) | (in.read() << 8) | in.read();
}
else
{
partial = true;
dataLength = 1 << (l & 0x1f);
}
return dataLength;
}
public int read(byte[] buf, int offset, int len)
throws IOException
{
if (dataLength > 0)
{
int readLen = (dataLength > len) ? len : dataLength;
readLen = in.read(buf, offset, readLen);
dataLength -= readLen;
return readLen;
}
else if (partial)
{
if (loadDataLength() < 0)
{
return -1;
}
return this.read(buf, offset, len);
}
return -1;
}
public int read()
throws IOException
{
if (dataLength > 0)
{
dataLength
return in.read();
}
else if (partial)
{
if (loadDataLength() < 0)
{
return -1;
}
return this.read();
}
return -1;
}
}
}
|
package org.bouncycastle.math.ec;
import java.math.BigInteger;
public class ECAlgorithms
{
public static ECPoint sumOfTwoMultiplies(ECPoint P, BigInteger a,
ECPoint Q, BigInteger b)
{
ECCurve c = P.getCurve();
if (!c.equals(Q.getCurve()))
{
throw new IllegalArgumentException("P and Q must be on same curve");
}
// Point multiplication for Koblitz curves (using WTNAF) beats Shamir's trick
if (c instanceof ECCurve.F2m)
{
ECCurve.F2m f2mCurve = (ECCurve.F2m)c;
if (f2mCurve.isKoblitz())
{
return P.multiply(a).add(Q.multiply(b));
}
}
return implShamirsTrick(P, a, Q, b);
}
/*
* "Shamir's Trick", originally due to E. G. Straus
* (Addition chains of vectors. American Mathematical Monthly,
* 71(7):806-808, Aug./Sept. 1964)
* <pre>
* Input: The points P, Q, scalar k = (km?, ... , k1, k0)
* and scalar l = (lm?, ... , l1, l0).
* Output: R = k * P + l * Q.
* 1: Z <- P + Q
* 2: R <- O
* 3: for i from m-1 down to 0 do
* 4: R <- R + R {point doubling}
* 5: if (ki = 1) and (li = 0) then R <- R + P end if
* 6: if (ki = 0) and (li = 1) then R <- R + Q end if
* 7: if (ki = 1) and (li = 1) then R <- R + Z end if
* 8: end for
* 9: return R
* </pre>
*/
public static ECPoint shamirsTrick(ECPoint P, BigInteger k,
ECPoint Q, BigInteger l)
{
if (!P.getCurve().equals(Q.getCurve()))
{
throw new IllegalArgumentException("P and Q must be on same curve");
}
return implShamirsTrick(P, k, Q, l);
}
private static ECPoint implShamirsTrick(ECPoint P, BigInteger k,
ECPoint Q, BigInteger l)
{
int m = Math.max(k.bitLength(), l.bitLength());
ECPoint Z = P.add(Q);
ECPoint R = P.getCurve().getInfinity();
for (int i = m - 1; i >= 0; --i)
{
R = R.twice();
if (k.testBit(i))
{
if (l.testBit(i))
{
R = R.add(Z);
}
else
{
R = R.add(P);
}
}
else
{
if (l.testBit(i))
{
R = R.add(Q);
}
}
}
return R;
}
}
|
package org.clapper.util.config;
import java.io.*;
import java.util.*;
import java.net.*;
import org.clapper.util.text.*;
import org.clapper.util.io.*;
public class Configuration
implements VariableDereferencer, VariableNameChecker
{
private static final String COMMENT_CHARS = "#!";
private static final char SECTION_START = '[';
private static final char SECTION_END = ']';
private static final String INCLUDE = "%include";
private static final int MAX_INCLUDE_NESTING_LEVEL = 50;
/**
* Contains one logical input line.
*/
private class Line
{
static final int COMMENT = 0;
static final int INCLUDE = 1;
static final int SECTION = 2;
static final int VARIABLE = 3;
static final int BLANK = 4;
int number = 0;
int type = COMMENT;
StringBuffer buffer = new StringBuffer();
Line()
{
}
void newLine()
{
buffer.setLength (0);
}
}
/**
* Contents of a variable. Mostly exists to make replacing a variable
* value easier while looping over a section.
*/
private class Variable
{
String name;
String cookedValue;
String rawValue;
Variable (String name, String value)
{
this.name = name;
setValue (value);
}
void setValue (String value)
{
this.rawValue = value;
this.cookedValue = value;
}
}
/**
* Contents of a section
*/
private class Section
{
/**
* Name of section
*/
String name;
/**
* Names of variables, in order encountered. Contains strings.
*/
List variableNames = new ArrayList();
/**
* List of Variable objects, indexed by variable name
*/
Map valueMap = new HashMap();
Section (String name)
{
this.name = name;
}
Variable getVariable (String varName)
{
return (Variable) valueMap.get (varName);
}
Variable addVariable (String varName, String value)
{
Variable variable = new Variable (varName, value);
valueMap.put (varName, variable);
variableNames.add (varName);
return variable;
}
}
/**
* Container for data used only during parsing.
*/
private class ParseData
{
/**
* Current section. Only set during parsing.
*/
private Section currentSection = null;
/**
* Current variable name being processed. Used during the variable
* substitution parsing phase.
*/
private Variable currentVariable = null;
/**
* Total number of variable substitutions performed on the current
* variable's value during one substitution round. Used during the
* variable substitution parsing phase.
*/
private int totalSubstitutions = 0;
/**
* Current include file nesting level. Used as a fail-safe during
* parsing.
*/
private int includeFileNestingLevel = 0;
/**
* Table of files/URLs currently open. Used during include
* processing.
*/
private Set openURLs = new HashSet();
ParseData()
{
}
}
/**
* List of sections, in order encountered. Each element is a reference to
* a Section object.
*/
private List sectionsInOrder = new ArrayList();
/**
* Sections by name. Each index is a string. Each value is a reference to
* a Section object.
*/
private Map sectionsByName = new HashMap();
/**
* Data used during parsing. Null when parsing isn't being done.
*/
private ParseData parseData = null;
/**
* Construct an empty <tt>Configuration</tt> object. The object may
* later be filled with configuration data via one of the <tt>load()</tt>
* methods, or by calls to {@link #addSection addSection()} and
* {@link #setVariable setVariable()}.
*/
public Configuration()
{
}
/**
* Construct a <tt>Configuration</tt> object that parses data from
* the specified file.
*
* @param f The <tt>File</tt> to open and parse
*
* @throws IOException can't open or read file
* @throws ConfigurationException error in configuration data
*/
public Configuration (File f)
throws IOException,
ConfigurationException
{
load (f);
}
/**
* Construct a <tt>Configuration</tt> object that parses data from
* the specified file.
*
* @param path the path to the file to parse
*
* @throws FileNotFoundException specified file doesn't exist
* @throws IOException can't open or read file
* @throws ConfigurationException error in configuration data
*/
public Configuration (String path)
throws FileNotFoundException,
IOException,
ConfigurationException
{
load (path);
}
/**
* Construct a <tt>Configuration</tt> object that parses data from
* the specified URL.
*
* @param url the URL to open and parse
*
* @throws IOException can't open or read URL
* @throws ConfigurationException error in configuration data
*/
public Configuration (URL url)
throws IOException,
ConfigurationException
{
load (url);
}
/**
* Construct a <tt>Configuration</tt> object that parses data from
* the specified <tt>InputStream</tt>.
*
* @param iStream the <tt>InputStream</tt>
*
* @throws IOException can't open or read URL
* @throws ConfigurationException error in configuration data
*/
public Configuration (InputStream iStream)
throws IOException,
ConfigurationException
{
parse (iStream, null);
}
/**
* Add a new section to this configuration data.
*
* @param sectionName the name of the new section
*
* @throws SectionExistsException a section by that name already exists
*
* @see #containsSection
* @see #getSectionNames
* @see #setVariable
*/
public void addSection (String sectionName)
throws SectionExistsException
{
if (sectionsByName.get (sectionName) != null)
throw new SectionExistsException (sectionName);
makeNewSection (sectionName);
}
/**
* Clear this object of all configuration data.
*/
public void clear()
{
sectionsInOrder.clear();
sectionsByName.clear();
}
/**
* Determine whether this object contains a specified section.
*
* @param sectionName the section name
*
* @return <tt>true</tt> if the section exists in this configuration,
* <tt>false</tt> if not.
*
* @see #getSectionNames
* @see #addSection
*/
public boolean containsSection (String sectionName)
{
return (sectionsByName.get (sectionName) != null);
}
/**
* Get the names of the sections in this object, in the order they were
* parsed and/or added.
*
* @param collection the <tt>Collection</tt> to which to add the section
* names. The names are added in the order they were
* parsed and/or added to this object; of course, the
* <tt>Collection</tt> may reorder them.
*
* @return the <tt>collection</tt> parameter, for convenience
*
* @see #getVariableNames
*/
public Collection getSectionNames (Collection collection)
{
for (Iterator it = sectionsInOrder.iterator(); it.hasNext(); )
collection.add (((Section) it.next()).name);
return collection;
}
/**
* Get the names of the all the variables in a section, in the order
* they were parsed and/or added.
*
* @param sectionName the name of the section to access
* @param collection the <tt>Collection</tt> to which to add the variable
* names. The names are added in the order they were
* parsed and/or added to this object; of course, the
* <tt>Collection</tt> may reorder them.
*
* @return the <tt>collection</tt> parameter, for convenience
*
* @throws NoSuchSectionException no such section
*
* @see #getSectionNames
* @see #containsSection
* @see #getVariableValue
*/
public Collection getVariableNames (String sectionName,
Collection collection)
throws NoSuchSectionException
{
Section section = (Section) sectionsByName.get (sectionName);
if (section == null)
throw new NoSuchSectionException (sectionName);
collection.addAll (section.variableNames);
return collection;
}
/**
* Get the value for a variable.
*
* @param sectionName the name of the section containing the variable
* @param variableName the variable name
*
* @return the value for the variable (which may be the empty string)
*
* @throws NoSuchSectionException the named section does not exist
* @throws NoSuchVariableException the section has no such variable
*/
public String getVariableValue (String sectionName, String variableName)
throws NoSuchSectionException,
NoSuchVariableException
{
Section section = (Section) sectionsByName.get (sectionName);
if (section == null)
throw new NoSuchSectionException (sectionName);
Variable variable = (Variable) section.getVariable (variableName);
if (variable == null)
throw new NoSuchVariableException (sectionName, variableName);
return variable.cookedValue;
}
/**
* Get the value associated with a given variable. Required by the
* {@link VariableDereferencer} interface, this method is used during
* parsing to handle variable substitutions (but also potentially
* useful by other applications). See this class's documentation for
* details on variable references.
*
* @param varName The name of the variable for which the value is
* desired.
*
* @return The variable's value. If the variable has no value, this
* method must return the empty string (""). It is important
* <b>not</b> to return null.
*
* @throws VariableSubstitutionException variable references itself
*/
public String getValue (String varName)
throws VariableSubstitutionException
{
if (parseData.currentVariable.name.equals (varName))
{
throw new VariableSubstitutionException ("Attempt to substitute "
+ "value for variable \""
+ varName
+ "\" within itself.");
}
int i;
Section section;
String value = null;
i = varName.indexOf (':');
if (i == -1)
{
section = parseData.currentSection;
}
else
{
section = (Section) sectionsByName.get (varName.substring (0, i));
varName = varName.substring (i + 1);
}
if (section != null)
{
Variable var = (Variable) section.getVariable (varName);
if (var != null)
value = var.cookedValue;
}
parseData.totalSubstitutions++;
return (value == null) ? "" : value;
}
public boolean legalVariableCharacter (char c)
{
return (Character.isLetterOrDigit (c) ||
(c == '_') ||
(c == '.') ||
(c == ':'));
}
/**
* Load configuration from a <tt>File</tt>. Any existing data is
* discarded.
*
* @param file the file
*
* @throws IOException read error
* @throws ConfigurationException parse error
*/
private void load (File file)
throws IOException,
ConfigurationException
{
clear();
parse (new FileInputStream (file), file.toURL());
}
/**
* Load configuration from a file specified as a pathname. Any existing
* data is discarded.
*
* @param path the path
*
* @throws FileNotFoundException specified file doesn't exist
* @throws IOException can't open or read file
* @throws ConfigurationException error in configuration data
*/
private void load (String path)
throws FileNotFoundException,
IOException,
ConfigurationException
{
clear();
parse (new FileInputStream (path), new File (path).toURL());
}
/**
* Load configuration from a URL. Any existing data is discarded.
*
* @param url the URL
*
* @throws IOException read error
* @throws ConfigurationException parse error
*/
private void load (URL url)
throws IOException,
ConfigurationException
{
clear();
parse (url.openStream(), url);
}
/**
* Set a variable's value. If the variable does not exist, it is created.
* If it does exist, its current value is overwritten with the new one.
* Metacharacters and variable references are not expanded unless the
* <tt>expand</tt> parameter is <tt>true</tt>. An <tt>expand</tt> value
* of <tt>false</tt> is useful when creating new configuration data to
* be written later.
*
* @param sectionName name of existing section to contain the variable
* @param variableName name of variable to set
* @param value variable's value
* @param expand <tt>true</tt> to expand metacharacters and variable
* references in the value, <tt>false</tt> to leave
* the value untouched.
*
* @throws NoSuchSectionException section does not exist
* @throws VariableSubstitutionException variable substitution error
*/
public void setVariable (String sectionName,
String variableName,
String value,
boolean expand)
throws NoSuchSectionException,
VariableSubstitutionException
{
Section section = (Section) sectionsByName.get (sectionName);
if (section == null)
throw new NoSuchSectionException (sectionName);
Variable variable = (Variable) section.getVariable (variableName);
if (variable != null)
variable.setValue (value);
else
variable = section.addVariable (variableName, value);
if (expand)
{
try
{
// substituteVariables() requires that the parseData
// instance variable be non-null and have valid values for
// currentSection and currentVariable.
parseData = new ParseData();
parseData.currentSection = section;
substituteVariables (variable,
new UnixShellVariableSubstituter());
}
finally
{
parseData = null;
}
}
}
/**
* Writes the configuration data to a <tt>PrintWriter</tt>. The sections
* and variables within the sections are written in the order they were
* originally read from the file. Non-printable characters (and a few
* others) are encoded into metacharacter sequences. Comments and
* variable references are not propagated, since they are not retained
* when the data is parsed.
*
* @param out where to write the configuration data
*
* @see XStringBuffer#encodeMetacharacters()
*/
public void write (PrintWriter out)
{
Iterator itSect;
Iterator itVar;
Section section;
String varName;
Variable var;
XStringBuffer value = new XStringBuffer();
boolean firstSection = true;
out.print (COMMENT_CHARS.charAt (0));
out.print (" Written by ");
out.println (this.getClass().getName());
out.print (COMMENT_CHARS.charAt (0));
out.print (" on ");
out.println (new Date().toString());
out.println();
for (itSect = sectionsInOrder.iterator(); itSect.hasNext(); )
{
section = (Section) itSect.next();
if (! firstSection)
out.println();
out.println (SECTION_START + section.name + SECTION_END);
firstSection = false;
for (itVar = section.variableNames.iterator(); itVar.hasNext(); )
{
varName = (String) itVar.next();
var = (Variable) section.getVariable (varName);
value.setLength (0);
value.append (var.cookedValue);
value.encodeMetacharacters();
out.println (varName + ": " + value.toString());
}
}
}
/**
* Writes the configuration data to a <tt>PrintStream</tt>. The sections
* and variables within the sections are written in the order they were
* originally read from the file. Non-printable characters (and a few
* others) are encoded into metacharacter sequences. Comments and
* variable references are not propagated, since they are not retained
* when the data is parsed.
*
* @param out where to write the configuration data
*
* @see XStringBuffer#encodeMetacharacters()
*/
public void write (PrintStream out)
{
PrintWriter w = new PrintWriter (out);
write (w);
w.flush();
}
/**
* Parse configuration data from the specified stream.
*
* @param in the input stream
* @param url the URL associated with the stream, or null if not known
*
* @throws ConfigurationException parse error
*/
private synchronized void parse (InputStream in, URL url)
throws ConfigurationException
{
parseData = new ParseData();
try
{
loadConfiguration (in, url);
postProcessParsedData();
}
finally
{
parseData = null;
}
}
/**
* Load the configuration data into memory, without processing
* metacharacters or variable substitution. Includes are processed,
* though.
*
* @param in the input stream
* @param url the URL associated with the stream, or null if not known
*
* @throws IOException read error
* @throws ConfigurationException parse error
*/
private void loadConfiguration (InputStream in, URL url)
throws ConfigurationException
{
BufferedReader r = new BufferedReader (new InputStreamReader (in));
Line line = new Line();
String sURL = url.toExternalForm();
if (parseData.openURLs.contains (sURL))
{
throw new ConfigurationException
(getExceptionPrefix (line, url)
+ "Attempt to include \""
+ sURL
+ "\" from itself, either directly or indirectly.");
}
parseData.openURLs.add (sURL);
// Parse the entire file into memory before doing variable
// substitution and metacharacter expansion.
while (readLogicalLine (r, line))
{
try
{
switch (line.type)
{
case Line.COMMENT:
case Line.BLANK:
break;
case Line.INCLUDE:
handleInclude (line, url);
break;
case Line.SECTION:
parseData.currentSection = handleNewSection (line,
url);
break;
case Line.VARIABLE:
if (parseData.currentSection == null)
{
throw new ConfigurationException
(getExceptionPrefix (line, url)
+ "Variable assignment before "
+ "first section.");
}
handleVariable (line, url);
break;
default:
throw new IllegalStateException
("Bug: line.type=" + line.type);
}
}
catch (IOException ex)
{
throw new ConfigurationException
(getExceptionPrefix (line, url)
+ ex.toString());
}
}
parseData.openURLs.remove (sURL);
}
/**
* Post-process the loaded configuration, doing variable substitution
* and metacharacter expansion.
*
* @throws ConfigurationException configuration error
*/
private void postProcessParsedData()
throws ConfigurationException
{
VariableSubstituter substituter;
Iterator itSect;
Iterator itVar;
String varName;
Section section;
XStringBuffer buf = new XStringBuffer();
// First, expand the the metacharacter sequences.
for (itSect = sectionsInOrder.iterator(); itSect.hasNext(); )
{
parseData.currentSection = (Section) itSect.next();
for (itVar = parseData.currentSection.variableNames.iterator();
itVar.hasNext(); )
{
varName = (String) itVar.next();
section = parseData.currentSection;
parseData.currentVariable = section.getVariable (varName);
buf.setLength (0);
buf.append (parseData.currentVariable.cookedValue);
buf.decodeMetacharacters();
parseData.currentVariable.cookedValue = buf.toString();
}
}
// Now, do variable substitution.
parseData.currentSection = null;
substituter = new UnixShellVariableSubstituter();
for (itSect = sectionsInOrder.iterator(); itSect.hasNext(); )
{
parseData.currentSection = (Section) itSect.next();
for (itVar = parseData.currentSection.variableNames.iterator();
itVar.hasNext(); )
{
varName = (String) itVar.next();
section = parseData.currentSection;
parseData.currentVariable = section.getVariable (varName);
try
{
substituteVariables (parseData.currentVariable,
substituter);
}
catch (VariableSubstitutionException ex)
{
throw new ConfigurationException (ex);
}
}
}
}
/**
* Handle a new section.
*
* @param line line buffer
* @param url URL currently being processed, or null if unknown
*
* @return a new Section object, which has been stored in the appropriate
* places
*
* @throws ConfigurationException configuration error
*/
private Section handleNewSection (Line line, URL url)
throws ConfigurationException
{
String s = line.buffer.toString().trim();
if (s.charAt (0) != SECTION_START)
{
throw new ConfigurationException
(getExceptionPrefix (line, url)
+ "Section does not begin with '"
+ SECTION_START
+ "'");
}
else if (s.charAt (s.length() - 1) != SECTION_END)
{
throw new ConfigurationException
(getExceptionPrefix (line, url)
+ "Section does not end with '"
+ SECTION_END
+ "'");
}
return makeNewSection (s.substring (1, s.length() - 1));
}
/**
* Handle a new variable.
*
* @param line line buffer
* @param url URL currently being processed, or null if unknown
*
* @throws ConfigurationException configuration error
*/
private void handleVariable (Line line, URL url)
throws ConfigurationException
{
String s = line.buffer.toString();
int i;
if ( ((i = s.indexOf ('=')) == -1) &&
((i = s.indexOf (':')) == -1) )
{
throw new ConfigurationException (getExceptionPrefix (line, url)
+ "Missing '=' or ':' for "
+ "variable definition.");
}
if (i == 0)
{
throw new ConfigurationException (getExceptionPrefix (line, url)
+ "Missing variable name for "
+ "variable definition.");
}
String varName = s.substring (0, i);
String value = s.substring (skipWhitespace (s, i + 1));
if (parseData.currentSection.getVariable (varName) != null)
{
throw new ConfigurationException (getExceptionPrefix (line, url)
+ "Section \""
+ parseData.currentSection.name
+ "\": Duplicate definition of "
+ "variable \""
+ varName
+ "\".");
}
parseData.currentSection.addVariable (varName, value);
}
/**
* Handle an include directive.
*
* @param line line buffer
* @param url URL currently being processed, or null if unknown
*
* @throws IOException I/O error opening or reading include
* @throws ConfigurationException configuration error
*/
private void handleInclude (Line line, URL url)
throws IOException,
ConfigurationException
{
if (parseData.includeFileNestingLevel >= MAX_INCLUDE_NESTING_LEVEL)
{
throw new ConfigurationException (getExceptionPrefix (line, url)
+ "Exceeded maximum nested "
+ "include level of "
+ MAX_INCLUDE_NESTING_LEVEL
+ ".");
}
parseData.includeFileNestingLevel++;
String s = line.buffer.toString();
// Parse the file name.
String includeTarget = s.substring (INCLUDE.length() + 1).trim();
int len = includeTarget.length();
// Make sure double quotes surround the file or URL.
if ((len < 2) ||
(! includeTarget.startsWith ("\"")) ||
(! includeTarget.endsWith ("\"")))
{
throw new ConfigurationException (getExceptionPrefix (line, url)
+ "Malformed "
+ INCLUDE
+ " directive.");
}
// Extract the file.
includeTarget = includeTarget.substring (1, len - 1);
if (includeTarget.length() == 0)
{
throw new ConfigurationException (getExceptionPrefix (line, url)
+ "Missing file name or URL in "
+ INCLUDE
+ " directive.");
}
// Process the include
try
{
loadInclude (new URL (includeTarget));
}
catch (MalformedURLException ex)
{
// Not obviously a URL. First, determine whether it has
// directory information or not. If not, try to use the
// parent's directory information.
if (FileUtils.isAbsolutePath (includeTarget))
{
loadInclude (new URL (url.getProtocol(),
url.getHost(),
url.getPort(),
includeTarget));
}
else
{
// It's relative to the parent. If the parent URL is not
// specified, then we can't do anything except try to load
// the include as is. It'll probably fail...
if (url == null)
{
loadInclude (new File (includeTarget).toURL());
}
else
{
String parent = new File (url.getFile()).getParent();
if (parent == null)
parent = "";
loadInclude (new URL (url.getProtocol(),
url.getHost(),
url.getPort(),
parent + "/" + includeTarget));
}
}
}
parseData.includeFileNestingLevel
}
/**
* Actually attempts to load an include reference. This is basically just
* a simplified front-end to loadConfiguration().
*
* @param url the URL to be included
*
* @throws IOException I/O error
* @throws ConfigurationException configuration error
*/
private void loadInclude (URL url)
throws IOException,
ConfigurationException
{
loadConfiguration (url.openStream(), url);
}
/**
* Read the next logical line of input from a config file.
*
* @param r the reader
* @param line where to store the line. The line number in this
* object is incremented, the "buffer" field is updated,
* and the "type" field is set appropriately.
*
* @return <tt>true</tt> if a line was read, <tt>false</tt> for EOF.
*
* @throws ConfigurationException read error
*/
private boolean readLogicalLine (BufferedReader r, Line line)
throws ConfigurationException
{
boolean continued = false;
boolean gotSomething = false;
line.newLine();
for (;;)
{
String s;
try
{
s = r.readLine();
}
catch (IOException ex)
{
throw new ConfigurationException (ex);
}
if (s == null)
break;
gotSomething = true;
line.number++;
// Strip leading white space on all lines.
int i;
char[] chars = s.toCharArray();
i = skipWhitespace (chars, 0);
if (i < chars.length)
s = s.substring (i);
else
s = "";
if (! continued)
{
// First line. Determine what it is.
char firstChar;
if (s.length() == 0)
line.type = Line.BLANK;
else if (COMMENT_CHARS.indexOf (s.charAt (0)) != -1)
line.type = Line.COMMENT;
else if (s.charAt (0) == SECTION_START)
line.type = Line.SECTION;
else if (new StringTokenizer (s).nextToken().equals (INCLUDE))
line.type = Line.INCLUDE;
else
line.type = Line.VARIABLE;
}
if ((line.type == Line.VARIABLE) && (hasContinuationMark (s)))
{
continued = true;
line.buffer.append (s.substring (0, s.length() - 1));
}
else
{
line.buffer.append (s);
break;
}
}
return gotSomething;
}
/**
* Determine whether a line has a continuation mark or not.
*
* @param s the line
*
* @return true if there's a continuation mark, false if not
*/
private boolean hasContinuationMark (String s)
{
boolean has = false;
if (s.length() > 0)
{
char[] chars = s.toCharArray();
if (chars[chars.length-1] == '\\')
{
// Possibly. See if there are an odd number of them.
int total = 0;
for (int i = chars.length - 1; i >= 0; i
{
if (chars[i] != '\\')
break;
total++;
}
has = ((total % 2) == 1);
}
}
return has;
}
/**
* Get an appropriate exception prefix (e.g., line number, etc.)
*
* @param line line buffer
* @param url URL currently being processed, or null if unknown
*
* @return a suitable string
*/
private String getExceptionPrefix (Line line, URL url)
{
StringBuffer buf = new StringBuffer();
if (url != null)
{
buf.append (url.toExternalForm());
buf.append (", line ");
}
else
{
buf.append ("Line ");
}
buf.append (line.number);
buf.append (": ");
return buf.toString();
}
/**
* Handle variable substitution for a variable value. NOTE: Requires
* that the "parseData" instance be non-null, and its "currentSection"
* item be appropriately set. (This method sets "currentVariable".)
*
* @param var The variable to expand
* @param substituter VariableSubstituter to use
*
* @return the expanded result
*
* @throws VariableSubstitutionException variable substitution error
*/
private void substituteVariables (Variable var,
VariableSubstituter substituter)
throws VariableSubstitutionException
{
// Keep substituting the current variable's value until there no
// more substitutions are performed. This handles the case where a
// dereferenced variable value contains its own variable
// references.
parseData.currentVariable = var;
do
{
parseData.totalSubstitutions = 0;
var.cookedValue = substituter.substitute (var.cookedValue,
this,
this);
}
while (parseData.totalSubstitutions > 0);
}
/**
* Get index of first non-whitespace character.
*
* @param s string to check
* @param start starting point
*
* @return index of first non-whitespace character past "start", or -1
*/
private int skipWhitespace (String s, int start)
{
return skipWhitespace (s.toCharArray(), start);
}
/**
* Get index of first non-whitespace character.
*
* @param chars character array to check
* @param start starting point
*
* @return index of first non-whitespace character past "start", or -1
*/
private int skipWhitespace (char[] chars, int start)
{
while (start < chars.length)
{
if (! Character.isWhitespace (chars[start]))
break;
start++;
}
return start;
}
/**
* Create and save a new Section.
*
* @param sectionName the name
*
* @return the Section object, which has been saved.
*/
private Section makeNewSection (String sectionName)
{
Section section = new Section (sectionName);
sectionsInOrder.add (section);
sectionsByName.put (sectionName, section);
return section;
}
}
|
package org.egordorichev.lasttry.entity;
import org.egordorichev.lasttry.util.Direction;
public abstract class Enemy extends Entity {
public static final String SLIME_GREEN = "Green Slime";
public static final String SLIME_BLUE = "Blue Slime";
protected int currentAi;
protected int maxAi;
public Enemy(String name, int maxHp, int defense, int damage) {
super(name, false, maxHp, defense, damage);
this.currentAi = 0;
}
public Enemy(String name) {
super(name, false);
this.currentAi = 0;
}
@Override
public void render() {
this.animations[this.state.getId()]
.getCurrentFrame().getFlippedCopy(this.direction == Direction.RIGHT, false)
.draw(this.renderBounds.x, this.renderBounds.y);
}
@Override
public void update(int dt) {
super.update(dt);
this.updateAI();
}
public void updateAI() {
this.currentAi++;
if(this.currentAi >= this.maxAi) {
this.currentAi = 0;
}
}
@Override
public void onSpawn() {
}
public static Enemy create(String name) {
if (name.equals(Enemy.SLIME_GREEN)) {
return new GreenSlime();
} else if(name.equals(SLIME_BLUE)) {
return new BlueSlime();
} else {
throw new RuntimeException("Entity with name " + name + " is not found.");
}
}
}
|
package org.idlesoft.android.hubroid;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class UserInfo extends Activity {
public JSONObject m_jsonData;
private SharedPreferences m_prefs;
private SharedPreferences.Editor m_editor;
public Intent m_intent;
private String m_username;
private String m_token;
private String m_targetUser;
private boolean m_isFollowing;
private OnClickListener onButtonClick = new OnClickListener() {
public void onClick(View v) {
Intent intent;
// Figure out what button was clicked
int id = v.getId();
switch (id) {
case R.id.btn_user_info_repositories:
// Go to the user's list of repositories
intent = new Intent(UserInfo.this, RepositoriesList.class);
intent.putExtra("username", m_targetUser);
startActivity(intent);
break;
case R.id.btn_user_info_followers_following:
// Go to the Followers/Following screen
intent = new Intent(UserInfo.this, FollowersFollowing.class);
intent.putExtra("username", m_targetUser);
startActivity(intent);
break;
case R.id.btn_user_info_watched_repositories:
// Go to the Watched Repositories screen
intent = new Intent(UserInfo.this, WatchedRepositories.class);
intent.putExtra("username", m_targetUser);
startActivity(intent);
break;
default:
// oh well...
break;
}
}
};
public boolean onPrepareOptionsMenu(Menu menu) {
if (menu.hasVisibleItems()) menu.clear();
if (m_isFollowing) {
menu.add(0, 3, 0, "Unfollow");
} else {
menu.add(0, 3, 0, "Follow");
}
menu.add(0, 0, 0, "Back to Main").setIcon(android.R.drawable.ic_menu_revert);
menu.add(0, 1, 0, "Clear Preferences");
menu.add(0, 2, 0, "Clear Cache");
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 3:
try {
HttpClient client = new DefaultHttpClient();
URL command;
if (m_isFollowing) {
command = new URL("http://github.com/api/v2/json/user/unfollow/"
+ URLEncoder.encode(m_targetUser));
} else {
command = new URL("http://github.com/api/v2/json/user/follow/"
+ URLEncoder.encode(m_targetUser));
}
HttpPost post = new HttpPost(command.toString());
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("login", m_username));
nameValuePairs.add(new BasicNameValuePair("token", m_token));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
if (m_isFollowing) {
Toast.makeText(this, "You are no longer following " + m_targetUser + ".", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "You are now following " + m_targetUser + ".", Toast.LENGTH_SHORT).show();
}
m_isFollowing = !m_isFollowing;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
break;
case 0:
Intent i1 = new Intent(this, Hubroid.class);
startActivity(i1);
return true;
case 1:
m_editor.clear().commit();
Intent intent = new Intent(this, Hubroid.class);
startActivity(intent);
return true;
case 2:
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()) {
File hubroid = new File(root, "hubroid");
if (!hubroid.exists() && !hubroid.isDirectory()) {
return true;
} else {
hubroid.delete();
return true;
}
}
}
return false;
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.user_info);
m_prefs = getSharedPreferences(Hubroid.PREFS_NAME, 0);
m_editor = m_prefs.edit();
m_username = m_prefs.getString("login", "");
m_token = m_prefs.getString("token", "");
m_isFollowing = false;
Bundle extras = getIntent().getExtras();
if (extras != null) {
try {
m_targetUser = extras.getString("username");
URL user_query = new URL("http://github.com/api/v2/json/user/show/"
+ URLEncoder.encode(m_targetUser));
JSONObject json = Hubroid.make_api_request(user_query);
if (json == null) {
// User doesn't really exist, return to the previous activity
this.setResult(5005);
this.finish();
} else {
m_jsonData = json.getJSONObject("user");
try {
URL following_url = new URL("http://github.com/api/v2/json/user/show/"
+ URLEncoder.encode(m_username) + "/following");
JSONArray following_list = Hubroid.make_api_request(following_url).getJSONArray("users");
int length = following_list.length() - 1;
for (int i = 0; i <= length; i++) {
if (following_list.getString(i).equalsIgnoreCase(m_targetUser)) {
m_isFollowing = true;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
String company, location, full_name, email, blog;
// Replace empty values with "N/A"
if (m_jsonData.has("company") && !m_jsonData.getString("company").equals("null") && !m_jsonData.getString("company").equals("")) {
company = m_jsonData.getString("company");
} else {
company = "N/A";
}
if (m_jsonData.has("location") && !m_jsonData.getString("location").equals("null") && !m_jsonData.getString("location").equals("")) {
location = m_jsonData.getString("location");
} else {
location = "N/A";
}
if (m_jsonData.has("name") && !m_jsonData.getString("name").equals("null")) {
full_name = m_jsonData.getString("name");
} else {
full_name = "N/A";
}
if (m_jsonData.has("email") && !m_jsonData.getString("email").equals("null") && !m_jsonData.getString("email").equals("")) {
email = m_jsonData.getString("email");
} else {
email = "N/A";
}
if (m_jsonData.has("blog") && !m_jsonData.getString("blog").equals("null") && !m_jsonData.getString("blog").equals("")) {
blog = m_jsonData.getString("blog");
} else {
blog = "N/A";
}
// Set all the values in the layout
((TextView)findViewById(R.id.tv_top_bar_title)).setText(m_targetUser);
((ImageView)findViewById(R.id.iv_user_info_gravatar)).setImageBitmap(Hubroid.getGravatar(Hubroid.getGravatarID(m_targetUser), 50));
((TextView)findViewById(R.id.tv_user_info_full_name)).setText(full_name);
((TextView)findViewById(R.id.tv_user_info_company)).setText(company);
((TextView)findViewById(R.id.tv_user_info_email)).setText(email);
((TextView)findViewById(R.id.tv_user_info_location)).setText(location);
((TextView)findViewById(R.id.tv_user_info_blog)).setText(blog);
// Make the buttons work
Button repositoriesBtn = (Button) findViewById(R.id.btn_user_info_repositories);
Button followersFollowingBtn = (Button) findViewById(R.id.btn_user_info_followers_following);
Button watchedRepositoriesBtn = (Button) findViewById(R.id.btn_user_info_watched_repositories);
repositoriesBtn.setOnClickListener(onButtonClick);
followersFollowingBtn.setOnClickListener(onButtonClick);
watchedRepositoriesBtn.setOnClickListener(onButtonClick);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
|
package org.jcryptool.visual.ssl.views;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.wb.swt.SWTResourceManager;
/**
* This class implements a JPanel that provides functions for drawing a list of
* arrows inside the panel. The arrows can be represented in black or in red.
*
* @author Denk Gandalf
*
*/
public class Arrows extends Canvas
{
/**
* A vector which saves all arrows which need to be painted
*/
private List<int[]> arrows;
/**
* Constructor of the class, creates a new Vector for the arrows
*/
/**
* Implements the paint method. Paints all arrows in the Vector arrow inside
* the panel and sets the background to grey.
*/
public Arrows(Composite parent, int style) {
super(parent, style);
arrows = new ArrayList<int[]>();
addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e)
{
int a[] = { 0, 0, 0, 0, 0, 0, 0 };
for (int i = 0; i < arrows.size(); i++) {
a = arrows.get(i);
if(a[5]==180)
{
e.gc.setBackground(SWTResourceManager.getColor(SWT.COLOR_DARK_GREEN));
e.gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_GREEN));
}
else
{
e.gc.setBackground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
e.gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
}
drawArrow(e, a[0], a[1], a[2], a[3]);
}
}
});
}
/**
* Draws a arrow from x, y to x1, y1 with an arrowhead in the right
* direction. The coordinations need to be chosen inside the JPanel.
*
* @param g1
* gives the Graphic set that is used
* @param x1
* X-coordination of the start point
* @param y1
* Y-coordination of the start point
* @param x2
* X-coordination of the end point
* @param y2
* Y-coordination of the end point
*/
private void drawArrow(PaintEvent e, int x1, int y1, int x2, int y2) {
e.gc.drawLine(x1, y1, x2,y2);
if(y1!=y2)
{
e.gc.fillPolygon(new int[]{x2,y2,x2-10,y2-5,x2-3,y2-12});
}
else if(x2>x1)
{
e.gc.fillPolygon(new int[]{x2,y2,x2-10,y2+5,x2-10,y2-5});
}
else
{
e.gc.fillPolygon(new int[]{x2,y2,x2+10,y2+5,x2+10,y2-5});
}
}
public void nextArrow(int x1, int y1, int x2, int y2, int r, int g, int b) {
int aro[] = { x1, y1, x2, y2, r, g, b };
arrows.add(aro);
redraw();
}
/**
* Removes the arrow that has been added latest
*/
public void removeLastArrow() {
arrows.remove(arrows.size() - 1);
redraw();
}
/**
* Removes all arrows.
*/
public void resetArrows() {
arrows.clear();
redraw();
}
/**
* Moves all arrows inside the panel for the value of distance positive
* values move the arrows upwards, negative once move them downwards.
*
* @param distance
* the distance the arrows are moved
*/
public void moveArrowsby(int distance) {
int a[] = { 0, 0, 0, 0, 0, 0, 0 };
for (int i = 0; i < arrows.size(); i++) {
a = arrows.get(i);
a[1] = a[1] - distance;
a[3] = a[3] - distance;
arrows.set(i, a);
}
redraw();
}
}
|
package org.latte.scripting.hostobjects;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import java.net.HttpURLConnection;
import org.mozilla.javascript.Callable;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.JavaScriptException;
import org.mozilla.javascript.Scriptable;
public class HPost implements Callable {
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] params) {
try {
URL url = new URL((String)params[0]);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
Scriptable reqParams = (Scriptable)params[1];
if(reqParams != null) {
for(Object key : reqParams.getIds()) {
connection.setRequestProperty(key.toString(), reqParams.get(key.toString(), reqParams).toString());
}
}
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write((String)params[2]);
writer.close();
InputStream in = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String res;
while ((res = br.readLine()) != null) {
sb.append(res);
}
br.close();
in.close();
return sb.toString();
} catch (Exception e) {
throw new JavaScriptException(e, "hpost", 0);
}
}
}
|
/*
* $Id: HttpResultMap.java,v 1.17 2014-11-21 22:36:29 tlipkis Exp $
*/
package org.lockss.util.urlconn;
import java.util.*;
import java.net.*;
import org.lockss.util.*;
import org.lockss.daemon.PluginException;
import org.lockss.plugin.ArchivalUnit;
/**
* Maps an HTTP result to success (null) or an exception, usually one under
* CacheException
*/
public class HttpResultMap implements CacheResultMap {
static Logger log = Logger.getLogger("HttpResultMap");
int[] SuccessCodes = {200, 203, 304};
int[] SameUrlCodes = { 408, 409, 413, 500, 502, 503, 504};
int[] MovePermCodes = {301};
int[] MoveTempCodes = { 307, 303, 302};
int[] UnimplementedCodes = {};
int[] PermissionCodes = { 401, 403, 407};
int[] ExpectedCodes = { 305, 402};
int[] RetryDeadLinkCodes = {};
int[] NoRetryDeadLinkCodes= {204, 300, 400, 404, 405, 406, 410};
int[] UnexpectedFailCodes = {
201, 202, 205, 206, 306,
411, 412, 416, 417, 501, 505};
int[] UnexpectedNoFailCodes = { 414, 415 };
/** Abstracts the event we're determining how to handle. Either an HTTP
* response or an Exception */
abstract static class Event {
String message;
Event(String message) {
this.message = message;
}
String getMessage() {
return message;
}
/** Return string for either response code or Exception */
abstract String getResultString();
/** Invoke the handler on the result (responseCode or Exception) */
@Deprecated
abstract CacheException invokeHandler(CacheResultHandler handler,
ArchivalUnit au,
LockssUrlConnection conn)
throws PluginException;
/** Invoke the handler on the result (responseCode or Exception) */
abstract CacheException invokeHandler(CacheResultHandler handler,
ArchivalUnit au,
String url)
throws PluginException;
}
/** HTTP response event */
static class ResponseEvent extends Event {
int responseCode;
ResponseEvent(int responseCode, String message) {
super(message);
this.responseCode = responseCode;
}
String getResultString() {
return Integer.toString(responseCode);
}
@Deprecated
CacheException invokeHandler(CacheResultHandler handler,
ArchivalUnit au,
LockssUrlConnection conn)
throws PluginException {
return invokeHandler(handler, au, getConnUrl(conn));
}
CacheException invokeHandler(CacheResultHandler handler,
ArchivalUnit au,
String url)
throws PluginException {
return handler.handleResult(au, url, responseCode);
}
}
/** Exception thrown attempting HTTP request or reading response */
static class ExceptionEvent extends Event {
Exception fetchException;
ExceptionEvent(Exception fetchException, String message) {
super(message);
this.fetchException = fetchException;
}
String getResultString() {
return fetchException.getMessage();
}
@Deprecated
CacheException invokeHandler(CacheResultHandler handler, ArchivalUnit au,
LockssUrlConnection conn)
throws PluginException {
return handler.handleResult(au, getConnUrl(conn), fetchException);
}
CacheException invokeHandler(CacheResultHandler handler, ArchivalUnit au,
String url)
throws PluginException {
return handler.handleResult(au, url, fetchException);
}
}
static String getConnUrl(LockssUrlConnection conn) {
return conn != null ? conn.getURL() : null;
}
/** Value in exceptionTable map, specified by plugin: either the class of
* an exception to throw or a CacheResultHandler instance. */
abstract static class ExceptionInfo {
String fmt;
ExceptionInfo(String fmt) {
this.fmt = fmt;
}
ExceptionInfo() {
}
/** Return the CacheException appropriate for the event, either from
* the specified class or CacheResultHandler */
@Deprecated
abstract CacheException makeException(ArchivalUnit au,
LockssUrlConnection connection,
Event evt)
throws Exception;
abstract CacheException makeException(ArchivalUnit au,
String url,
Event evt)
throws Exception;
String fmtMsg(String s, String msg) {
if (fmt != null) {
return String.format(fmt, s);
}
if (msg != null) {
return s + " " + msg;
}
return s;
}
@Deprecated
CacheException getCacheException(ArchivalUnit au,
LockssUrlConnection connection,
Event evt) {
return getCacheException(au, getConnUrl(connection), evt);
}
/** Return the exception to throw for this event, or an
* UnknownCodeException if an error occurs trying to create it */
CacheException getCacheException(ArchivalUnit au,
String url,
Event evt) {
try {
CacheException cacheException = makeException(au, url, evt);
return cacheException;
} catch (Exception ex) {
log.error("Can't make CacheException for: " + evt.getResultString(),
ex);
return new
CacheException.UnknownCodeException("Unable to make exception:"
+ ex.getMessage());
}
}
/** Wraps a plugin-supplied CacheResultHandler */
static class Handler extends ExceptionInfo {
CacheResultHandler handler;
Handler(CacheResultHandler handler) {
this.handler = handler;
}
Handler(CacheResultHandler handler, String fmt) {
super(fmt);
this.handler = handler;
}
@Deprecated
CacheException makeException(ArchivalUnit au,
LockssUrlConnection connection,
Event evt)
throws PluginException {
return makeException(au, getConnUrl(connection), evt);
}
CacheException makeException(ArchivalUnit au,
String url,
Event evt)
throws PluginException {
return evt.invokeHandler(handler, au, url);
}
public String toString() {
return "[EIH: " + handler + "]";
}
}
/** Wraps a CacheException class */
static class Cls extends ExceptionInfo {
Class ex;
Cls(Class ex) {
this.ex = ex;
}
Cls(Class ex, String fmt) {
super(fmt);
this.ex = ex;
}
@Deprecated
CacheException makeException(ArchivalUnit au,
LockssUrlConnection connection,
Event evt)
throws Exception {
return makeException(au, getConnUrl(connection), evt);
}
CacheException makeException(ArchivalUnit au,
String url,
Event evt)
throws Exception {
CacheException exception = (CacheException)ex.newInstance();
exception.initMessage(fmtMsg(evt.getResultString(),
evt.getMessage()));
return exception;
}
public String toString() {
return "[EIC: " + ex + "]";
}
}
}
HashMap<Object,ExceptionInfo> exceptionTable = new HashMap();
public HttpResultMap() {
initExceptionTable();
}
protected void initExceptionTable() {
// HTTP result codes
storeArrayEntries(SuccessCodes, CacheSuccess.class);
storeArrayEntries(SameUrlCodes,
CacheException.RetrySameUrlException.class);
storeArrayEntries(MovePermCodes,
CacheException.NoRetryPermUrlException.class);
storeArrayEntries(MoveTempCodes,
CacheException.NoRetryTempUrlException.class);
storeArrayEntries(UnimplementedCodes,
CacheException.UnimplementedCodeException.class);
storeArrayEntries(PermissionCodes,
CacheException.PermissionException.class);
storeArrayEntries(ExpectedCodes,
CacheException.ExpectedNoRetryException.class);
storeArrayEntries(UnexpectedFailCodes,
CacheException.UnexpectedNoRetryFailException.class);
storeArrayEntries(UnexpectedNoFailCodes,
CacheException.UnexpectedNoRetryNoFailException.class);
storeArrayEntries(RetryDeadLinkCodes,
CacheException.RetryDeadLinkException.class);
storeArrayEntries(NoRetryDeadLinkCodes,
CacheException.NoRetryDeadLinkException.class);
// IOExceptions
storeMapEntry(UnknownHostException.class,
CacheException.RetryableNetworkException_2_30S.class,
"Unknown host: %s");
// SocketException subsumes ConnectException, NoRouteToHostException
// and PortUnreachableException
storeMapEntry(SocketException.class,
CacheException.RetryableNetworkException_3_30S.class);
storeMapEntry(LockssUrlConnection.ConnectionTimeoutException.class,
CacheException.RetryableNetworkException_3_30S.class);
// SocketTimeoutException is an InterruptedIOException, not a
// SocketException
storeMapEntry(SocketTimeoutException.class,
CacheException.RetryableNetworkException_3_30S.class);
// I don't think these can happen
storeMapEntry(ProtocolException.class,
CacheException.RetryableNetworkException_3_30S.class);
storeMapEntry(java.nio.channels.ClosedChannelException.class,
CacheException.RetryableNetworkException_3_30S.class);
storeMapEntry(org.lockss.plugin.ContentValidationException.EmptyFile.class,
CacheException.WarningOnly.class);
}
public void storeArrayEntries(int[] codeArray, Class exceptionClass) {
for (int i=0; i< codeArray.length; i++) {
storeMapEntry(codeArray[i], exceptionClass);
}
}
// For unit tests
void storeArrayEntries(int[] codeArray, CacheResultHandler handler) {
for (int i=0; i< codeArray.length; i++) {
storeMapEntry(codeArray[i], handler);
}
}
/** Map the http result code to the response. DefinablePlugin calls this
* without knowing whether it's passing a CacheResultHandler instance or
* a CacheException class. Should be cleaned up but awkwardness is
* inconsequential */
public void storeMapEntry(int code, Object response) {
if (response instanceof CacheResultHandler) {
storeMapEntry(code,
new ExceptionInfo.Handler((CacheResultHandler)response));
} else if (response instanceof Class) {
storeMapEntry(code, new ExceptionInfo.Cls((Class)response));
} else {
throw new RuntimeException("Unsupported response type: " + response);
}
}
/** Map the http result code to the response. DefinablePlugin calls this
* without knowing whether it's passing a CacheResultHandler instance or
* a CacheException class. Should be cleaned up but awkwardness is
* inconsequential */
public void storeMapEntry(Class fetchExceptionClass, Object response) {
if (response instanceof CacheResultHandler) {
storeMapEntry(fetchExceptionClass, (CacheResultHandler)response);
} else if (response instanceof Class) {
storeMapEntry(fetchExceptionClass, (Class)response);
} else {
throw new RuntimeException("Unsupported response type: " + response);
}
}
/** Map the http result code to the CacheException class */
public void storeMapEntry(int code, Class exceptionClass) {
storeMapEntry(code, exceptionClass, null);
}
/** Map the http result code to the CacheException class */
public void storeMapEntry(int code, Class exceptionClass, String fmt) {
storeMapEntry(code, new ExceptionInfo.Cls(exceptionClass, fmt));
}
/** Map the fetch exception (SocketException, IOException, etc.) to the
* CacheException class */
public void storeMapEntry(Class fetchExceptionClass, Class exceptionClass) {
storeMapEntry(fetchExceptionClass, exceptionClass, null);
}
/** Map the fetch exception (SocketException, IOException, etc.) to the
* CacheException class */
public void storeMapEntry(Class fetchExceptionClass, Class exceptionClass,
String fmt) {
storeMapEntry(fetchExceptionClass,
new ExceptionInfo.Cls(exceptionClass, fmt));
}
/** Map the fetch exception (SocketException, IOException, etc.) to the
* CacheResultHandler instance */
public void storeMapEntry(Class fetchExceptionClass,
CacheResultHandler handler) {
storeMapEntry(fetchExceptionClass,
new ExceptionInfo.Handler(handler));
}
/** Map the fetch exception (SocketException, IOException, etc.) to the
* CacheResultHandler instance */
public void storeMapEntry(Class fetchExceptionClass,
CacheResultHandler handler,
String fmt) {
storeMapEntry(fetchExceptionClass,
new ExceptionInfo.Handler(handler, fmt));
}
/** Map the fetch exception (SocketException, IOException, etc.) to the
* CacheResultHandler instance */
public void storeMapEntry(Class fetchExceptionClass,
ExceptionInfo ei) {
exceptionTable.put(fetchExceptionClass, ei);
}
/** Map the fetch exception (SocketException, IOException, etc.) to the
* CacheResultHandler instance */
public void storeMapEntry(int code,
ExceptionInfo ei) {
exceptionTable.put(code, ei);
}
public CacheException getMalformedURLException(Exception nestedException) {
return new CacheException.MalformedURLException(nestedException);
}
public CacheException getRepositoryException(Exception nestedException) {
return new CacheException.RepositoryException(nestedException);
}
public CacheException checkResult(ArchivalUnit au,
LockssUrlConnection connection) {
try {
int code = connection.getResponseCode();
String msg = connection.getResponseMessage();
return mapException(au, connection, code, msg);
}
catch (RuntimeException ex) {
return new CacheException.UnknownExceptionException(ex);
}
}
public CacheException mapException(ArchivalUnit au,
LockssUrlConnection connection,
int responseCode,
String message) {
return mapException(au, getConnUrl(connection),
responseCode, message);
}
public CacheException mapException(ArchivalUnit au,
String url,
int responseCode,
String message) {
Event evt = new ResponseEvent(responseCode, message);
ExceptionInfo ei = exceptionTable.get(responseCode);
if (ei == null) {
if (message != null) {
return new CacheException.UnknownCodeException("Unknown result code: "
+ responseCode + ": "
+ message);
} else {
return new CacheException.UnknownCodeException("Unknown result code: "
+ responseCode);
}
}
CacheException cacheException = ei.getCacheException(au, url, evt);
// Instance of marker class means success
if (cacheException instanceof CacheSuccess) {
return null;
}
return cacheException;
}
public CacheException mapException(ArchivalUnit au,
LockssUrlConnection connection,
Exception fetchException,
String message) {
return mapException(au, getConnUrl(connection),
fetchException, message);
}
public CacheException mapException(ArchivalUnit au,
String url,
Exception fetchException,
String message) {
Event evt = new ExceptionEvent(fetchException, message);
ExceptionInfo ei = findNearestException(fetchException);
if (ei == null) {
if (message != null) {
return
new CacheException.UnknownExceptionException(("Unmapped exception: "
+ fetchException + ": "
+ message),
fetchException);
} else {
return
new CacheException.UnknownExceptionException(("Unmapped exception: "
+ fetchException),
fetchException);
}
}
CacheException cacheException = ei.getCacheException(au, url, evt);
// Instance of marker class means success
if (cacheException instanceof CacheSuccess) {
return null;
}
return cacheException;
}
ExceptionInfo findNearestException(Exception fetchException) {
Class exClass = fetchException.getClass();
ExceptionInfo resultEi;
do {
resultEi = exceptionTable.get(exClass);
} while (resultEi == null
&& ((exClass = exClass.getSuperclass()) != null
&& exClass != Exception.class));
return resultEi;
}
public String toString() {
return "[HRM: " + exceptionTable + "]";
}
}
|
package org.ssgwt.client.ui.form;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import org.ssgwt.client.ui.ImageButton;
import org.ssgwt.client.ui.form.event.ComplexInputFormCancelEvent;
import org.ssgwt.client.ui.form.event.ComplexInputFormConfirmationEvent;
import org.ssgwt.client.ui.form.event.ComplexInputFormRemoveEvent;
import org.ssgwt.client.ui.form.event.ComplexInputFormAddEvent;
import org.ssgwt.client.ui.form.event.ComplexInputFormConfirmationEvent.ComplexInputFormConfirmationHandler;
/**
* Abstract Complex Input is an input field that contains a dynamic form and a
* view ui that is binded and used to display the view state of the field
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*
* @param <T> is the type if data used like a VO
*/
public abstract class ComplexInput<T> extends Composite
implements
HasValue<T>,
InputField<T, T>,
ComplexInputFormRemoveEvent.ComplexInputFormRemoveHasHandlers,
ComplexInputFormAddEvent.ComplexInputFormAddHasHandlers,
ComplexInputFormCancelEvent.ComplexInputFormCancelHasHandlers {
/**
* This is the main panel.
*/
protected FlowPanel mainPanel = new FlowPanel();
/**
* The panel that holds the dynamicForm.
*/
protected FlowPanel dynamicFormPanel = new FlowPanel();
/**
* The panel that holds the view.
*
* The ui binder is added to it
*/
protected FlowPanel viewPanel = new FlowPanel();
/**
* The panel data contains the data of the field.
*
* The view and dynamicForm.
*/
protected FlowPanel dataPanel = new FlowPanel();
/**
* Panel that holds the action buttons
*/
protected FlowPanel actionPanel = new FlowPanel();
/**
* The Panel that holds the view buttons
*/
protected FlowPanel viewButtons = new FlowPanel();
/**
* The Panel that holds the edit buttons
*/
protected FlowPanel editButtons = new FlowPanel();
/**
* The save buttons.
*/
protected ImageButton saveButton = new ImageButton("Done");
/**
* The undo button
*/
protected ImageButton undoButton = new ImageButton("Cancel");
/**
* The add buttons
*/
protected ImageButton addButton = new ImageButton("Add");
/**
* The edit label
*/
protected Label editLabel = new Label("Edit |");
/**
* The remove label
*/
protected Label removeLabel = new Label("Remove");
/**
* The panel that will be used to display either the info message
* or the validation error
*/
private FlowPanel messagePanel;
/**
* The table-panel that will be used to display either the info message
* or the validation error
*/
private FlowPanel messageTable;
/**
* The row-panel that will be used to display either the info message
* or the validation error
*/
private FlowPanel messageRow;
/**
* The cell-label that will hold either the info message or the
* validation error
*/
private Label messageCell;
/**
* Flowpanel to hold the message panel
*/
private FlowPanel messageContainer;
/**
* Injected Object
*/
protected Object injectedObject;
/**
* Class constructor
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*/
public ComplexInput() {
initWidget(mainPanel);
}
/**
* Style to display elements inline
*/
private String displayInlineStyle = "ssGWT-displayInlineBlockMiddel";
/**
* language Input Click Labels style
*/
private String inputClickLabelsStyle = "ssGWT-languageInputClickLabels";
/**
* Save Button style
*/
private String complexSaveButtonStyle = "ssGWT-complexSaveButton";
/**
* Label Button style
*/
private String complexLabelButtonStyle = "ssGWT-complexLabelButton";
/**
* Undo Button style
*/
private String complexUndoButtonStyle = "ssGWT-complexUndoButton";
/**
* Add Button style
*/
private String complexAddButtonStyle = "ssGWT-complexAddButton";
/**
* Gray row styling
*/
private String grayRowStyling = "ssGWT-displayGrayRow";
/**
* Action Container style
*/
private String complexActionContainerStyle = "ssGWT-complexActionContainer";
/**
* Function to construct all the components and add it to the main panel
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*/
public void constructor() {
//create view components
messagePanel = new FlowPanel();
messageTable = new FlowPanel();
messageRow = new FlowPanel();
messageCell = new Label();
messageContainer = new FlowPanel();
messageContainer.add(messagePanel);
messagePanel.setVisible(false);
mainPanel.add(messagePanel);
dynamicFormPanel.add(getDynamicForm());
dynamicFormPanel.addStyleName(displayInlineStyle);
viewPanel.add(getUiBinder());
viewPanel.setStyleName(displayInlineStyle);
viewPanel.setVisible(false);
dataPanel.add(dynamicFormPanel);
dataPanel.add(viewPanel);
dataPanel.setStyleName(displayInlineStyle);
viewButtons.add(editLabel);
editLabel.setStyleName(displayInlineStyle, true);
editLabel.setStyleName(inputClickLabelsStyle, true);
editLabel.setStyleName(complexLabelButtonStyle, true);
viewButtons.add(removeLabel);
removeLabel.setStyleName(displayInlineStyle, true);
removeLabel.setStyleName(inputClickLabelsStyle, true);
removeLabel.setStyleName(complexLabelButtonStyle, true);
viewButtons.setStyleName(displayInlineStyle, true);
editButtons.add(saveButton);
saveButton.addStyleName(complexSaveButtonStyle);
editButtons.add(undoButton);
// undoButton.setStyleName(displayInlineStyle);
undoButton.setStyleName(complexUndoButtonStyle, true);
editButtons.setStyleName(displayInlineStyle);
addButton.setStyleName(complexAddButtonStyle);
actionPanel.add(addButton);
actionPanel.addStyleName(displayInlineStyle);
actionPanel.addStyleName(complexActionContainerStyle);
mainPanel.add(dataPanel);
mainPanel.add(actionPanel);
/**
* Add click handler on editLabel
*/
editLabel.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
setEditState();
mainPanel.removeStyleName(grayRowStyling);
}
});
/**
* Add click handler on removeLabel
*/
removeLabel.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
removeField();
}
});
/**
* Add click handler on addButton
*/
addButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
addField();
}
});
/**
* Add click handler on saveButton
*/
saveButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
saveField();
}
});
/**
* Add click handler on undoButton
*/
undoButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
addUndo();
}
});
}
/**
* This function will be responsible for the canceling of data
*
* @author Ashwin Arendse <ashwin.arendse@a24group.com>
* @since 03 December 2012
*/
public abstract void addUndo();
/**
* Abstract function for the get of the ui view
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*
* @return the ui as a Widget
*/
public abstract Widget getUiBinder();
/**
* Abstract function for the get of the DynamicForm
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*
* @return the DynamicForm
*/
public abstract DynamicForm<T> getDynamicForm();
/**
* Abstract function to set the field in a view state
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*/
public abstract void setViewState();
/**
* Abstract function to set the field in a edit state
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*/
public abstract void setEditState();
/**
* Abstract function to set the field in a add state
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*/
public abstract void setAddState();
/**
* Abstract function that will be called on click of the save button is clicked
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*/
public abstract void saveField();
/**
* Abstract function that will be called on click of the add button is clicked
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*/
public abstract void addField();
/**
* Abstract function that will be called on click of the remove button is clicked
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*/
public abstract void removeField();
/**
* Gets the save button
*
* @return the save button
*/
public ImageButton getSaveButton() {
return saveButton;
}
/**
* If the need arise for the field to have ValueChangeHandler added to it
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*
* @param handler - The Value Change Handler
*/
@Override
public HandlerRegistration addValueChangeHandler(ValueChangeHandler<T> handler) {
return null;
}
/**
* Function that will set a widget in the action container
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*
* @param widget - The widget to set
*/
protected void setActionPanel(Widget widget) {
actionPanel.clear();
actionPanel.add(widget);
}
/**
* Function that will add a widget in the action container
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*
* @param widget - The widget to add
*/
protected void addToActionPanel(Widget widget) {
actionPanel.add(widget);
}
/**
* Function that will remove a widget in the action container
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*
* @param widget - The widget to remove
*/
protected void removeFromActionPanel(Widget widget) {
actionPanel.remove(widget);
}
/**
* Function that will clear the action container
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*/
protected void clearActionPanel() {
actionPanel.clear();
}
/**
* Getter for the view panel
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*
* @return the view panel
*/
protected FlowPanel getViewPanel() {
return this.viewPanel;
}
/**
* Getter for the dynamic panel
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*
* @return the dynamic panel
*/
protected FlowPanel getDynamicFormPanel() {
return this.dynamicFormPanel;
}
/**
* Set the add button to the action container.
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*/
protected void setAddButton() {
setActionPanel(addButton);
}
/**
* Used to set the text for the add button
*
* @param text The text used for the add button
*/
protected void setAddButtonText(String text) {
addButton.setText(text);
}
/**
* Set the view buttons to the action container.
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*/
protected void setViewButtons() {
setActionPanel(viewButtons);
}
/**
* Set the edit button to the action container.
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*/
protected void setEditButtons() {
setActionPanel(editButtons);
}
/**
* A setter for an inject object
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*
* @param object - The object to inject
*/
public void setInjectedObject(Object object) {
this.injectedObject = object;
}
/**
* Return the field as a widget
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 22 November 2012
*
* @return the field as a widget
*/
@Override
public Widget getInputFieldWidget() {
return this.getWidget();
}
/**
* Set the message panel to visible and sets an error message
* on it. Also applies the error style.
*
* @param message String to display as message
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 26 November 2012
*/
public void displayValidationError(String message) {
this.clearMessage();
messageCell.setText(message);
messageCell.setStyleName("messageErrorCell");
messageRow.setStyleName("messageRow");
messageTable.setStyleName("messageTable");
messagePanel.setStyleName("ssGWT-complexMessagePanel");
messageRow.add(messageCell);
messageTable.add(messageRow);
messagePanel.add(messageTable);
messagePanel.setVisible(true);
}
/**
* Set the message panel to visible and sets an info message
* on it. Also applies the info style.
*
* @param message String to display as message
*
* @author Alec Erasmus <alec.erasmus@a24group.com>
* @since 26 November 2012
*/
public void displayInfoMessage(String message) {
this.clearMessage();
messageCell.setText(message);
messageCell.setStyleName("messageInfoCell");
messageRow.setStyleName("messageRow");
messageTable.setStyleName("messageTable");
messagePanel.setStyleName("ssGWT-complexMessagePanel");
messageRow.add(messageCell);
messageTable.add(messageRow);
messagePanel.add(messageTable);
messagePanel.setVisible(true);
}
/**
* Clear the message panel of messages and sets it's
* visibility to false.
*
* @author Ashwin Arendse <ashwin.arendse@a24group.com>
* @since 12 November 2012
*/
public void clearMessage() {
messagePanel.setVisible(false);
messageCell.setText("");
messagePanel.clear();
}
public void addActionPanelStyle(String style) {
actionPanel.addStyleName(style);
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public Class<T> getReturnType() {
return null;
}
/**
* Function force implementation due to class inheritance
*/
@Deprecated
@Override
public boolean isRequired() {
return false;
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public void setRequired(boolean required) {
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public void setReadOnly(boolean readOnly) {
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public boolean isReadOnly() {
return false;
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public void setValue(T value, boolean fireEvents) {
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public void setValue(T object, T value) {
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public T getValue(T object) {
return null;
}
/**
* Sets the style that will be used by the save button
*
* @param complexSaveButtonStyle The style that will be used by the save button
*/
public void setComplexSaveButtonStyle(String complexSaveButtonStyle) {
this.complexSaveButtonStyle = complexSaveButtonStyle;
}
/**
* Sets the style that will be used by the undo button
*
* @param complexUndoButtonStyle The style that will be used by the undo button
*/
public void setComplexUndoButtonStyle(String complexUndoButtonStyle) {
this.complexUndoButtonStyle = complexUndoButtonStyle;
}
/**
* Sets the style that will be used by the add button
*
* @param complexAddButtonStyle The style that will be used by the add button
*/
public void setComplexAddButtonStyle(String complexAddButtonStyle) {
this.complexAddButtonStyle = complexAddButtonStyle;
}
}
|
package dr.evolution.util;
import dr.util.Identifiable;
import dr.app.beauti.options.PartitionTreeModel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
* Class for a list of taxa.
*
* @version $Id: Taxa.java,v 1.29 2006/09/05 13:29:34 rambaut Exp $
*
* @author Alexei Drummond
*/
public class Taxa implements MutableTaxonList, Identifiable, Comparable<Taxa> {
private final ArrayList<MutableTaxonListListener> mutableTaxonListListeners = new ArrayList<MutableTaxonListListener>();
ArrayList<Taxon> taxa = new ArrayList<Taxon>();
private String id = null;
private PartitionTreeModel treeModel;
public Taxa() {
}
public Taxa(String id) {
this.id = id;
}
public Taxa(TaxonList list) {
addTaxa(list);
}
public Taxa(Collection<Taxon> taxa) {
addTaxa(taxa);
}
public Taxa(String id, PartitionTreeModel treeModel) {
this.id = id;
this.treeModel = treeModel;
}
/**
* Adds the given taxon and returns its index. If the taxon is already in the list then it is not
* added but it returns its index.
*
* @param taxon the taxon to be added
*/
public int addTaxon(Taxon taxon) {
int index = getTaxonIndex(taxon);
if (index == -1) {
taxa.add(taxon);
fireTaxonAdded(taxon);
index = taxa.size() - 1;
}
return index;
}
/** Removes a taxon of the given name and returns true if successful. */
public boolean removeTaxon(Taxon taxon) {
boolean success = taxa.remove(taxon);
if (success) {
fireTaxonRemoved(taxon);
}
return success;
}
public void addTaxa(TaxonList taxa) {
for(int nt = 0; nt < taxa.getTaxonCount(); ++nt) {
addTaxon(taxa.getTaxon(nt));
}
}
public void addTaxa(Collection<Taxon> taxa) {
for(Taxon taxon : taxa) {
addTaxon(taxon);
}
}
public void removeTaxa(TaxonList taxa) {
for(int nt = 0; nt < taxa.getTaxonCount(); ++nt) {
removeTaxon(taxa.getTaxon(nt));
}
}
public void removeTaxa(Collection<Taxon> taxa) {
for(Taxon taxon : taxa) {
removeTaxon(taxon);
}
}
public void removeAllTaxa() {
taxa.clear();
fireTaxonRemoved(null);
}
/**
* @return a count of the number of taxa in the list.
*/
public int getTaxonCount() {
return taxa.size();
}
/**
* @return the ith taxon.
*/
public Taxon getTaxon(int taxonIndex) {
return taxa.get(taxonIndex);
}
/**
* @return the ID of the ith taxon.
*/
public String getTaxonId(int taxonIndex) {
return (taxa.get(taxonIndex)).getId();
}
/**
* Sets the unique identifier of the ith taxon.
*/
public void setTaxonId(int taxonIndex, String id) {
(taxa.get(taxonIndex)).setId(id);
fireTaxaChanged();
}
/**
* returns the index of the taxon with the given id.
*/
public int getTaxonIndex(String id) {
for (int i = 0; i < taxa.size(); i++) {
if (getTaxonId(i).equals(id)) return i;
}
return -1;
}
/**
* returns the index of the given taxon.
*/
public int getTaxonIndex(Taxon taxon) {
for (int i = 0; i < taxa.size(); i++) {
if (getTaxon(i) == taxon) return i;
}
return -1;
}
public List<Taxon> asList() {
return new ArrayList<Taxon>(taxa);
}
/**
* returns whether the list contains this taxon
* @param taxon
* @return true if taxon is in the list
*/
public boolean contains(Taxon taxon) {
return taxa.contains(taxon);
}
/**
* Returns true if at least 1 member of taxonList is contained in this Taxa.
* @param taxonList a TaxonList
* @return true if any of taxonList is in this Taxa
*/
public boolean containsAny(TaxonList taxonList) {
for (int i = 0; i < taxonList.getTaxonCount(); i++) {
Taxon taxon = taxonList.getTaxon(i);
if (taxa.contains(taxon)) {
return true;
}
}
return false;
}
/**
* Returns true if at least 1 member of taxonList is contained in this Taxa.
* @param taxa a collection of taxa
* @return true if any of taxa is in this Taxa
*/
public boolean containsAny(Collection<Taxon> taxa) {
for (Taxon taxon : taxa) {
if (taxa.contains(taxon)) {
return true;
}
}
return false;
}
/**
* Returns true if taxonList is a subset of the taxa in this Taxa.
* @param taxonList a TaxonList
* @return true if all of taxonList is in this Taxa
*/
public boolean containsAll(TaxonList taxonList) {
for (int i = 0; i < taxonList.getTaxonCount(); i++) {
Taxon taxon = taxonList.getTaxon(i);
if (!taxa.contains(taxon)) {
return false;
}
}
return true;
}
/**
* Returns true if taxonList is a subset of the taxa in this Taxa.
* @param taxa a collection of taxa
* @return true if all of taxa is in this Taxa
*/
public boolean containsAll(Collection<Taxon> taxa) {
for (Taxon taxon : taxa) {
if (!taxa.contains(taxon)) {
return false;
}
}
return true;
}
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public int compareTo(Taxa o) {
return getId().compareTo(o.getId());
}
public String toString() { return id; }
public Iterator<Taxon> iterator() {
return taxa.iterator();
}
/**
* Sets an named attribute for a given taxon.
* @param taxonIndex the index of the taxon whose attribute is being set.
* @param name the name of the attribute.
* @param value the new value of the attribute.
*/
public void setTaxonAttribute(int taxonIndex, String name, Object value) {
Taxon taxon = getTaxon(taxonIndex);
taxon.setAttribute(name, value);
fireTaxaChanged();
}
/**
* @return an object representing the named attributed for the given taxon.
* @param taxonIndex the index of the taxon whose attribute is being fetched.
* @param name the name of the attribute of interest.
*/
public Object getTaxonAttribute(int taxonIndex, String name) {
Taxon taxon = getTaxon(taxonIndex);
return taxon.getAttribute(name);
}
public void addMutableTaxonListListener(MutableTaxonListListener listener) {
mutableTaxonListListeners.add(listener);
}
private void fireTaxonAdded(Taxon taxon) {
for (MutableTaxonListListener mutableTaxonListListener : mutableTaxonListListeners) {
mutableTaxonListListener.taxonAdded(this, taxon);
}
}
private void fireTaxonRemoved(Taxon taxon) {
for (MutableTaxonListListener mutableTaxonListListener : mutableTaxonListListeners) {
mutableTaxonListListener.taxonRemoved(this, taxon);
}
}
private void fireTaxaChanged() {
for (MutableTaxonListListener mutableTaxonListListener : mutableTaxonListListeners) {
mutableTaxonListListener.taxaChanged(this);
}
}
public PartitionTreeModel getTreeModel() {
return treeModel;
}
public void setTreeModel(PartitionTreeModel treeModel) {
this.treeModel = treeModel;
}
}
|
package eg.ui.menu;
import java.awt.event.KeyEvent;
import java.awt.event.ActionEvent;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
//--Eadgyth--//
import eg.CurrentProject;
import eg.ui.IconFiles;
/**
* The menu for project actions.
* <p> Created in {@link MenuBar}
*/
public class ProjectMenu {
private final JMenu menu = new JMenu("Project");
private final JMenuItem SaveCompile
= new JMenuItem("Save selected source file and compile");
private final JMenuItem SaveAllCompile
= new JMenuItem("Save all source files and compile",
IconFiles.COMPILE_ICON);
private final JMenuItem run = new JMenuItem("Run", IconFiles.RUN_ICON);
private final JMenuItem build = new JMenuItem("Build");
private final JMenuItem newProj = new JMenuItem("Assign project");
private final JMenuItem setProject = new JMenuItem("Project settings");
private final JMenuItem changeProj
= new JMenuItem("Change project", IconFiles.CHANGE_PROJ_ICON);
public ProjectMenu() {
assembleMenu();
shortCuts();
}
public JMenu getMenu() {
return menu;
}
public void setActions(CurrentProject currProj) {
setProject.addActionListener(e -> currProj.openSettingsWindow());
changeProj.addActionListener(e -> currProj.changeProject());
newProj.addActionListener(e -> currProj.createProject());
run.addActionListener(e -> currProj.runProj());
build.addActionListener(e -> currProj.buildProj());
SaveCompile.addActionListener(e -> currProj.saveAndCompile());
SaveAllCompile.addActionListener(e -> currProj.saveAllAndCompile());
}
public void enableChangeProjItm(boolean isEnabled) {
changeProj.setEnabled(isEnabled);
}
public void enableSrcCodeActionItms(boolean isCompile, boolean isRun,
boolean isBuild) {
SaveCompile.setEnabled(isCompile);
SaveAllCompile.setEnabled(isCompile);
run.setEnabled(isRun);
build.setEnabled(isBuild);
}
public void setBuildLabel(String label) {
build.setText(label);
}
//--private--/
private void assembleMenu() {
menu.add(SaveCompile);
menu.add(SaveAllCompile);
menu.add(run);
menu.addSeparator();
menu.add(build);
menu.addSeparator();
menu.add(newProj);
menu.add(setProject);
menu.add(changeProj);
menu.setMnemonic(KeyEvent.VK_P);
changeProj.setEnabled(false);
enableSrcCodeActionItms(false, false, false);
}
private void shortCuts() {
SaveAllCompile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K,
ActionEvent.CTRL_MASK));
run.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R,
ActionEvent.CTRL_MASK));
}
}
|
package enums;
import smartMath.Vec2;
// TODO: tester et ajuster
public enum PathfindingNodes {
COIN_1(new Vec2(700, 1250)), // marche
COIN_2(new Vec2(-700, 1250)),
COIN_3(new Vec2(1000, 1300)),
COIN_4(new Vec2(-1000, 1350)),
COIN_5(new Vec2(1000, 700)),
COIN_6(new Vec2(-1000, 700)),
LONGE_1(new Vec2(0, 1200)), // longe les marches
LONGE_2(new Vec2(900, 1000)),
LONGE_3(new Vec2(-900, 1000)),
SCRIPT_PLOT_1(new Vec2(800, 650)), // plots
SCRIPT_PLOT_2(new Vec2(350, 600)),
SCRIPT_PLOT_3(new Vec2(-800, 650)),
SCRIPT_PLOT_4(new Vec2(-350, 650)),
SCRIPT_PLOT_5(new Vec2(500, 200)),
SCRIPT_PLOT_6(new Vec2(-500, 200)),
SCRIPT_PLOT_7(new Vec2(1000, 250)),
SCRIPT_PLOT_8(new Vec2(-1000, 250)),
SCRIPT_PLOT_9(new Vec2(1000, 1700)),
SCRIPT_PLOT_10(new Vec2(-1000, 1700)),
SCRIPT_VERRE_1(new Vec2(750, 1100)), // verres
SCRIPT_VERRE_2(new Vec2(-750, 1100)),
SCRIPT_TAPIS(new Vec2(250, 1300)), // tapis
SCRIPT_CLAP_1(new Vec2(1200, 300)), // clap
SCRIPT_CLAP_2(new Vec2(-900, 300)),
SCRIPT_CLAP_3(new Vec2(500, 300)),
MILIEU_1(new Vec2(0, 600)), // juste des points au milieu
MILIEU_2(new Vec2(0, 900));
private Vec2 coordonnees;
// Permet surtout de savoir si on n'emprunte jamais certains noeuds...
private int use;
private PathfindingNodes(Vec2 coordonnees)
{
this.coordonnees = coordonnees;
}
public Vec2 getCoordonnees()
{
return coordonnees;
}
public void incrementUse()
{
use++;
}
public int getNbUse()
{
return use;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package erp.mtrn.data;
import cfd.DCfdUtils;
import erp.SBaseXClient;
import erp.SBaseXUtils;
import erp.cfd.SCfdConsts;
import erp.data.SDataConstantsSys;
import erp.lib.SLibConstants;
import erp.lib.SLibUtilities;
import erp.mod.SModConsts;
import erp.mod.trn.db.STrnUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import sa.lib.SLibConsts;
import sa.lib.SLibUtils;
import sa.lib.db.SDbConsts;
import sa.lib.xml.SXmlUtils;
/* IMPORTANT:
* Every single change made to the definition of this class' table must be updated also in the following classes:
* - erp.mod.hrs.db.SDbFormerPayrollImport
* - erp.mtrn.data.SCfdUtils
* All of them execute raw SQL insertions.
*/
public class SDataCfd extends erp.lib.data.SDataRegistry implements java.io.Serializable {
public static final int FIELD_ACC_WS = 1;
public static final int FIELD_ACC_XML_STO = 4;
public static final int FIELD_ACC_PDF_STO = 5;
public static final int FIELD_ACC_USR = 6;
public static final int FIELD_ACK_DVY = 7;
public static final int FIELD_MSJ_DVY = 8;
public static final int FIELD_TP_XML_DVY = 9;
public static final int FIELD_ST_XML_DVY = 10;
public static final int FIELD_USR_DVY = 11;
public static final int FIELD_B_CON = 12;
private final static int DATA_TYPE_TEXT = 1;
private final static int DATA_TYPE_NUMBER = 2;
private final static int DATA_TYPE_DATE = 3;
protected int mnPkCfdId;
protected java.lang.String msSeries;
protected int mnNumber;
protected java.util.Date mtTimestamp;
protected java.lang.String msCertNumber;
protected java.lang.String msStringSigned;
protected java.lang.String msSignature;
protected int mnNodeId_n;
protected java.lang.String msDocXml;
protected java.lang.String msDocXmlName;
protected java.lang.String msDocXmlRfcEmi;
protected java.lang.String msDocXmlRfcRec;
protected double mdDocXmlTot;
protected java.lang.String msDocXmlMon;
protected double mdDocXmlTc;
protected java.util.Date mtDocXmlSign_n;
protected java.lang.String msUuid;
protected byte[] moQrCode_n;
protected java.lang.String msAcknowledgmentCancellationXml;
protected java.sql.Blob moAcknowledgmentCancellationPdf_n;
protected java.lang.String msAcknowledgmentDelivery;
protected java.lang.String msMessageDelivery;
protected boolean mbIsProcessingWebService;
protected boolean mbIsProcessingStorageXml;
protected boolean mbIsProcessingStoragePdf;
protected boolean mbIsConsistent;
protected int mnFkCfdTypeId;
protected int mnFkXmlTypeId;
protected int mnFkXmlStatusId;
protected int mnFkXmlDeliveryTypeId;
protected int mnFkXmlDeliveryStatusId;
protected int mnFkCompanyBranchId_n;
protected int mnFkDpsYearId_n;
protected int mnFkDpsDocId_n;
protected int mnFkRecordYearId_n;
protected int mnFkRecordPeriodId_n;
protected int mnFkRecordBookkeepingCenterId_n;
protected java.lang.String msFkRecordRecordTypeId_n;
protected int mnFkRecordNumberId_n;
protected int mnFkRecordEntryId_n;
protected int mnFkPayrollPayrollId_n;
protected int mnFkPayrollEmployeeId_n;
protected int mnFkPayrollBizPartnerId_n;
protected int mnFkPayrollReceiptPayrollId_n;
protected int mnFkPayrollReceiptEmployeeId_n;
protected int mnFkPayrollReceiptIssueId_n;
protected int mnFkUserProcessingId;
protected int mnFkUserDeliveryId;
protected java.util.Date mtUserProcessingTs;
protected java.util.Date mtUserDeliveryTs;
protected java.lang.String msAuxRfcEmisor;
protected java.lang.String msAuxRfcReceptor;
protected double mdAuxTotalCy;
protected boolean mbAuxIsSign;
protected boolean mbAuxIsProcessingValidation;
protected byte[] mayExtraPrivateDocXml_ns;
public SDataCfd() {
super(SModConsts.TRN_CFD);
reset();
}
private void parseCfdiAttributes(final Connection connection, final String xml) throws java.lang.Exception {
boolean isCfdi = false;
String sql = "";
String xmlSafe = SLibUtils.textToSql(xml);
ResultSet resultSet = null;
msDocXmlRfcEmi = "";
msDocXmlRfcRec = "";
mdDocXmlTot = 0;
msDocXmlMon = "";
mdDocXmlTc = 0;
mtDocXmlSign_n = null;
msUuid = "";
// is CFDI:
sql = "SELECT " +
"erp.f_get_xml_atr('cfdi:Emisor', 'rfc=', '" + xmlSafe + "', " + DATA_TYPE_TEXT + ") AS _xml_emisor_rfc, " +
"erp.f_get_xml_atr('cfdi:Receptor', 'rfc=', '" + xmlSafe + "', " + DATA_TYPE_TEXT + ") AS _xml_receptor_rfc, " +
"erp.f_get_xml_atr('cfdi:Comprobante', 'Total=', '" + xmlSafe + "', " + DATA_TYPE_NUMBER + ") AS _xml_total, " +
"erp.f_get_xml_atr('cfdi:Comprobante', 'TipoCambio=', '" + xmlSafe + "', " + DATA_TYPE_NUMBER + ") AS _xml_tc, " +
"erp.f_get_xml_atr('cfdi:Comprobante', 'Moneda=', '" + xmlSafe + "', " + DATA_TYPE_TEXT + ") AS _xml_moneda, " +
"CAST(REPLACE(erp.f_get_xml_atr('cfdi:Complemento', 'FechaTimbrado=', '" + xmlSafe + "', " + DATA_TYPE_DATE + "), 'T', ' ') AS DATETIME) AS _xml_timbrado, " +
"erp.f_get_xml_atr('cfdi:Complemento', 'UUID=', '" + xmlSafe + "', " + DATA_TYPE_TEXT + ") AS _xml_uuid ";
resultSet = connection.createStatement().executeQuery(sql);
if (resultSet.next()) {
msDocXmlRfcEmi = DCfdUtils.cleanXmlEntities(resultSet.getString("_xml_emisor_rfc"));
msDocXmlRfcRec = DCfdUtils.cleanXmlEntities(resultSet.getString("_xml_receptor_rfc"));
mdDocXmlTot = resultSet.getDouble("_xml_total");
msDocXmlMon = resultSet.getString("_xml_moneda");
mdDocXmlTc = resultSet.getDouble("_xml_tc");
mtDocXmlSign_n = resultSet.getTimestamp("_xml_timbrado");
msUuid = resultSet.getString("_xml_uuid");
isCfdi = !msDocXmlRfcEmi.isEmpty();
}
// is CFD:
if (!isCfdi) {
sql = "SELECT " +
"erp.f_get_xml_atr('Emisor', 'rfc=', '" + xmlSafe + "', " + DATA_TYPE_TEXT + ") AS _xml_emisor_rfc, " +
"erp.f_get_xml_atr('Receptor', 'rfc=', '" + xmlSafe + "', " + DATA_TYPE_TEXT + ") AS _xml_receptor_rfc, " +
"erp.f_get_xml_atr('Comprobante', 'Total=', '" + xmlSafe + "', " + DATA_TYPE_NUMBER + ") AS _xml_total, " +
"erp.f_get_xml_atr('Comprobante', 'TipoCambio=', '" + xmlSafe + "', " + DATA_TYPE_NUMBER + ") AS _xml_tc, " +
"erp.f_get_xml_atr('Comprobante', 'Moneda=', '" + xmlSafe + "', " + DATA_TYPE_TEXT + ") AS _xml_moneda, " +
"NULL AS _xml_timbrado, " +
"'' AS _xml_uuid ";
resultSet = connection.createStatement().executeQuery(sql);
if (resultSet.next()) {
msDocXmlRfcEmi = DCfdUtils.cleanXmlEntities(resultSet.getString("_xml_emisor_rfc"));
msDocXmlRfcRec = DCfdUtils.cleanXmlEntities(resultSet.getString("_xml_receptor_rfc"));
mdDocXmlTot = resultSet.getDouble("_xml_total");
msDocXmlMon = resultSet.getString("_xml_moneda");
mdDocXmlTc = resultSet.getDouble("_xml_tc");
mtDocXmlSign_n = resultSet.getTimestamp("_xml_timbrado");
msUuid = resultSet.getString("_xml_uuid");
}
}
}
public void setPkCfdId(int n) { mnPkCfdId = n; }
public void setSeries(java.lang.String s) { msSeries = s; }
public void setNumber(int n) { mnNumber = n; }
public void setTimestamp(java.util.Date t) { mtTimestamp = t; }
public void setCertNumber(java.lang.String s) { msCertNumber = s; }
public void setStringSigned(java.lang.String s) { msStringSigned = s; }
public void setSignature(java.lang.String s) { msSignature = s; }
public void setNodeId_n(int n) { mnNodeId_n = n; }
public void setDocXml(java.lang.String s) { msDocXml = s; }
public void setDocXmlName(java.lang.String s) { msDocXmlName = s; }
public void setDocXmlRfcEmi(java.lang.String s) { msDocXmlRfcEmi = s; }
public void setDocXmlRfcRec(java.lang.String s) { msDocXmlRfcRec = s; }
public void setDocXmlTot(double d) { mdDocXmlTot = d; }
public void setDocXmlMon(java.lang.String s) { msDocXmlMon = s; }
public void setDocXmlTc(double d) { mdDocXmlTc = d; }
public void setDocXmlSign_n(java.util.Date t) { mtDocXmlSign_n = t; }
public void setUuid(java.lang.String s) { msUuid = s; }
public void setQrCode_n(byte[] o) { moQrCode_n = o; }
public void setAcknowledgmentCancellationXml(java.lang.String s) { msAcknowledgmentCancellationXml = s; }
public void setAcknowledgmentCancellationPdf_n(java.sql.Blob o) { moAcknowledgmentCancellationPdf_n = o; }
public void setAcknowledgmentDelivery(java.lang.String s) { msAcknowledgmentDelivery = s; }
public void setMessageDelivery(java.lang.String s) { msMessageDelivery = s; }
public void setIsProcessingWebService(boolean b) { mbIsProcessingWebService = b; }
public void setIsProcessingStorageXml(boolean b) { mbIsProcessingStorageXml = b; }
public void setIsProcessingStoragePdf(boolean b) { mbIsProcessingStoragePdf = b; }
public void setIsConsistent(boolean b) { mbIsConsistent = b; }
public void setFkCfdTypeId(int n) { mnFkCfdTypeId = n; }
public void setFkXmlTypeId(int n) { mnFkXmlTypeId = n; }
public void setFkXmlStatusId(int n) { mnFkXmlStatusId = n; }
public void setFkXmlDeliveryTypeId(int n) { mnFkXmlDeliveryTypeId = n; }
public void setFkXmlDeliveryStatusId(int n) { mnFkXmlDeliveryStatusId = n; }
public void setFkCompanyBranchId_n(int n) { mnFkCompanyBranchId_n = n; }
public void setFkDpsYearId_n(int n) { mnFkDpsYearId_n = n; }
public void setFkDpsDocId_n(int n) { mnFkDpsDocId_n = n; }
public void setFkRecordYearId_n(int n) { mnFkRecordYearId_n = n; }
public void setFkRecordPeriodId_n(int n) { mnFkRecordPeriodId_n = n; }
public void setFkRecordBookkeepingCenterId_n(int n) { mnFkRecordBookkeepingCenterId_n = n; }
public void setFkRecordRecordTypeId_n(java.lang.String s) { msFkRecordRecordTypeId_n = s; }
public void setFkRecordNumberId_n(int n) { mnFkRecordNumberId_n = n; }
public void setFkRecordEntryId_n(int n) { mnFkRecordEntryId_n = n; }
public void setFkPayrollPayrollId_n(int n) { mnFkPayrollPayrollId_n = n; }
public void setFkPayrollEmployeeId_n(int n) { mnFkPayrollEmployeeId_n = n; }
public void setFkPayrollBizPartnerId_n(int n) { mnFkPayrollBizPartnerId_n = n; }
public void setFkPayrollReceiptPayrollId_n(int n) { mnFkPayrollReceiptPayrollId_n = n; }
public void setFkPayrollReceiptEmployeeId_n(int n) { mnFkPayrollReceiptEmployeeId_n = n; }
public void setFkPayrollReceiptIssueId_n(int n) { mnFkPayrollReceiptIssueId_n = n; }
public void setFkUserProcessingId(int n) { mnFkUserProcessingId = n; }
public void setFkUserDeliveryId(int n) { mnFkUserDeliveryId = n; }
public void setUserProcessingTs(java.util.Date t) { mtUserProcessingTs = t; }
public void setUserDeliveryTs(java.util.Date t) { mtUserDeliveryTs = t; }
public void setAuxRfcEmisor(java.lang.String s) { msAuxRfcEmisor = s; }
public void setAuxRfcReceptor(java.lang.String s) { msAuxRfcReceptor = s; }
public void setAuxTotalCy(double d) { mdAuxTotalCy = d; }
public void setAuxIsSign(boolean b) { mbAuxIsSign = b; }
public void setAuxIsProcessingValidation(boolean b) { mbAuxIsProcessingValidation = b; }
public int getPkCfdId() { return mnPkCfdId; }
public java.lang.String getSeries() { return msSeries; }
public int getNumber() { return mnNumber; }
public java.util.Date getTimestamp() { return mtTimestamp; }
public java.lang.String getCertNumber() { return msCertNumber; }
public java.lang.String getStringSigned() { return msStringSigned; }
public java.lang.String getSignature() { return msSignature; }
public int getNodeId_n() { return mnNodeId_n; }
public java.lang.String getDocXml() { return msDocXml; }
public java.lang.String getDocXmlName() { return msDocXmlName; }
public java.lang.String getDocXmlRfcEmi() { return msDocXmlRfcEmi; }
public java.lang.String getDocXmlRfcRec() { return msDocXmlRfcRec; }
public double getDocXmlTot() { return mdDocXmlTot; }
public java.lang.String getDocXmlMon() { return msDocXmlMon; }
public double getDocXmlTc() { return mdDocXmlTc; }
public java.util.Date getDocXmlSign_n() { return mtDocXmlSign_n; }
public java.lang.String getUuid() { return msUuid; }
public byte[] getQrCode_n() { return moQrCode_n; }
public java.lang.String getAcknowledgmentCancellationXml() { return msAcknowledgmentCancellationXml; }
public java.sql.Blob getAcknowledgmentCancellationPdf_n() { return moAcknowledgmentCancellationPdf_n; }
public java.lang.String getAcknowledgmentDelivery() { return msAcknowledgmentDelivery; }
public java.lang.String getMessageDelivery() { return msMessageDelivery; }
public boolean getIsProcessingWebService() { return mbIsProcessingWebService; }
public boolean getIsProcessingStorageXml() { return mbIsProcessingStorageXml; }
public boolean getIsProcessingStoragePdf() { return mbIsProcessingStoragePdf; }
public boolean getIsConsistent() { return mbIsConsistent; }
public int getFkCfdTypeId() { return mnFkCfdTypeId; }
public int getFkXmlTypeId() { return mnFkXmlTypeId; }
public int getFkXmlStatusId() { return mnFkXmlStatusId; }
public int getFkXmlDeliveryTypeId() { return mnFkXmlDeliveryTypeId; }
public int getFkXmlDeliveryStatusId() { return mnFkXmlDeliveryStatusId; }
public int getFkCompanyBranchId_n() { return mnFkCompanyBranchId_n; }
public int getFkDpsYearId_n() { return mnFkDpsYearId_n; }
public int getFkDpsDocId_n() { return mnFkDpsDocId_n; }
public int getFkRecordYearId_n() { return mnFkRecordYearId_n; }
public int getFkRecordPeriodId_n() { return mnFkRecordPeriodId_n; }
public int getFkRecordBookkeepingCenterId_n() { return mnFkRecordBookkeepingCenterId_n; }
public java.lang.String getFkRecordRecordTypeId_n() { return msFkRecordRecordTypeId_n; }
public int getFkRecordNumberId_n() { return mnFkRecordNumberId_n; }
public int getFkRecordEntryId_n() { return mnFkRecordEntryId_n; }
public int getFkPayrollPayrollId_n() { return mnFkPayrollPayrollId_n; }
public int getFkPayrollEmployeeId_n() { return mnFkPayrollEmployeeId_n; }
public int getFkPayrollBizPartnerId_n() { return mnFkPayrollBizPartnerId_n; }
public int getFkPayrollReceiptPayrollId_n() { return mnFkPayrollReceiptPayrollId_n; }
public int getFkPayrollReceiptEmployeeId_n() { return mnFkPayrollReceiptEmployeeId_n; }
public int getFkPayrollReceiptIssueId_n() { return mnFkPayrollReceiptIssueId_n; }
public int getFkUserProcessingId() { return mnFkUserProcessingId; }
public int getFkUserDeliveryId() { return mnFkUserDeliveryId; }
public java.util.Date getUserProcessingTs() { return mtUserProcessingTs; }
public java.util.Date getUserDeliveryTs() { return mtUserDeliveryTs; }
public java.lang.String getAuxRfcEmisor() { return msAuxRfcEmisor; }
public java.lang.String getAuxRfcReceptor() { return msAuxRfcReceptor; }
public double getAuxTotalCy() { return mdAuxTotalCy; }
public boolean getAuxIsSign() { return mbAuxIsSign; }
public boolean getAuxIsProcessingValidation() { return mbAuxIsProcessingValidation; }
public boolean testDeletion(java.lang.String msg, int action) throws java.lang.Exception {
String sMsg = msg;
if (action == SDbConsts.ACTION_DELETE && isStamped()) {
msDbmsError = sMsg + "¡El comprobante está timbrado!";
throw new Exception(msDbmsError);
}
if (mnFkXmlStatusId == SDataConstantsSys.TRNS_ST_DPS_ANNULED) {
msDbmsError = sMsg + "¡El comprobante está anulado!";
throw new Exception(msDbmsError);
}
if (!mbAuxIsProcessingValidation) {
if (mbIsProcessingWebService) {
msDbmsError = sMsg + "¡" + SCfdConsts.ERR_MSG_PROCESSING_WEB_SERVICE + "!";
throw new Exception(msDbmsError);
}
if (action != SDbConsts.ACTION_ANNUL && mbIsProcessingStorageXml) {
msDbmsError = sMsg + "¡" + SCfdConsts.ERR_MSG_PROCESSING_XML_STORAGE + "!";
throw new Exception(msDbmsError);
}
if (action != SDbConsts.ACTION_ANNUL && mbIsProcessingStoragePdf) {
msDbmsError = sMsg + "¡" + SCfdConsts.ERR_MSG_PROCESSING_PDF_STORAGE + "!";
throw new Exception(msDbmsError);
}
}
return true;
}
/**
* Check if CFD is actually a CFD.
* @return True if CFD is a CFD.
*/
public boolean isCfd() {
return mnFkXmlTypeId == SDataConstantsSys.TRNS_TP_XML_CFD;
}
/**
* Check if CFD is actually a CFDI 3.2 or 3.3.
* @return True if CFD is a CFDI.
*/
public boolean isCfdi() {
return SLibUtils.belongsTo(mnFkXmlTypeId, new int[] { SDataConstantsSys.TRNS_TP_XML_CFDI_32, SDataConstantsSys.TRNS_TP_XML_CFDI_33 });
}
/**
* Check if CFD is stamped, regardless it is an active, annulled or deleted registry.
* If CFD is a CFDI, then it is stamped if it has an UUID.
* If CFD is not a CFDI, then it is stamped if it is not new.
* @return
*/
public boolean isStamped() {
return (isCfdi() && !msUuid.isEmpty()) || (!isCfdi() && mnFkXmlStatusId != SDataConstantsSys.TRNS_ST_DPS_NEW);
}
public String getCfdNumber() {
String cfdNumber = "";
if (mnNumber != SLibConstants.UNDEFINED) {
cfdNumber = STrnUtils.formatDocNumber(msSeries, "" + mnNumber);
}
else {
String numberSer = "";
String number = "";
try {
Document doc = SXmlUtils.parseDocument(msDocXml);
Node node = null;
NamedNodeMap namedNodeMap = null;
node = SXmlUtils.extractElements(doc, mnFkXmlTypeId == SDataConstantsSys.TRNS_TP_XML_CFD ? "Comprobante" : "cfdi:Comprobante").item(0);
namedNodeMap = node.getAttributes();
numberSer = SXmlUtils.extractAttributeValue(namedNodeMap, "serie", false);
number = SXmlUtils.extractAttributeValue(namedNodeMap, "folio", false);
}
catch (Exception e) {
SLibUtilities.printOutException(this, e);
}
cfdNumber = STrnUtils.formatDocNumber(numberSer, number);
}
return cfdNumber;
}
/*
* Implementation of erp.lib.data.SDataRegistry
*/
@Override
public void setPrimaryKey(java.lang.Object pk) {
mnPkCfdId = ((int[]) pk)[0];
}
@Override
public java.lang.Object getPrimaryKey() {
return new int[] { mnPkCfdId };
}
@Override
public void reset() {
super.resetRegistry();
mnPkCfdId = 0;
msSeries = "";
mnNumber = 0;
mtTimestamp = null;
msCertNumber = "";
msStringSigned = "";
msSignature = "";
mnNodeId_n = -1; // means null
msDocXml = "";
msDocXmlName = "";
msDocXmlRfcEmi = "";
msDocXmlRfcRec = "";
mdDocXmlTot = 0;
msDocXmlMon = "";
mdDocXmlTc = 0;
mtDocXmlSign_n = null;
msUuid = "";
moQrCode_n = null;
msAcknowledgmentCancellationXml = "";
moAcknowledgmentCancellationPdf_n = null;
msAcknowledgmentDelivery = "";
msMessageDelivery = "";
mbIsProcessingWebService = false;
mbIsProcessingStorageXml = false;
mbIsProcessingStoragePdf = false;
mbIsConsistent = false;
mnFkCfdTypeId = 0;
mnFkXmlTypeId = 0;
mnFkXmlStatusId = 0;
mnFkXmlDeliveryTypeId = 0;
mnFkXmlDeliveryStatusId = 0;
mnFkCompanyBranchId_n = 0;
mnFkDpsYearId_n = 0;
mnFkDpsDocId_n = 0;
mnFkRecordYearId_n = 0;
mnFkRecordPeriodId_n = 0;
mnFkRecordBookkeepingCenterId_n = 0;
msFkRecordRecordTypeId_n = "";
mnFkRecordNumberId_n = 0;
mnFkRecordEntryId_n = 0;
mnFkPayrollPayrollId_n = 0;
mnFkPayrollEmployeeId_n = 0;
mnFkPayrollBizPartnerId_n = 0;
mnFkPayrollReceiptPayrollId_n = 0;
mnFkPayrollReceiptEmployeeId_n = 0;
mnFkPayrollReceiptIssueId_n = 0;
mnFkUserProcessingId = 0;
mnFkUserDeliveryId = 0;
mtUserProcessingTs = null;
mtUserDeliveryTs = null;
msAuxRfcEmisor = "";
msAuxRfcReceptor = "";
mdAuxTotalCy = 0;
mbAuxIsSign = false;
mbAuxIsProcessingValidation = false;
mayExtraPrivateDocXml_ns = null;
}
@Override
public int read(java.lang.Object pk, java.sql.Statement statement) {
int[] key = (int[]) pk;
String sql = "";
ResultSet resultSet = null;
mnLastDbActionResult = SLibConstants.UNDEFINED;
reset();
try {
sql = "SELECT * FROM trn_cfd WHERE id_cfd = " + key[0] + " ";
resultSet = statement.executeQuery(sql);
if (!resultSet.next()) {
throw new Exception(SLibConstants.MSG_ERR_REG_FOUND_NOT);
}
else {
mnPkCfdId = resultSet.getInt("id_cfd");
msSeries = resultSet.getString("ser");
mnNumber = resultSet.getInt("num");
mtTimestamp = resultSet.getTimestamp("ts");
msCertNumber = resultSet.getString("cert_num");
msStringSigned = resultSet.getString("str_signed");
msSignature = resultSet.getString("signature");
mnNodeId_n = resultSet.getInt("node_id_n");
if (resultSet.wasNull()) {
mnNodeId_n = -1; // means null
}
/*
msDocXml = db:open-id("TreeBD", resultSet.getString("doc_xml"))
*/
String mysqlDatabaseURL = statement.getConnection().getMetaData().getURL();
String databaseHost = SBaseXUtils.getDbHostFromUrl(mysqlDatabaseURL);
String databaseName = SBaseXUtils.getDbNameFromUrl(mysqlDatabaseURL);
// Company BaseX database connection
SBaseXClient baseXSession = SBaseXUtils.getBaseXSessionInstance(databaseHost, 1984, "admin", "admin");
String getDocumentByNodeID = "db:open-id(\""+ databaseName +"\"," + resultSet.getString("node_id_n") + " )";
String xmlDocument = SBaseXUtils.executeBaseXQuery(baseXSession, getDocumentByNodeID).get(0);
msDocXml = xmlDocument;
msDocXml = resultSet.getString("doc_xml");
msDocXmlName = resultSet.getString("doc_xml_name");
msDocXmlRfcEmi = resultSet.getString("xml_rfc_emi");
msDocXmlRfcRec = resultSet.getString("xml_rfc_rec");
mdDocXmlTot = resultSet.getDouble("xml_tot");
msDocXmlMon = resultSet.getString("xml_mon");
mdDocXmlTc = resultSet.getDouble("xml_tc");
mtDocXmlSign_n = resultSet.getTimestamp("xml_sign_n");
msUuid = resultSet.getString("uuid");
//moQrCode_n = resultSet.getBlob("qrc_n"); it's cannot read a object blob (2014-03-10, jbarajas)
msAcknowledgmentCancellationXml = resultSet.getString("ack_can_xml");
//moAcknowledgmentCancellationPdf_n = resultSet.getBlob("ack_can_pdf_n"); it's cannot read a object blob (2014-09-01, jbarajas)
msAcknowledgmentDelivery = resultSet.getString("ack_dvy");
msMessageDelivery = resultSet.getString("msg_dvy");
mbIsProcessingWebService = resultSet.getBoolean("b_prc_ws");
mbIsProcessingStorageXml = resultSet.getBoolean("b_prc_sto_xml");
mbIsProcessingStoragePdf = resultSet.getBoolean("b_prc_sto_pdf");
mbIsConsistent = resultSet.getBoolean("b_con");
mnFkCfdTypeId = resultSet.getInt("fid_tp_cfd");
mnFkXmlTypeId = resultSet.getInt("fid_tp_xml");
mnFkXmlStatusId = resultSet.getInt("fid_st_xml");
mnFkXmlDeliveryTypeId = resultSet.getInt("fid_tp_xml_dvy");
mnFkXmlDeliveryStatusId = resultSet.getInt("fid_st_xml_dvy");
mnFkCompanyBranchId_n = resultSet.getInt("fid_cob_n");
mnFkDpsYearId_n = resultSet.getInt("fid_dps_year_n");
mnFkDpsDocId_n = resultSet.getInt("fid_dps_doc_n");
mnFkRecordYearId_n = resultSet.getInt("fid_rec_year_n");
mnFkRecordPeriodId_n = resultSet.getInt("fid_rec_per_n");
mnFkRecordBookkeepingCenterId_n = resultSet.getInt("fid_rec_bkc_n");
msFkRecordRecordTypeId_n = resultSet.getString("fid_rec_tp_rec_n");
mnFkRecordNumberId_n = resultSet.getInt("fid_rec_num_n");
mnFkRecordEntryId_n = resultSet.getInt("fid_rec_ety_n");
mnFkPayrollPayrollId_n = resultSet.getInt("fid_pay_pay_n");
mnFkPayrollEmployeeId_n = resultSet.getInt("fid_pay_emp_n");
mnFkPayrollBizPartnerId_n = resultSet.getInt("fid_pay_bpr_n");
mnFkPayrollReceiptPayrollId_n = resultSet.getInt("fid_pay_rcp_pay_n");
mnFkPayrollReceiptEmployeeId_n = resultSet.getInt("fid_pay_rcp_emp_n");
mnFkPayrollReceiptIssueId_n = resultSet.getInt("fid_pay_rcp_iss_n");
mnFkUserProcessingId = resultSet.getInt("fid_usr_prc");
mnFkUserDeliveryId = resultSet.getInt("fid_usr_dvy");
mtUserProcessingTs = resultSet.getTimestamp("ts_prc");
mtUserDeliveryTs = resultSet.getTimestamp("ts_dvy");
mbIsRegistryNew = false;
mnLastDbActionResult = SLibConstants.DB_ACTION_READ_OK;
}
}
catch (java.lang.Exception e) {
mnLastDbActionResult = SLibConstants.DB_ACTION_READ_ERROR;
if (msDbmsError.isEmpty()) {
msDbmsError = SLibConstants.MSG_ERR_DB_REG_READ;
}
msDbmsError += "\n" + e.toString();
SLibUtilities.printOutException(this, e);
}
return mnLastDbActionResult;
}
@Override
public int save(java.sql.Connection connection) {
int index = 1;
final int LENGTH_CURRENCY = 15;
boolean bIsUpd = false;
String sql = "";
ResultSet resultSet = null;
Statement statement = null;
PreparedStatement preparedStatement = null;
mnLastDbActionResult = SLibConstants.UNDEFINED;
try {
statement = connection.createStatement();
if (mnPkCfdId == SLibConsts.UNDEFINED) {
// obtain new ID for CFD:
sql = "SELECT COALESCE(MAX(id_cfd), 0) + 1 FROM trn_cfd ";
resultSet = statement.executeQuery(sql);
if (!resultSet.next()) {
throw new Exception(SDbConsts.ERR_MSG_REG_NOT_FOUND);
}
else {
mnPkCfdId = resultSet.getInt(1);
}
if (!msSeries.isEmpty() && mnNumber == 0) {
// obtain new Number for actual Series of CFD, only CFD with own number series will be numbered:
sql = "SELECT COALESCE(MAX(num), 0) + 1 FROM trn_cfd WHERE ser = '" + msSeries + "' ";
resultSet = statement.executeQuery(sql);
if (!resultSet.next()) {
throw new Exception(SDbConsts.ERR_MSG_REG_NOT_FOUND);
}
else {
mnNumber = resultSet.getInt(1);
}
}
sql = "INSERT INTO trn_cfd (id_cfd, ser, num, " +
"ts, cert_num, str_signed, signature, node_id_n, doc_xml, doc_xml_name, xml_rfc_emi, xml_rfc_rec, xml_tot, xml_mon, " +
"xml_tc, xml_sign_n, uuid, qrc_n, ack_can_xml, ack_can_pdf_n, ack_dvy, msg_dvy, b_prc_ws, b_prc_sto_xml, " +
"b_prc_sto_pdf, b_con, fid_tp_cfd, fid_tp_xml, fid_st_xml, fid_tp_xml_dvy, fid_st_xml_dvy, fid_cob_n, fid_dps_year_n, fid_dps_doc_n, " +
"fid_rec_year_n, fid_rec_per_n, fid_rec_bkc_n, fid_rec_tp_rec_n, fid_rec_num_n, fid_rec_ety_n, fid_pay_pay_n, fid_pay_emp_n, fid_pay_bpr_n, fid_pay_rcp_pay_n, fid_pay_rcp_emp_n, " +
"fid_pay_rcp_iss_n, fid_usr_prc, fid_usr_dvy, ts_prc, ts_dvy) " +
"VALUES (" + mnPkCfdId + ", ?, ?, " +
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
"?, ?, ?, NOW(), NOW())";
}
else {
bIsUpd = true;
sql = "UPDATE trn_cfd SET ser = ?, num = ?, ts = ?, cert_num = ?, str_signed = ?, signature = ?, node_id_n = ?, " +
"doc_xml = ?, doc_xml_name = ?, xml_rfc_emi = ?, xml_rfc_rec = ?, xml_tot = ?, xml_mon = ?, xml_tc = ?, xml_sign_n = ?, " +
"uuid = ?, qrc_n = ?, ack_can_xml = ?, ack_dvy = ?, msg_dvy = ?, b_con = ?, " +
"fid_tp_cfd = ?, fid_tp_xml = ?, fid_st_xml = ?, fid_tp_xml_dvy = ?, fid_st_xml_dvy = ?, fid_cob_n = ?, " +
"fid_dps_year_n = ?, fid_dps_doc_n = ?, fid_rec_year_n = ?, fid_rec_per_n = ?, fid_rec_bkc_n = ?, fid_rec_tp_rec_n = ?, fid_rec_num_n = ?, fid_rec_ety_n = ?, " +
"fid_pay_pay_n = ?, fid_pay_emp_n = ?, fid_pay_bpr_n = ?, fid_pay_rcp_pay_n = ?, fid_pay_rcp_emp_n = ?, fid_pay_rcp_iss_n = ?, fid_usr_dvy = ?, ts_dvy = NOW() " +
"WHERE id_cfd = " + mnPkCfdId + " ";
}
parseCfdiAttributes(connection, msDocXml);
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(index++, msSeries);
preparedStatement.setInt(index++, mnNumber);
preparedStatement.setTimestamp(index++, new java.sql.Timestamp(mtTimestamp.getTime()));
preparedStatement.setString(index++, msCertNumber);
preparedStatement.setString(index++, msStringSigned);
preparedStatement.setString(index++, msSignature);
if (mnNodeId_n == -1) {
preparedStatement.setNull(index++, java.sql.Types.INTEGER);
}
else {
preparedStatement.setInt(index++, mnNodeId_n);
}
String mysqlDatabaseURL = connection.getMetaData().getURL();
String databaseHost = SBaseXUtils.getDbHostFromUrl(mysqlDatabaseURL);
String databaseName = SBaseXUtils.getDbNameFromUrl(mysqlDatabaseURL);
// Company BaseX database connection
SBaseXClient baseXSession = SBaseXUtils.getBaseXSessionInstance(databaseHost, 1984, "admin", "admin");
// escape XML special characters.
String xmlDocBody = SBaseXUtils.escapeSpecialCharacters(msDocXml);
// Parse the xml body and add it to the BaseX database.
String addXmlToDBQuery = "db:add(\"" + databaseName + "\", fn:parse-xml(\"" + xmlDocBody + "\"), \"" + msDocXmlName + "\")";
SBaseXUtils.executeBaseXQuery(baseXSession, addXmlToDBQuery);
// Obtain the last inserted document of the BaseX database and return its node-id
String getLastDBEntryQuery
= "let $last := collection(\"" + databaseName + "\")[last()]\n"
+ "return db:node-id($last)";
ArrayList<String> queryResult = SBaseXUtils.executeBaseXQuery(baseXSession, getLastDBEntryQuery);
// Insert the document node-id and add it to the MySQL database as reference.
String updateNodeId_nQuery = "UPDATE trn_cfd SET node_id_n = " + queryResult.get(0) + " WHERE id_cfd = " + mnPkCfdId + ";";
connection.createStatement().executeUpdate(updateNodeId_nQuery);
preparedStatement.setString(index++, SLibUtils.textToSql(msDocXml));
preparedStatement.setString(index++, SLibUtils.textToSql(msDocXmlName));
preparedStatement.setString(index++, msDocXmlRfcEmi);
preparedStatement.setString(index++, msDocXmlRfcRec);
preparedStatement.setDouble(index++, mdDocXmlTot);
if (msDocXmlMon.length() >= LENGTH_CURRENCY) {
preparedStatement.setString(index++, msDocXmlMon.substring(0, LENGTH_CURRENCY - 1)); //Valid value size
}
else {
preparedStatement.setString(index++, msDocXmlMon);
}
preparedStatement.setDouble(index++, mdDocXmlTc);
if (mtDocXmlSign_n == null) {
preparedStatement.setNull(index++, java.sql.Types.DATE);
}
else {
preparedStatement.setTimestamp(index++, new java.sql.Timestamp(mtDocXmlSign_n.getTime()));
}
preparedStatement.setString(index++, msUuid);
preparedStatement.setNull(index++, java.sql.Types.BLOB); // NOTE: 2018-05-16, Sergio Flores: QR code will not be saved anymore, it was never useful!
preparedStatement.setString(index++, msAcknowledgmentCancellationXml);
if (!bIsUpd) {
preparedStatement.setNull(index++, java.sql.Types.BLOB); // it's cannot updated a object blob (2014-09-01, jbarajas)
}
preparedStatement.setString(index++, msAcknowledgmentDelivery);
preparedStatement.setString(index++, msMessageDelivery);
if (!bIsUpd) {
preparedStatement.setBoolean(index++, mbIsProcessingWebService);
preparedStatement.setBoolean(index++, mbIsProcessingStorageXml);
preparedStatement.setBoolean(index++, mbIsProcessingStoragePdf);
}
preparedStatement.setBoolean(index++, mbIsConsistent);
preparedStatement.setInt(index++, mnFkCfdTypeId);
preparedStatement.setInt(index++, mnFkXmlTypeId);
preparedStatement.setInt(index++, mnFkXmlStatusId);
preparedStatement.setInt(index++, mnFkXmlDeliveryTypeId);
preparedStatement.setInt(index++, mnFkXmlDeliveryStatusId);
if (mnFkCompanyBranchId_n == SLibConsts.UNDEFINED) {
preparedStatement.setNull(index++, java.sql.Types.INTEGER);
}
else {
preparedStatement.setInt(index++, mnFkCompanyBranchId_n);
}
if (mnFkDpsYearId_n == SLibConsts.UNDEFINED) {
preparedStatement.setNull(index++, java.sql.Types.SMALLINT);
preparedStatement.setNull(index++, java.sql.Types.INTEGER);
}
else {
preparedStatement.setInt(index++, mnFkDpsYearId_n);
preparedStatement.setInt(index++, mnFkDpsDocId_n);
}
if (mnFkRecordYearId_n == SLibConsts.UNDEFINED) {
preparedStatement.setNull(index++, java.sql.Types.SMALLINT);
preparedStatement.setNull(index++, java.sql.Types.SMALLINT);
preparedStatement.setNull(index++, java.sql.Types.SMALLINT);
preparedStatement.setNull(index++, java.sql.Types.CHAR);
preparedStatement.setNull(index++, java.sql.Types.INTEGER);
preparedStatement.setNull(index++, java.sql.Types.INTEGER);
}
else {
preparedStatement.setInt(index++, mnFkRecordYearId_n);
preparedStatement.setInt(index++, mnFkRecordPeriodId_n);
preparedStatement.setInt(index++, mnFkRecordBookkeepingCenterId_n);
preparedStatement.setString(index++, msFkRecordRecordTypeId_n);
preparedStatement.setInt(index++, mnFkRecordNumberId_n);
preparedStatement.setInt(index++, mnFkRecordEntryId_n);
}
if (mnFkPayrollPayrollId_n == SLibConsts.UNDEFINED) {
preparedStatement.setNull(index++, java.sql.Types.SMALLINT);
preparedStatement.setNull(index++, java.sql.Types.SMALLINT);
preparedStatement.setNull(index++, java.sql.Types.INTEGER);
}
else {
preparedStatement.setInt(index++, mnFkPayrollPayrollId_n);
preparedStatement.setInt(index++, mnFkPayrollEmployeeId_n);
preparedStatement.setInt(index++, mnFkPayrollBizPartnerId_n);
}
if (mnFkPayrollReceiptPayrollId_n == SLibConsts.UNDEFINED) {
preparedStatement.setNull(index++, java.sql.Types.SMALLINT);
preparedStatement.setNull(index++, java.sql.Types.SMALLINT);
preparedStatement.setNull(index++, java.sql.Types.SMALLINT);
}
else {
preparedStatement.setInt(index++, mnFkPayrollReceiptPayrollId_n);
preparedStatement.setInt(index++, mnFkPayrollReceiptEmployeeId_n);
preparedStatement.setInt(index++, mnFkPayrollReceiptIssueId_n);
}
if (!bIsUpd) {
preparedStatement.setInt(index++, mnFkUserProcessingId);
}
preparedStatement.setInt(index++, mnFkUserDeliveryId);
preparedStatement.execute();
mnDbmsErrorId = 0;
msDbmsError = "";
mbIsRegistryNew = false;
mnLastDbActionResult = SLibConstants.DB_ACTION_SAVE_OK;
}
catch (java.lang.Exception e) {
mnLastDbActionResult = SLibConstants.DB_ACTION_SAVE_ERROR;
if (msDbmsError.isEmpty()) {
msDbmsError = SLibConstants.MSG_ERR_DB_REG_SAVE;
}
msDbmsError += "\n" + e.toString();
SLibUtilities.printOutException(this, e);
}
return mnLastDbActionResult;
}
@Override
public java.util.Date getLastDbUpdate() {
return null;
}
@Override
public int canSave(java.sql.Connection connection) {
if (!mbAuxIsSign) {
mnLastDbActionResult = super.canSave(connection);
}
else {
mnLastDbActionResult = SLibConstants.UNDEFINED;
try {
if (testDeletion("No se puede timbrar el comprobante: ", SDbConsts.ACTION_DELETE)) {
mnLastDbActionResult = SLibConstants.DB_CAN_SAVE_YES;
}
}
catch (Exception e) {
mnLastDbActionResult = SLibConstants.DB_CAN_SAVE_NO;
if (msDbmsError.isEmpty()) {
msDbmsError = SLibConstants.MSG_ERR_DB_REG_CAN_SAVE;
}
msDbmsError += "\n" + e.toString();
SLibUtilities.printOutException(this, e);
}
}
return mnLastDbActionResult;
}
@Override
public int canAnnul(java.sql.Connection connection) {
mnLastDbActionResult = SLibConstants.UNDEFINED;
try {
if (testDeletion("No se puede anular el comprobante: ", SDbConsts.ACTION_ANNUL)) {
mnLastDbActionResult = SLibConstants.DB_CAN_ANNUL_YES;
}
}
catch (Exception e) {
mnLastDbActionResult = SLibConstants.DB_CAN_ANNUL_NO;
if (msDbmsError.isEmpty()) {
msDbmsError = SLibConstants.MSG_ERR_DB_REG_CAN_ANNUL;
}
msDbmsError += "\n" + e.toString();
SLibUtilities.printOutException(this, e);
}
return mnLastDbActionResult;
}
@Override
public int annul(java.sql.Connection connection) {
String sSql = "";
Statement oStatement = null;
mnLastDbActionResult = SLibConstants.UNDEFINED;
try {
oStatement = connection.createStatement();
// Set CFD as annuled:
if (testDeletion("No se puede anular el comprobante: ", SDbConsts.ACTION_ANNUL)) {
sSql = "UPDATE trn_cfd SET fid_st_xml = " + SDataConstantsSys.TRNS_ST_DPS_ANNULED + " " +
"WHERE id_cfd = " + mnPkCfdId + " ";
oStatement.execute(sSql);
mnLastDbActionResult = SLibConstants.DB_ACTION_ANNUL_OK;
}
}
catch (Exception e) {
mnLastDbActionResult = SLibConstants.DB_ACTION_ANNUL_ERROR;
if (msDbmsError.isEmpty()) {
msDbmsError = SLibConstants.MSG_ERR_DB_REG_ANNUL;
}
msDbmsError += "\n" + e.toString();
SLibUtilities.printOutException(this, e);
}
return mnLastDbActionResult;
}
/**
* Updates some field of status of this CFD.
* @param connection Database connection.
* @param field Field or status of this CFD to be updated. Available options defined in this class by constants named FIELD_...
* @param value Updated value.
* @throws Exception
*/
public void saveField(java.sql.Connection connection, final int field, final Object value) throws Exception {
String sSql = "";
mnLastDbActionResult = SLibConstants.UNDEFINED;
sSql = "UPDATE trn_cfd SET ";
switch (field) {
case FIELD_ACC_WS:
sSql += "b_prc_ws = " + value + " ";
break;
case FIELD_ACC_XML_STO:
sSql += "b_prc_sto_xml = " + value + " ";
break;
case FIELD_ACC_PDF_STO:
sSql += "b_prc_sto_pdf = " + value + " ";
break;
case FIELD_ACC_USR:
sSql += "fid_usr_prc = " + value + ", ts_prc = NOW() ";
break;
case FIELD_ACK_DVY:
sSql += "ack_dvy = '" + value + "' ";
break;
case FIELD_MSJ_DVY:
sSql += "msg_dvy = '" + value + "' ";
break;
case FIELD_TP_XML_DVY:
sSql += "fid_tp_xml_dvy = " + value + " ";
break;
case FIELD_ST_XML_DVY:
sSql += "fid_st_xml_dvy = " + value + " ";
break;
case FIELD_USR_DVY:
sSql += "fid_usr_dvy = " + value + ", ts_dvy = NOW() ";
break;
case FIELD_B_CON:
sSql += "b_con = " + value + " ";
break;
default:
throw new Exception(SLibConsts.ERR_MSG_OPTION_UNKNOWN);
}
sSql += "WHERE id_cfd = " + mnPkCfdId + ";";
connection.createStatement().execute(sSql);
mnLastDbActionResult = SLibConstants.DB_ACTION_SAVE_OK;
}
}
|
public class ExampleDocument {
// surveyaccess s = new surveyaccess();
// private String _id = s.eename;
public String _id ="";
public String EmployeeName="";
public String Banda="";
public String EmployeeID="";
public String Service_Line="";
public String Bluepages_Manager_Name="";
public String Service_Area="";
public String Primary_Job_Role="";
public String Test_script_creation ="";
public String Test_data_creation="";
public String Execute_test_scripts="";
public String Write_defects="";
public String Effectively_communicate="";
public String Use_of_HP_Application_Lifecycle_Management_ALM="";
public String Use_of_Rational_ClearCase_and_ClearQuest="";
public String Use_of_Rational_Collaborative_Life_cycle_Management_clm_product="";
public String Use_of_Rational_Doors= null;
public String Use_of_Rational_Manual_Tester= null;
public String Use_of_Rational_Quality_Manager= null;
public String Use_of_Rational_Requirements_Composer= null;
public String Use_of_Rational_RequisitePro= null;
public String Use_of_Rational_Software_Architect_Design_Manager= null;
public String Use_of_Rational_Team_Concert= null;
public String Use_Rational_TestManager= null;
public String Continuos_Integration_Continuous_Testing= null;
public String Test_driven_development_TDD_Behavior_driven_development_BDD= null;
public String Test_Architect_Technical_Leadership= null;
public String Create_test_plan= null;
public String Create_test_data_plan= null;
public String Create_test_schedule= null;
public String Review_and_track_test_team_schedule_progress= null;
public String Resource_onboarding = null;
public String Create_and_present_test_status_and_reports_to_key_stakeholders = null;
public String Prepare_Analyze_test_metrics = null;
public String Perform_defect_management = null;
private String _rev = null;
public ExampleDocument(String name, String eID, String Band, String sl, String BM, String SA, String PJR, String ts,String td,String ET, String WD, String Ec, String useofhp, String useofrational, String useofrationalcol, String rationald, String urmt,String urqm, String urrc, String uorp,String uoras, String uortc, String uortest, String Continuos_Integration, String tdd,String taa, String ctp,String ctdp,String ctts, String rattsp, String rss, String cprss,String pstm,String perd) {
_id=eID;
System.out.println(_id);
EmployeeName=name;
EmployeeID=eID;
Banda=Band;
Service_Line=sl;
Bluepages_Manager_Name=BM;
Service_Area=SA;
Primary_Job_Role=PJR;
Test_script_creation=ts;
Test_data_creation=td;
Execute_test_scripts=ET;
Write_defects=WD;
Effectively_communicate =Ec;
Use_of_HP_Application_Lifecycle_Management_ALM=useofhp;
Use_of_Rational_ClearCase_and_ClearQuest=useofrational;
Use_of_Rational_Collaborative_Life_cycle_Management_clm_product=useofrationalcol;
Use_of_Rational_Doors=rationald;
Use_of_Rational_Manual_Tester=urmt;
Use_of_Rational_Quality_Manager=urqm;
Use_of_Rational_Requirements_Composer= urrc;
Use_of_Rational_RequisitePro=uorp;
Use_of_Rational_Software_Architect_Design_Manager=uoras;
Use_of_Rational_Team_Concert=uortc;
Use_Rational_TestManager=uortest;
Continuos_Integration_Continuous_Testing=Continuos_Integration;
Test_driven_development_TDD_Behavior_driven_development_BDD=tdd;
Test_Architect_Technical_Leadership=taa;
Create_test_plan=ctp;
Create_test_data_plan=ctdp;
Create_test_schedule=ctts;
Review_and_track_test_team_schedule_progress=rattsp;
Resource_onboarding=rss;
Create_and_present_test_status_and_reports_to_key_stakeholders=cprss;
Prepare_Analyze_test_metrics=pstm;
Perform_defect_management=perd;
if(eID==""){
_id=""+Math.random();
}
}
public String toString() {
return "{ id: " + _id + ",\nrev: " + "EmployeeName: " + EmployeeName + " EmployeeID: " + EmployeeID +"Band: " + Banda + " Service Line: " +Service_Line + "Bluepages Manager Name: " + Bluepages_Manager_Name+ "Service Area"+ Service_Area+"Primary Job Role: "+Primary_Job_Role +"Test script creation: " + Test_script_creation + "Testdatacreation: " +Test_data_creation +"Execute Test Scripts" +Execute_test_scripts+ "Write defects: " +Write_defects+ "Effectively communicate to stakeholders/client: "+Effectively_communicate + _rev + "Use of HP Application Lifecycle" + Use_of_HP_Application_Lifecycle_Management_ALM+ "Use of Rational ClearCase: "+Use_of_Rational_ClearCase_and_ClearQuest+ "Use_of_Rational_Collaborative_Life_cycle_Management"+Use_of_Rational_Collaborative_Life_cycle_Management_clm_product + Use_of_Rational_Doors+ Use_of_Rational_Manual_Tester+ Use_of_Rational_Quality_Manager +Use_of_Rational_Requirements_Composer+Use_of_Rational_RequisitePro+Use_of_Rational_Software_Architect_Design_Manager +Use_of_Rational_Team_Concert+Use_Rational_TestManager +
Continuos_Integration_Continuous_Testing+ Test_driven_development_TDD_Behavior_driven_development_BDD + Test_Architect_Technical_Leadership+ Create_test_plan+Create_test_data_plan+ Review_and_track_test_team_schedule_progress +Resource_onboarding+Prepare_Analyze_test_metrics+"\n}";
}
}
|
package cliente;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import javax.swing.JOptionPane;
import com.google.gson.Gson;
import comandos.ComandosCliente;
import frames.MenuCarga;
import frames.MenuComerciar;
import frames.MenuJugar;
import frames.MenuMapas;
import juego.Juego;
import mensajeria.Comando;
import mensajeria.Paquete;
import mensajeria.PaqueteComerciar;
import mensajeria.PaquetePersonaje;
import mensajeria.PaqueteUsuario;
public class Cliente extends Thread {
private Socket cliente;
private String miIp;
private ObjectInputStream entrada;
private ObjectOutputStream salida;
// Objeto gson
private final Gson gson = new Gson();
// Paquete usuario y paquete personaje
private PaqueteUsuario paqueteUsuario;
private PaquetePersonaje paquetePersonaje;
private PaqueteComerciar paqueteComercio;
// Acciones que realiza el usuario
private int accion;
//MENU COMERCIAR
private MenuComerciar m1;
// Ip y puerto
private String ip;
private final int puerto = 9999;
/**Pide la accion
* @return Devuelve la accion
*/
public int getAccion() {
return accion;
}
/**Setea la accion
* @param accion accion a setear
*/
public void setAccion(final int accion) {
this.accion = accion;
}
private Juego wome;
private MenuCarga menuCarga;
/**Constructor del Cliente
*/
public Cliente() {
ip = JOptionPane.showInputDialog("Ingrese IP del servidor: (default localhost)");
if(ip == null) {
ip = "localhost";
}
try {
cliente = new Socket(ip, puerto);
miIp = cliente.getInetAddress().getHostAddress();
entrada = new ObjectInputStream(cliente.getInputStream());
salida = new ObjectOutputStream(cliente.getOutputStream());
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Fallo al iniciar la aplicación. "
+ "Revise la conexión con el servidor.");
System.exit(1);
e.printStackTrace();
}
}
public Cliente(String ip, int puerto) {
try {
cliente = new Socket(ip, puerto);
miIp = cliente.getInetAddress().getHostAddress();
entrada = new ObjectInputStream(cliente.getInputStream());
salida = new ObjectOutputStream(cliente.getOutputStream());
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Fallo al iniciar la aplicación. "
+ "Revise la conexión con el servidor.");
System.exit(1);
e.printStackTrace();
}
}
@Override
public void run() {
synchronized(this) {
try {
ComandosCliente comand;
// Creo el paquete que le voy a enviar al servidor
paqueteUsuario = new PaqueteUsuario();
MenuJugar menuJugar = null;
while (!paqueteUsuario.isInicioSesion()) {
if(menuJugar == null){
menuJugar = new MenuJugar(this);
menuJugar.setVisible(true);
// Creo los paquetes que le voy a enviar al servidor
paqueteUsuario = new PaqueteUsuario();
paquetePersonaje = new PaquetePersonaje();
// Espero a que el usuario seleccione alguna accion
wait();
comand = (ComandosCliente) Paquete.getObjetoSet(Comando.NOMBREPAQUETE, getAccion());
comand.setCadena(null);
comand.setCliente(this);
comand.ejecutar();
// Le envio el paquete al servidor
salida.writeObject(gson.toJson(paqueteUsuario));
}
// Recibo el paquete desde el servidor
String cadenaLeida = (String) entrada.readObject();
Paquete paquete = gson.fromJson(cadenaLeida, Paquete.class);
comand = (ComandosCliente) paquete.getObjeto(Comando.NOMBREPAQUETE);
comand.setCadena(cadenaLeida);
comand.setCliente(this);
comand.ejecutar();
}
// Creo un paquete con el comando mostrar mapas
paquetePersonaje.setComando(Comando.MOSTRARMAPAS);
// Abro el menu de eleccion del mapa
MenuMapas menuElegirMapa = new MenuMapas(this);
menuElegirMapa.setVisible(true);
// Espero a que el usuario elija el mapa
wait();
//Si clickeo en la Cruz al Seleccionar mapas
if (paquetePersonaje.getMapa() == 0) {
paquetePersonaje.setComando(Comando.DESCONECTAR);
salida.writeObject(gson.toJson(paquetePersonaje));
} else {
// Establezco el mapa en el paquete personaje
paquetePersonaje.setIp(miIp);
// Le envio el paquete con el mapa seleccionado
salida.writeObject(gson.toJson(paquetePersonaje));
// Instancio el juego y cargo los recursos
wome = new Juego("World Of the Middle Earth", 800, 600, this, paquetePersonaje);
// Muestro el menu de carga
menuCarga = new MenuCarga(this);
menuCarga.setVisible(true);
// Espero que se carguen todos los recursos
wait();
// Inicio el juego
wome.start();
// Finalizo el menu de carga
menuCarga.dispose();
}
} catch (IOException | InterruptedException | ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, "Fallo la conexión con el servidor durante el inicio de sesión.");
System.exit(1);
e.printStackTrace();
}
}
}
/**Pide el cliente
* @return Devuelve el cliente
*/
public Socket getSocket() {
return cliente;
}
/**Setea el cliente
* @param cliente cliente a setear
*/
public void setSocket(final Socket cliente) {
this.cliente = cliente;
}
/**Pide la ip
* @return Devuelve la ip
*/
public String getMiIp() {
return miIp;
}
/**Setea la ip
* @param miIp ip a setear
*/
public void setMiIp(final String miIp) {
this.miIp = miIp;
}
/**Pide la entrada
* @return Devuelve la entrada
*/
public ObjectInputStream getEntrada() {
return entrada;
}
/**Setea la entrada
* @param entrada entrada a setear
*/
public void setEntrada(final ObjectInputStream entrada) {
this.entrada = entrada;
}
/**Pide la salida
* @return Devuelve la salida
*/
public ObjectOutputStream getSalida() {
return salida;
}
/**Setea la salida
* @param salida salida a setear
*/
public void setSalida(final ObjectOutputStream salida) {
this.salida = salida;
}
/**Pide el paquete usuario
* @return Devuelve el paquete usuario
*/
public PaqueteUsuario getPaqueteUsuario() {
return paqueteUsuario;
}
/**Pide el paquete personaje
* @return Devuelve el paquete personaje
*/
public PaquetePersonaje getPaquetePersonaje() {
return paquetePersonaje;
}
/**Pide el juego
* @return Devuelve el juego
*/
public Juego getJuego() {
return wome;
}
/**Pide el menu de carga
* @return Devuelve el menu de carga
*/
public MenuCarga getMenuCarga() {
return menuCarga;
}
public void actualizarItems(PaquetePersonaje paqueteActualizado) {
if(paquetePersonaje.getCantItems() != 0 && paquetePersonaje.getCantItems() != paqueteActualizado.getCantItems()) {
paquetePersonaje.anadirItem(paqueteActualizado.getItems().get(paqueteActualizado.getItems().size() -1));
}
}
public String getIp() {
return ip;
}
public void actualizarPersonaje(PaquetePersonaje pP) {
paquetePersonaje = pP;
}
public Juego getWome() {
return wome;
}
public void setWome(Juego wome) {
this.wome = wome;
}
public int getPuerto() {
return puerto;
}
public void setPaqueteUsuario(PaqueteUsuario paqueteUsuario) {
this.paqueteUsuario = paqueteUsuario;
}
public void setPaquetePersonaje(PaquetePersonaje paquetePersonaje) {
this.paquetePersonaje = paquetePersonaje;
}
public void setIp(String ip) {
this.ip = ip;
}
public void setMenuCarga(MenuCarga menuCarga) {
this.menuCarga = menuCarga;
}
public MenuComerciar getM1() {
return m1;
}
public void setM1(MenuComerciar m1) {
this.m1 = m1;
}
public PaqueteComerciar getPaqueteComercio() {
return paqueteComercio;
}
public void setPaqueteComercio(PaqueteComerciar paqueteComercio) {
this.paqueteComercio = paqueteComercio;
}
}
|
package ezvcard;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import javax.xml.transform.TransformerException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import ezvcard.io.HCardPage;
import ezvcard.io.HCardReader;
import ezvcard.io.IParser;
import ezvcard.io.VCardReader;
import ezvcard.io.VCardWriter;
import ezvcard.io.XCardDocument;
import ezvcard.io.XCardReader;
import ezvcard.types.VCardType;
import ezvcard.util.IOUtils;
import freemarker.template.TemplateException;
/**
* <p>
* Contains helper methods for parsing/writing vCards. The methods wrap the
* following classes:
* </p>
*
*
* <table border="1">
* <tr>
* <th></th>
* <th>Reading</th>
* <th>Writing</th>
* </tr>
* <tr>
* <th>Plain text</th>
* <td>{@link VCardReader}</td>
* <td>{@link VCardWriter}</td>
* </tr>
* <tr>
* <th>XML</th>
* <td>{@link XCardReader}</td>
* <td>{@link XCardDocument}</td>
* </tr>
* <tr>
* <th>HTML</th>
* <td>{@link HCardReader}</td>
* <td>{@link HCardPage}</td>
* </tr>
* </table>
* @author Michael Angstadt
*/
public class Ezvcard {
/**
* The version of the library.
*/
public static final String VERSION;
/**
* The project webpage.
*/
public static final String URL;
static {
InputStream in = null;
try {
in = Ezvcard.class.getResourceAsStream("/ez-vcard-info.properties");
Properties props = new Properties();
props.load(in);
VERSION = props.getProperty("version");
URL = props.getProperty("url");
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(in);
}
}
public static ParserChainTextString parse(String str) {
return new ParserChainTextString(str);
}
public static ParserChainTextReader parse(File file) throws FileNotFoundException {
return parse(new FileReader(file));
}
public static ParserChainTextReader parse(InputStream in) {
return parse(new InputStreamReader(in));
}
public static ParserChainTextReader parse(Reader reader) {
return new ParserChainTextReader(reader);
}
public static ParserChainXmlString parseXml(String xml) {
return new ParserChainXmlString(xml);
}
public static ParserChainXmlReader parseXml(File file) throws FileNotFoundException {
return parseXml(new FileReader(file));
}
public static ParserChainXmlReader parseXml(InputStream in) {
return parseXml(new InputStreamReader(in));
}
public static ParserChainXmlReader parseXml(Reader reader) {
return new ParserChainXmlReader(reader);
}
public static ParserChainXmlDom parseXml(Document document) {
return new ParserChainXmlDom(document);
}
public static ParserChainHtmlString parseHtml(String html) {
return new ParserChainHtmlString(html);
}
public static ParserChainHtmlReader parseHtml(File file) throws FileNotFoundException {
return parseHtml(new FileReader(file));
}
public static ParserChainHtmlReader parseHtml(InputStream in) {
return parseHtml(new InputStreamReader(in));
}
public static ParserChainHtmlReader parseHtml(Reader reader) {
return new ParserChainHtmlReader(reader);
}
public static ParserChainHtmlReader parseHtml(URL url) {
return new ParserChainHtmlReader(url);
}
public static WriterChainTextSingle write(VCard vcard) {
return new WriterChainTextSingle(vcard);
}
public static WriterChainTextMulti write(VCard... vcards) {
return write(Arrays.asList(vcards));
}
public static WriterChainTextMulti write(Collection<VCard> vcards) {
return new WriterChainTextMulti(vcards);
}
public static WriterChainXmlSingle writeXml(VCard vcard) {
return new WriterChainXmlSingle(vcard);
}
public static WriterChainXmlMulti writeXml(VCard... vcards) {
return writeXml(Arrays.asList(vcards));
}
public static WriterChainXmlMulti writeXml(Collection<VCard> vcards) {
return new WriterChainXmlMulti(vcards);
}
public static WriterChainHtml writeHtml(VCard... vcards) {
return writeHtml(Arrays.asList(vcards));
}
public static WriterChainHtml writeHtml(Collection<VCard> vcards) {
return new WriterChainHtml(vcards);
}
static abstract class ParserChain<T, U extends IParser> {
T childThis;
final List<Class<? extends VCardType>> extendedTypes = new ArrayList<Class<? extends VCardType>>();
List<List<String>> warnings;
/**
* Registers an extended type class.
* @param typeClass the extended type class
* @return this
*/
public T register(Class<? extends VCardType> typeClass) {
extendedTypes.add(typeClass);
return childThis;
}
/**
* Provides a list object that any unmarshal warnings will be put into.
* @param warnings the list object that will be populated with the
* warnings of each unmarshalled vCard. Each element of the list is the
* list of warnings for one of the unmarshalled vCards. Therefore, the
* size of this list will be equal to the number of parsed vCards. If a
* vCard does not have any warnings, then its warning list will be
* empty.
* @return this
*/
public T warnings(List<List<String>> warnings) {
this.warnings = warnings;
return childThis;
}
/**
* Creates the parser.
* @return the parser object
*/
abstract U init() throws IOException, SAXException;
U ready() throws IOException, SAXException {
U parser = init();
for (Class<? extends VCardType> extendedType : extendedTypes) {
parser.registerExtendedType(extendedType);
}
return parser;
}
/**
* Reads the first vCard from the stream.
* @return the vCard or null if there are no vCards
* @throws IOException if there's an I/O problem
* @throws SAXException if there's a problem parsing the XML
*/
public VCard first() throws IOException, SAXException {
IParser parser = ready();
VCard vcard = parser.readNext();
if (warnings != null) {
warnings.add(parser.getWarnings());
}
return vcard;
}
/**
* Reads all vCards from the stream.
* @return the parsed vCards
* @throws IOException if there's an I/O problem
* @throws SAXException if there's a problem parsing the XML
*/
public List<VCard> all() throws IOException, SAXException {
IParser parser = ready();
List<VCard> vcards = new ArrayList<VCard>();
VCard vcard;
while ((vcard = parser.readNext()) != null) {
if (warnings != null) {
warnings.add(parser.getWarnings());
}
vcards.add(vcard);
}
return vcards;
}
}
/**
* Convenience chainer class for parsing plain text vCards.
*/
static abstract class ParserChainText<T> extends ParserChain<T, VCardReader> {
boolean caretDecoding = true;
public T caretDecoding(boolean enable) {
caretDecoding = enable;
return childThis;
}
@Override
VCardReader ready() throws IOException, SAXException {
VCardReader parser = super.ready();
parser.setCaretDecodingEnabled(caretDecoding);
return parser;
}
@Override
public VCard first() throws IOException {
try {
return super.first();
} catch (SAXException e) {
//not parsing XML
}
return null;
}
@Override
public List<VCard> all() throws IOException {
try {
return super.all();
} catch (SAXException e) {
//not parsing XML
}
return null;
}
}
/**
* Convenience chainer class for parsing plain text vCards.
*/
public static class ParserChainTextReader extends ParserChainText<ParserChainTextReader> {
private Reader reader;
private ParserChainTextReader(Reader reader) {
super.childThis = this;
this.reader = reader;
}
@Override
public ParserChainTextReader register(Class<? extends VCardType> typeClass) {
return super.register(typeClass);
}
@Override
public ParserChainTextReader warnings(List<List<String>> warnings) {
return super.warnings(warnings);
}
@Override
public ParserChainTextReader caretDecoding(boolean enable) {
return super.caretDecoding(enable);
}
@Override
VCardReader init() {
return new VCardReader(reader);
}
}
/**
* Convenience chainer class for parsing plain text vCards.
*/
public static class ParserChainTextString extends ParserChainText<ParserChainTextString> {
private String text;
private ParserChainTextString(String text) {
super.childThis = this;
this.text = text;
}
@Override
public ParserChainTextString register(Class<? extends VCardType> typeClass) {
return super.register(typeClass);
}
@Override
public ParserChainTextString warnings(List<List<String>> warnings) {
return super.warnings(warnings);
}
@Override
public ParserChainTextString caretDecoding(boolean enable) {
return super.caretDecoding(enable);
}
@Override
VCardReader init() {
return new VCardReader(text);
}
@Override
public VCard first() {
try {
return super.first();
} catch (IOException e) {
//reading from string
}
return null;
}
@Override
public List<VCard> all() {
try {
return super.all();
} catch (IOException e) {
//reading from string
}
return null;
}
}
/**
* Convenience chainer class for parsing XML vCards.
*/
static abstract class ParserChainXml<T> extends ParserChain<T, XCardReader> {
//nothing
}
/**
* Convenience chainer class for parsing XML vCards.
*/
public static class ParserChainXmlReader extends ParserChainXml<ParserChainXmlReader> {
private Reader reader;
private ParserChainXmlReader(Reader reader) {
super.childThis = this;
this.reader = reader;
}
@Override
XCardReader init() throws IOException, SAXException {
return new XCardReader(reader);
}
}
/**
* Convenience chainer class for parsing XML vCards.
*/
public static class ParserChainXmlString extends ParserChainXml<ParserChainXmlString> {
private String xml;
private ParserChainXmlString(String xml) {
super.childThis = this;
this.xml = xml;
}
@Override
XCardReader init() throws SAXException {
return new XCardReader(xml);
}
@Override
public VCard first() throws SAXException {
try {
return super.first();
} catch (IOException e) {
//reading from string
}
return null;
}
@Override
public List<VCard> all() throws SAXException {
try {
return super.all();
} catch (IOException e) {
//reading from string
}
return null;
}
}
/**
* Convenience chainer class for parsing XML vCards.
*/
public static class ParserChainXmlDom extends ParserChainXml<ParserChainXmlDom> {
private Document document;
private ParserChainXmlDom(Document document) {
super.childThis = this;
this.document = document;
}
@Override
XCardReader init() {
return new XCardReader(document);
}
@Override
public VCard first() {
try {
return super.first();
} catch (IOException e) {
//reading from DOM
} catch (SAXException e) {
//reading from DOM
}
return null;
}
@Override
public List<VCard> all() {
try {
return super.all();
} catch (IOException e) {
//reading from DOM
} catch (SAXException e) {
//reading from DOM
}
return null;
}
}
/**
* Convenience chainer class for parsing HTML vCards.
*/
static abstract class ParserChainHtml<T> extends ParserChain<T, HCardReader> {
String pageUrl;
/**
* Sets the original URL of the webpage. This is used to resolve
* relative links and to set the SOURCE property on the vCard. Setting
* this property has no effect if reading from a {@link URL}.
* @param pageUrl the webpage URL
* @return this
*/
public T pageUrl(String pageUrl) {
this.pageUrl = pageUrl;
return childThis;
}
@Override
public VCard first() throws IOException {
try {
return super.first();
} catch (SAXException e) {
//not parsing XML
}
return null;
}
@Override
public List<VCard> all() throws IOException {
try {
return super.all();
} catch (SAXException e) {
//not parsing XML
}
return null;
}
}
/**
* Convenience chainer class for parsing HTML vCards.
*/
public static class ParserChainHtmlReader extends ParserChainHtml<ParserChainHtmlReader> {
private Reader reader;
private URL url;
private ParserChainHtmlReader(Reader reader) {
this.childThis = this;
this.reader = reader;
}
private ParserChainHtmlReader(URL url) {
this.url = url;
}
@Override
public ParserChainHtmlReader pageUrl(String pageUrl) {
return super.pageUrl(pageUrl);
}
@Override
HCardReader init() throws IOException {
return (url == null) ? new HCardReader(reader, pageUrl) : new HCardReader(url);
}
}
/**
* Convenience chainer class for parsing HTML vCards.
*/
public static class ParserChainHtmlString extends ParserChainHtml<ParserChainHtmlString> {
private String html;
private ParserChainHtmlString(String html) {
this.childThis = this;
this.html = html;
}
@Override
HCardReader init() {
return new HCardReader(html, pageUrl);
}
@Override
public ParserChainHtmlString pageUrl(String pageUrl) {
return super.pageUrl(pageUrl);
}
@Override
public VCard first() {
try {
return super.first();
} catch (IOException e) {
//reading from string
}
return null;
}
@Override
public List<VCard> all() {
try {
return super.all();
} catch (IOException e) {
//reading from string
}
return null;
}
}
static abstract class WriterChain {
final Collection<VCard> vcards;
WriterChain(Collection<VCard> vcards) {
this.vcards = vcards;
}
}
static abstract class WriterChainText<T> extends WriterChain {
T childThis;
VCardVersion version;
boolean prodId = true;
boolean caretEncoding = false;
WriterChainText(Collection<VCard> vcards) {
super(vcards);
}
/**
* <p>
* Sets the version that all the vCards will be marshalled to. The
* version that is attached to each individual {@link VCard} object will
* be ignored.
* </p>
* <p>
* If no version is passed into this method, the writer will look at the
* version attached to each individual {@link VCard} object and marshal
* it to that version. And if a {@link VCard} object has no version
* attached to it, then it will be marshalled to version 3.0.
* </p>
* @param version the version to marshal the vCards to
* @return this
*/
public T version(VCardVersion version) {
this.version = version;
return childThis;
}
/**
* Sets whether or not to add a PRODID type to each vCard, saying that
* the vCard was generated by this library. For 2.1 vCards, the extended
* type X-PRODID is used, since PRODID is not supported by that version.
* @param include true to add PRODID (default), false not to
* @return this
*/
public T prodId(boolean include) {
this.prodId = include;
return childThis;
}
public T caretEncoding(boolean enable) {
this.caretEncoding = enable;
return childThis;
}
/**
* Writes the vCards to a string.
* @return the vCard string
*/
public String go() {
StringWriter sw = new StringWriter();
try {
go(sw);
} catch (IOException e) {
//writing to a string
}
return sw.toString();
}
/**
* Writes the vCards to an output stream.
* @param out the output stream to write to
* @throws IOException if there's a problem writing to the output stream
*/
public void go(OutputStream out) throws IOException {
go(new OutputStreamWriter(out));
}
/**
* Writes the vCards to a file.
* @param file the file to write to
* @throws IOException if there's a problem writing to the file
*/
public void go(File file) throws IOException {
FileWriter writer = null;
try {
writer = new FileWriter(file);
go(writer);
} finally {
IOUtils.closeQuietly(writer);
}
}
/**
* Writes the vCards to a writer.
* @param writer the writer to write to
* @throws IOException if there's a problem writing to the writer
*/
public void go(Writer writer) throws IOException {
VCardWriter vcardWriter = new VCardWriter(writer);
if (version != null) {
vcardWriter.setTargetVersion(version);
}
vcardWriter.setAddProdId(prodId);
vcardWriter.setCaretEncodingEnabled(caretEncoding);
for (VCard vcard : vcards) {
if (version == null) {
VCardVersion vcardVersion = vcard.getVersion();
vcardWriter.setTargetVersion((vcardVersion == null) ? VCardVersion.V3_0 : vcardVersion);
}
vcardWriter.write(vcard);
addWarnings(vcardWriter.getWarnings());
}
}
abstract void addWarnings(List<String> warnings);
}
/**
* Convenience chainer class for writing plain text vCards
*/
public static class WriterChainTextMulti extends WriterChainText<WriterChainTextMulti> {
private List<List<String>> warnings;
private WriterChainTextMulti(Collection<VCard> vcards) {
super(vcards);
super.childThis = this;
}
@Override
public WriterChainTextMulti version(VCardVersion version) {
return super.version(version);
}
@Override
public WriterChainTextMulti prodId(boolean include) {
return super.prodId(include);
}
@Override
public WriterChainTextMulti caretEncoding(boolean enable) {
return super.caretEncoding(enable);
}
/**
* Provides a list object that any marshal warnings will be put into.
* Warnings usually occur when there is a property in the VCard that is
* not supported by the version to which the vCard is being marshalled.
* @param warnings the list object that will be populated with the
* warnings of each marshalled vCard. Each element of the list is the
* list of warnings for one of the marshalled vCards. Therefore, the
* size of this list will be equal to the number of parsed vCards. If a
* vCard does not have any warnings, then its warning list will be
* empty.
* @return this
*/
public WriterChainTextMulti warnings(List<List<String>> warnings) {
this.warnings = warnings;
return this;
}
@Override
void addWarnings(List<String> warnings) {
if (this.warnings != null) {
this.warnings.add(warnings);
}
}
}
/**
* Convenience chainer class for writing plain text vCards
*/
public static class WriterChainTextSingle extends WriterChainText<WriterChainTextSingle> {
private List<String> warnings;
private WriterChainTextSingle(VCard vcard) {
super(Arrays.asList(vcard));
super.childThis = this;
}
@Override
public WriterChainTextSingle version(VCardVersion version) {
return super.version(version);
}
@Override
public WriterChainTextSingle prodId(boolean include) {
return super.prodId(include);
}
@Override
public WriterChainTextSingle caretEncoding(boolean enable) {
return super.caretEncoding(enable);
}
/**
* Provides a list object that any marshal warnings will be put into.
* Warnings usually occur when there is a property in the VCard that is
* not supported by the version to which the vCard is being marshalled.
* @param warnings the list object that will be populated with the
* warnings of the marshalled vCard.
* @return this
*/
public WriterChainTextSingle warnings(List<String> warnings) {
this.warnings = warnings;
return this;
}
@Override
void addWarnings(List<String> warnings) {
if (this.warnings != null) {
this.warnings.addAll(warnings);
}
}
}
static abstract class WriterChainXml<T> extends WriterChain {
T childThis;
boolean prodId = true;
int indent = -1;
WriterChainXml(Collection<VCard> vcards) {
super(vcards);
}
/**
* Sets whether or not to add a PRODID type to each vCard, saying that
* the vCard was generated by this library.
* @param include true to add PRODID (default), false not to
* @return this
*/
public T prodId(boolean include) {
this.prodId = include;
return childThis;
}
/**
* Sets the number of indent spaces to use for pretty-printing. If not
* set, then the XML will not be pretty-printed.
* @param indent the number of spaces in the indent string
* @return this
*/
public T indent(int indent) {
this.indent = indent;
return childThis;
}
/**
* Writes the xCards to a string.
* @return the XML document
*/
public String go() {
StringWriter sw = new StringWriter();
try {
go(sw);
} catch (TransformerException e) {
//writing to a string
}
return sw.toString();
}
/**
* Writes the xCards to an output stream.
* @param out the output stream to write to
* @throws TransformerException if there's a problem writing to the
* output stream
*/
public void go(OutputStream out) throws TransformerException {
go(new OutputStreamWriter(out));
}
/**
* Writes the xCards to a file.
* @param file the file to write to
* @throws IOException if the file can't be opened
* @throws TransformerException if there's a problem writing to the file
*/
public void go(File file) throws IOException, TransformerException {
FileWriter writer = null;
try {
writer = new FileWriter(file);
go(writer);
} finally {
IOUtils.closeQuietly(writer);
}
}
/**
* Writes the xCards to a writer.
* @param writer the writer to write to
* @throws TransformerException if there's a problem writing to the
* writer
*/
public void go(Writer writer) throws TransformerException {
XCardDocument doc = createXCardDocument();
doc.write(writer, indent);
}
/**
* Generates an XML document object model (DOM) containing the xCards.
* @return the DOM
*/
public Document dom() {
XCardDocument doc = createXCardDocument();
return doc.getDocument();
}
private XCardDocument createXCardDocument() {
XCardDocument doc = new XCardDocument();
doc.setAddProdId(prodId);
for (VCard vcard : vcards) {
doc.addVCard(vcard);
addWarnings(doc.getWarnings());
}
return doc;
}
abstract void addWarnings(List<String> warnings);
}
/**
* Convenience chainer class for writing XML vCards (xCard).
*/
public static class WriterChainXmlMulti extends WriterChainXml<WriterChainXmlMulti> {
private List<List<String>> warnings;
private WriterChainXmlMulti(Collection<VCard> vcards) {
super(vcards);
super.childThis = this;
}
@Override
public WriterChainXmlMulti prodId(boolean include) {
return super.prodId(include);
}
@Override
public WriterChainXmlMulti indent(int indent) {
return super.indent(indent);
}
/**
* Provides a list object that any marshal warnings will be put into.
* Warnings usually occur when there is a property in the VCard that is
* not supported by the version to which the vCard is being marshalled.
* @param warnings the list object that will be populated with the
* warnings of each marshalled vCard. Each element of the list is the
* list of warnings for one of the marshalled vCards. Therefore, the
* size of this list will be equal to the number of parsed vCards. If a
* vCard does not have any warnings, then its warning list will be
* empty.
* @return this
*/
public WriterChainXmlMulti warnings(List<List<String>> warnings) {
this.warnings = warnings;
return this;
}
@Override
void addWarnings(List<String> warnings) {
if (this.warnings != null) {
this.warnings.add(warnings);
}
}
}
/**
* Convenience chainer class for writing XML vCards (xCard).
*/
public static class WriterChainXmlSingle extends WriterChainXml<WriterChainXmlSingle> {
private List<String> warnings;
private WriterChainXmlSingle(VCard vcard) {
super(Arrays.asList(vcard));
super.childThis = this;
}
@Override
public WriterChainXmlSingle prodId(boolean include) {
return super.prodId(include);
}
@Override
public WriterChainXmlSingle indent(int indent) {
return super.indent(indent);
}
/**
* Provides a list object that any marshal warnings will be put into.
* Warnings usually occur when there is a property in the VCard that is
* not supported by the version to which the vCard is being marshalled.
* @param warnings the list object that will be populated with the
* warnings of each marshalled vCard.
* @return this
*/
public WriterChainXmlSingle warnings(List<String> warnings) {
this.warnings = warnings;
return this;
}
@Override
void addWarnings(List<String> warnings) {
if (this.warnings != null) {
this.warnings.addAll(warnings);
}
}
}
/**
* Convenience chainer class for writing HTML vCards (hCard).
*/
public static class WriterChainHtml extends WriterChain {
private WriterChainHtml(Collection<VCard> vcards) {
super(vcards);
}
/**
* Writes the hCards to a string.
* @return the HTML page
* @throws TemplateException if there's a problem with the freemarker
* template
*/
public String go() throws TemplateException {
StringWriter sw = new StringWriter();
try {
go(sw);
} catch (IOException e) {
//writing string
}
return sw.toString();
}
/**
* Writes the hCards to an output stream.
* @param out the output stream to write to
* @throws IOException if there's a problem writing to the output stream
* @throws TemplateException if there's a problem with the freemarker
* template
*/
public void go(OutputStream out) throws IOException, TemplateException {
go(new OutputStreamWriter(out));
}
/**
* Writes the hCards to a file.
* @param file the file to write to
* @throws IOException if there's a problem writing to the file
* @throws TemplateException if there's a problem with the freemarker
* template
*/
public void go(File file) throws IOException, TemplateException {
FileWriter writer = null;
try {
writer = new FileWriter(file);
go(writer);
} finally {
IOUtils.closeQuietly(writer);
}
}
/**
* Writes the hCards to a writer.
* @param writer the writer to write to
* @throws IOException if there's a problem writing to the writer
* @throws TemplateException if there's a problem with the freemarker
* template
*/
public void go(Writer writer) throws IOException, TemplateException {
HCardPage page = new HCardPage();
for (VCard vcard : vcards) {
page.addVCard(vcard);
}
page.write(writer);
}
}
private Ezvcard() {
//hide
}
}
|
package main.java.gameboi.cpu;
import main.java.gameboi.memory.GBMem;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
/**
* Z80 Gameboy CPU
*
* Implementation of a gameboy cpu. Eight registers (a,b,c,d,e,f,h,l), a
* stack pointer, program counter, and timers
*
* @author tomis007
*/
public class CPU {
// registers, stack pointer, program counter
private final GBRegisters registers;
private int sp;
private int pc;
private static final GBRegisters.Reg A = GBRegisters.Reg.A;
private static final GBRegisters.Reg B = GBRegisters.Reg.B;
private static final GBRegisters.Reg C = GBRegisters.Reg.C;
private static final GBRegisters.Reg D = GBRegisters.Reg.D;
private static final GBRegisters.Reg E = GBRegisters.Reg.E;
private static final GBRegisters.Reg F = GBRegisters.Reg.F;
private static final GBRegisters.Reg H = GBRegisters.Reg.H;
private static final GBRegisters.Reg L = GBRegisters.Reg.L;
private static final GBRegisters.Reg HL = GBRegisters.Reg.HL;
private static final GBRegisters.Reg BC = GBRegisters.Reg.BC;
private static final GBRegisters.Reg DE = GBRegisters.Reg.DE;
private static final GBRegisters.Reg AF = GBRegisters.Reg.AF;
//flag bitnum constants
private static final int ZERO_F = 7;
private static final int SUBTRACT_F = 6;
private static final int HALFCARRY_F = 5;
private static final int CARRY_F = 4;
//memory
private final GBMem memory;
//cpu clocks
private static final int clockSpeed = 4194304;
private int timerCounter;
private int divideCounter;
//stop, halt
private boolean isStopped;
private boolean executionHalted;
/**
* Interrupt state of cpu
* Represents the Interrupt Master Enable Flag
* allows for correct transition timing
*/
private enum InterruptCpuState {
DISABLED, DELAY_ON, DELAY_OFF, ENABLED
}
private InterruptCpuState interruptState;
private static final InterruptCpuState DISABLED = InterruptCpuState.DISABLED;
private static final InterruptCpuState DELAY_ON = InterruptCpuState.DELAY_ON;
private static final InterruptCpuState DELAY_OFF = InterruptCpuState.DELAY_OFF;
private static final InterruptCpuState ENABLED = InterruptCpuState.ENABLED;
private static final int BYTE_SAVE_LENGTH = 17;
/**
* Constructor for gameboy z80 CPU
*
* @param memory GBMem object to associate with this cpu
*/
public CPU(GBMem memory) {
pc = 0x100;
sp = 0xfffe;
this.memory = memory;
registers = new GBRegisters();
timerCounter = getCountFrequency();
divideCounter = 16384; //TODO
interruptState = DISABLED;
executionHalted = false; //TODO ADD TO SAVING
}
/**
* save the current cpu state into byte[]
* this can be written to file and loaded
* with loadState()
*
* @return byte array to write
*/
public byte[] saveState() {
byte[] buf = new byte[BYTE_SAVE_LENGTH];
buf[0] = (byte)registers.getReg(A);
buf[1] = (byte)registers.getReg(B);
buf[2] = (byte)registers.getReg(C);
buf[3] = (byte)registers.getReg(D);
buf[4] = (byte)registers.getReg(E);
buf[5] = (byte)registers.getReg(F);
buf[6] = (byte)registers.getReg(H);
buf[7] = (byte)registers.getReg(L);
buf[8] = (byte)(sp & 0xff);
buf[9] = (byte)((sp & 0xff00) >> 8);
buf[10] = (byte)(pc & 0xff);
buf[11] = (byte)((pc & 0xff00) >> 8);
buf[12] = (byte)(timerCounter & 0xff);
buf[13] = (byte)((timerCounter & 0xff00) >> 8);
buf[14] = (byte)(divideCounter & 0xff);
buf[15] = (byte)((divideCounter & 0xff00) >> 8);
buf[16] = interruptStateToByte();
dumpRegisters(0x0);
return buf;
}
/**
*
* Returns current interrupt state as a byte for saving
* @return byte representing current interrupt state
*/
private byte interruptStateToByte() {
switch(interruptState) {
case ENABLED:
return 0;
case DELAY_OFF:
return 1;
case DELAY_ON:
return 2;
case DISABLED:
return 3;
default:
return -1;
}
}
private void setInterruptStateFromByte(byte state) {
switch(state) {
case 0:
interruptState = ENABLED;
break;
case 1:
interruptState = DELAY_OFF;
break;
case 2:
interruptState = DELAY_ON;
break;
case 3:
interruptState = DISABLED;
break;
default:
interruptState = DISABLED;
System.err.println("Unable to load interrupt state from save file");
break;
}
}
/**
* returns the state to how it was saved
* from saveState()
*
*
* @param save same byte array as created in saveGame
*/
public void loadState(byte[] save) {
registers.setReg(A, Byte.toUnsignedInt(save[0]));
registers.setReg(B, Byte.toUnsignedInt(save[1]));
registers.setReg(C, Byte.toUnsignedInt(save[2]));
registers.setReg(D, Byte.toUnsignedInt(save[3]));
registers.setReg(E, Byte.toUnsignedInt(save[4]));
registers.setReg(F, Byte.toUnsignedInt(save[5]));
registers.setReg(H, Byte.toUnsignedInt(save[6]));
registers.setReg(L, Byte.toUnsignedInt(save[7]));
sp = Byte.toUnsignedInt(save[8]);
sp |= Byte.toUnsignedInt(save[9]) << 8;
pc = Byte.toUnsignedInt(save[10]);
pc |= Byte.toUnsignedInt(save[11]) << 8;
timerCounter = Byte.toUnsignedInt(save[12]);
timerCounter |= (Byte.toUnsignedInt(save[13]) << 8);
divideCounter = Byte.toUnsignedInt(save[14]);
divideCounter |= Byte.toUnsignedInt(save[15]);
setInterruptStateFromByte(save[16]);
dumpRegisters(0x0);
}
/**
* amount of bytes used for byte saving
* @return lenght of bytes used for saving
*/
public static int byteSaveLength() {
return BYTE_SAVE_LENGTH;
}
/**
* Execute the next opcode in memory, and update the CPU timers
*
* @return clock cycles taken to execute the opcode
*/
public int ExecuteOpcode() {
if (executionHalted) {
if ((memory.readByte(0xff0f) & memory.readByte(0xffff)) != 0) {
executionHalted = false;
} else {
updateDivideRegister(4);
updateTimers(4);
return 4;
}
}
//handle interrupt state change
if (interruptState == DELAY_ON) {
interruptState = ENABLED;
} else if (interruptState == DELAY_OFF) {
interruptState = DISABLED;
}
int opcode = memory.readByte(pc);
pc++;
int cycles = runInstruction(opcode);
updateDivideRegister(cycles); //TODO
updateTimers(cycles);
checkInterrupts();
return cycles;
}
/**
* Opcode Instructions for the Gameboy Z80 Chip.
*
* <p>
* Runs the instruction associated with the opcode, and returns the
* clock cycles taken.
*
* TODO HALT BUG
* @param opcode (required) opcode to execute
* @return number of cycles taken to execute
*/
private int runInstruction(int opcode) {
switch (opcode) {
case 0x0: return 4; //NOP
// LD nn,n
case 0x06: return ld_NN_N(B);
case 0x0e: return ld_NN_N(C);
case 0x16: return ld_NN_N(D);
case 0x1e: return ld_NN_N(E);
case 0x26: return ld_NN_N(H);
case 0x2e: return ld_NN_N(L);
//LD r1,r2
case 0x7f: return eightBitLdR1R2(A, A);
case 0x78: return eightBitLdR1R2(A, B);
case 0x79: return eightBitLdR1R2(A, C);
case 0x7a: return eightBitLdR1R2(A, D);
case 0x7b: return eightBitLdR1R2(A, E);
case 0x7c: return eightBitLdR1R2(A, H);
case 0x7d: return eightBitLdR1R2(A, L);
case 0x7e: return eightBitLdR1R2(A, HL);
case 0x40: return eightBitLdR1R2(B, B);
case 0x41: return eightBitLdR1R2(B, C);
case 0x42: return eightBitLdR1R2(B, D);
case 0x43: return eightBitLdR1R2(B, E);
case 0x44: return eightBitLdR1R2(B, H);
case 0x45: return eightBitLdR1R2(B, L);
case 0x46: return eightBitLdR1R2(B, HL);
case 0x48: return eightBitLdR1R2(C, B);
case 0x49: return eightBitLdR1R2(C, C);
case 0x4a: return eightBitLdR1R2(C, D);
case 0x4b: return eightBitLdR1R2(C, E);
case 0x4c: return eightBitLdR1R2(C, H);
case 0x4d: return eightBitLdR1R2(C, L);
case 0x4e: return eightBitLdR1R2(C, HL);
case 0x50: return eightBitLdR1R2(D, B);
case 0x51: return eightBitLdR1R2(D, C);
case 0x52: return eightBitLdR1R2(D, D);
case 0x53: return eightBitLdR1R2(D, E);
case 0x54: return eightBitLdR1R2(D, H);
case 0x55: return eightBitLdR1R2(D, L);
case 0x56: return eightBitLdR1R2(D, HL);
case 0x58: return eightBitLdR1R2(E, B);
case 0x59: return eightBitLdR1R2(E, C);
case 0x5a: return eightBitLdR1R2(E, D);
case 0x5b: return eightBitLdR1R2(E, E);
case 0x5c: return eightBitLdR1R2(E, H);
case 0x5d: return eightBitLdR1R2(E, L);
case 0x5e: return eightBitLdR1R2(E, HL);
case 0x60: return eightBitLdR1R2(H, B);
case 0x61: return eightBitLdR1R2(H, C);
case 0x62: return eightBitLdR1R2(H, D);
case 0x63: return eightBitLdR1R2(H, E);
case 0x64: return eightBitLdR1R2(H, H);
case 0x65: return eightBitLdR1R2(H, L);
case 0x66: return eightBitLdR1R2(H, HL);
case 0x68: return eightBitLdR1R2(L, B);
case 0x69: return eightBitLdR1R2(L, C);
case 0x6a: return eightBitLdR1R2(L, D);
case 0x6b: return eightBitLdR1R2(L, E);
case 0x6c: return eightBitLdR1R2(L, H);
case 0x6d: return eightBitLdR1R2(L, L);
case 0x6e: return eightBitLdR1R2(L, HL);
case 0x70: return eightBitLdR1R2(HL, B);
case 0x71: return eightBitLdR1R2(HL, C);
case 0x72: return eightBitLdR1R2(HL, D);
case 0x73: return eightBitLdR1R2(HL, E);
case 0x74: return eightBitLdR1R2(HL, H);
case 0x75: return eightBitLdR1R2(HL, L);
// special 8 bit load from memory
case 0x36: return eightBitLoadFromMem();
// LD A,n
case 0x0a: return eightBitLdAN(BC);
case 0x1a: return eightBitLdAN(DE);
case 0xfa: return eightBitALoadMem(true);
case 0x3e: return eightBitALoadMem(false);
// LD n,A
case 0x47: return eightBitLdR1R2(B, A);
case 0x4f: return eightBitLdR1R2(C, A);
case 0x57: return eightBitLdR1R2(D, A);
case 0x5f: return eightBitLdR1R2(E, A);
case 0x67: return eightBitLdR1R2(H, A);
case 0x6f: return eightBitLdR1R2(L, A);
case 0x02: return eightBitLdR1R2(BC, A);
case 0x12: return eightBitLdR1R2(DE, A);
case 0x77: return eightBitLdR1R2(HL, A);
case 0xea: return eightBitLoadToMem();
case 0xf2: return eightBitLDfromAC();
case 0xe2: return eightBitLDtoAC();
// LDD A,(HL)
case 0x3a: return eightBitLDAHl();
// LDD (HL), A
case 0x32: return eightBitStoreHL();
// LDI (HL), A
case 0x2a: return eightBitLDIA();
// LDI (HL), A
case 0x22: return LDI_HL_A();
// LDH (n), A, LDH A,(n)
case 0xe0: return eightBitLdhA(true);
case 0xf0: return eightBitLdhA(false);
//LD n, nn
case 0x01: return ld_N_NN(BC);
case 0x11: return ld_N_NN(DE);
case 0x21: return ld_N_NN(HL);
case 0x31: return ld_SP_NN();
//LD SP,HL
case 0xf9: return sixteenBitLdSpHl();
case 0xf8: return sixteenBitLdHlSp();
//LD (nn), SP
case 0x08: return sixteenBitLdNnSp();
//Push nn to stack
case 0xf5: return pushNN(AF);
case 0xc5: return pushNN(BC);
case 0xd5: return pushNN(DE);
case 0xe5: return pushNN(HL);
//POP nn off stack
case 0xf1: return popNN(AF);
case 0xc1: return popNN(BC);
case 0xd1: return popNN(DE);
case 0xe1: return popNN(HL);
//ADD A,n
case 0x87: return addAN(A, false, false);
case 0x80: return addAN(B, false, false);
case 0x81: return addAN(C, false, false);
case 0x82: return addAN(D, false, false);
case 0x83: return addAN(E, false, false);
case 0x84: return addAN(H, false, false);
case 0x85: return addAN(L, false, false);
case 0x86: return addAN(HL, false, false);
case 0xc6: return addAN(A, false, true);
//ADC A,n
case 0x8f: return addAN(A, true, false);
case 0x88: return addAN(B, true, false);
case 0x89: return addAN(C, true, false);
case 0x8a: return addAN(D, true, false);
case 0x8b: return addAN(E, true, false);
case 0x8c: return addAN(H, true, false);
case 0x8d: return addAN(L, true, false);
case 0x8e: return addAN(HL, true, false);
case 0xce: return addAN(A, true, true);
//SUB n
case 0x97: return subAN(A, false, false);
case 0x90: return subAN(B, false, false);
case 0x91: return subAN(C, false, false);
case 0x92: return subAN(D, false, false);
case 0x93: return subAN(E, false, false);
case 0x94: return subAN(H, false, false);
case 0x95: return subAN(L, false, false);
case 0x96: return subAN(HL, false, false);
case 0xd6: return subAN(A, false, true);
//SUBC A,n
case 0x9f: return subAN(A, true, false);
case 0x98: return subAN(B, true, false);
case 0x99: return subAN(C, true, false);
case 0x9a: return subAN(D, true, false);
case 0x9b: return subAN(E, true, false);
case 0x9c: return subAN(H, true, false);
case 0x9d: return subAN(L, true, false);
case 0x9e: return subAN(HL, true, false);
case 0xde: return subAN(A, true, true);
//AND N
case 0xa7: return andN(A, false);
case 0xa0: return andN(B, false);
case 0xa1: return andN(C, false);
case 0xa2: return andN(D, false);
case 0xa3: return andN(E, false);
case 0xa4: return andN(H, false);
case 0xa5: return andN(L, false);
case 0xa6: return andN(HL, false);
case 0xe6: return andN(A, true);
//OR N
case 0xb7: return orN(A, false);
case 0xb0: return orN(B, false);
case 0xb1: return orN(C, false);
case 0xb2: return orN(D, false);
case 0xb3: return orN(E, false);
case 0xb4: return orN(H, false);
case 0xb5: return orN(L, false);
case 0xb6: return orN(HL, false);
case 0xf6: return orN(A, true);
// XOR n
case 0xaf: return xorN(A, false);
case 0xa8: return xorN(B, false);
case 0xa9: return xorN(C, false);
case 0xaa: return xorN(D, false);
case 0xab: return xorN(E, false);
case 0xac: return xorN(H, false);
case 0xad: return xorN(L, false);
case 0xae: return xorN(HL, false);
case 0xee: return xorN(A, true);
// CP n
case 0xbf: return cpN(A, false);
case 0xb8: return cpN(B, false);
case 0xb9: return cpN(C, false);
case 0xba: return cpN(D, false);
case 0xbb: return cpN(E, false);
case 0xbc: return cpN(H, false);
case 0xbd: return cpN(L, false);
case 0xbe: return cpN(HL, false);
case 0xfe: return cpN(A, true);
// INC n
case 0x3c: return incN(A);
case 0x04: return incN(B);
case 0x0c: return incN(C);
case 0x14: return incN(D);
case 0x1c: return incN(E);
case 0x24: return incN(H);
case 0x2c: return incN(L);
case 0x34: return incN(HL);
// DEC n
case 0x3d: return decN(A);
case 0x05: return decN(B);
case 0x0d: return decN(C);
case 0x15: return decN(D);
case 0x1d: return decN(E);
case 0x25: return decN(H);
case 0x2d: return decN(L);
case 0x35: return decN(HL);
//ADD HL,n
case 0x09: return sixteenBitAdd(BC, false);
case 0x19: return sixteenBitAdd(DE, false);
case 0x29: return sixteenBitAdd(HL, false);
case 0x39: return sixteenBitAdd(BC, true);
//ADD SP,n
case 0xe8: return addSPN();
//INC nn
case 0x03: return incNN(BC, false);
case 0x13: return incNN(DE, false);
case 0x23: return incNN(HL, false);
case 0x33: return incNN(BC, true);
//DEC nn
case 0x0B: return decNN(BC, false);
case 0x1B: return decNN(DE, false);
case 0x2B: return decNN(HL, false);
case 0x3B: return decNN(BC, true);
// extended
case 0xcb: return extendedOpcode();
// DAA
case 0x27: return decAdjust();
//CPL
case 0x2f: return cplRegA();
//CCF
case 0x3f: return ccf();
//SCF
case 0x37: return scf();
//Jumps
case 0xc3: return jump();
// conditional jump
case 0xc2: return jumpC(opcode);
case 0xca: return jumpC(opcode);
case 0xd2: return jumpC(opcode);
case 0xda: return jumpC(opcode);
// JP (HL)
case 0xe9: return jumpHL();
//JR n
case 0x18: return jumpN();
//JR cc, n
case 0x20: return jumpCN(opcode);
case 0x28: return jumpCN(opcode);
case 0x30: return jumpCN(opcode);
case 0x38: return jumpCN(opcode);
case 0x76: return halt();
case 0x10: return stop();
case 0xf3: return disableInterrupts();
case 0xfb: return enableInterrupts();
//calls
case 0xcd: return call();
case 0xc4: return callC(opcode);
case 0xcc: return callC(opcode);
case 0xd4: return callC(opcode);
case 0xdc: return callC(opcode);
//restarts
case 0xc7: return restart(0x00);
case 0xcf: return restart(0x08);
case 0xd7: return restart(0x10);
case 0xdf: return restart(0x18);
case 0xe7: return restart(0x20);
case 0xef: return restart(0x28);
case 0xf7: return restart(0x30);
case 0xff: return restart(0x38);
//RETURNs
case 0xc9: return ret();
case 0xc0: return retC(opcode);
case 0xc8: return retC(opcode);
case 0xd0: return retC(opcode);
case 0xd8: return retC(opcode);
//RETI
case 0xd9: return retI();
//ROTATES AND SHIFTS
//RLCA
case 0x07: return rlcA();
//RLA
case 0x17: return rlA();
//RRCA
case 0x0f: return rrcA();
case 0x1f: return rrN(A, false);
default:
System.err.println("Unimplemented opcode: 0x" +
Integer.toHexString(opcode));
System.err.println("pc: 0x" + Integer.toHexString(pc));
System.exit(1); //TODO DONT
}
return 0;
}
private int extendedOpcode() {
int opcode = memory.readByte(pc);
pc++;
switch(opcode) {
//SWAP N
case 0x37: return swapN(A);
case 0x30: return swapN(B);
case 0x31: return swapN(C);
case 0x32: return swapN(D);
case 0x33: return swapN(E);
case 0x34: return swapN(H);
case 0x35: return swapN(L);
case 0x36: return swapN(HL);
//RLC n
case 0x07: return rlcN(A);
case 0x00: return rlcN(B);
case 0x01: return rlcN(C);
case 0x02: return rlcN(D);
case 0x03: return rlcN(E);
case 0x04: return rlcN(H);
case 0x05: return rlcN(L);
case 0x06: return rlcN(HL);
//RL n
case 0x17: return rlN(A);
case 0x10: return rlN(B);
case 0x11: return rlN(C);
case 0x12: return rlN(D);
case 0x13: return rlN(E);
case 0x14: return rlN(H);
case 0x15: return rlN(L);
case 0x16: return rlN(HL);
//RRC n
case 0x0f: return rrcN(A);
case 0x08: return rrcN(B);
case 0x09: return rrcN(C);
case 0x0a: return rrcN(D);
case 0x0b: return rrcN(E);
case 0x0c: return rrcN(H);
case 0x0d: return rrcN(L);
case 0x0e: return rrcN(HL);
//RR n
case 0x1f: return rrN(A, true);
case 0x18: return rrN(B, true);
case 0x19: return rrN(C, true);
case 0x1a: return rrN(D, true);
case 0x1b: return rrN(E, true);
case 0x1c: return rrN(H, true);
case 0x1d: return rrN(L, true);
case 0x1e: return rrN(HL, true);
//SLA n
case 0x27: return slAN(A);
case 0x20: return slAN(B);
case 0x21: return slAN(C);
case 0x22: return slAN(D);
case 0x23: return slAN(E);
case 0x24: return slAN(H);
case 0x25: return slAN(L);
case 0x26: return slAN(HL);
//SRA n
case 0x2f: return srAL(A, false);
case 0x28: return srAL(B, false);
case 0x29: return srAL(C, false);
case 0x2a: return srAL(D, false);
case 0x2b: return srAL(E, false);
case 0x2c: return srAL(H, false);
case 0x2d: return srAL(L, false);
case 0x2e: return srAL(HL, false);
//SRL n
case 0x3f: return srAL(A, true);
case 0x38: return srAL(B, true);
case 0x39: return srAL(C, true);
case 0x3a: return srAL(D, true);
case 0x3b: return srAL(E, true);
case 0x3c: return srAL(H, true);
case 0x3d: return srAL(L, true);
case 0x3e: return srAL(HL, true);
//Bit opcodes
case 0x47: return bitBR(0, A);
case 0x40: return bitBR(0, B);
case 0x41: return bitBR(0, C);
case 0x42: return bitBR(0, D);
case 0x43: return bitBR(0, E);
case 0x44: return bitBR(0, H);
case 0x45: return bitBR(0, L);
case 0x46: return bitBR(0, HL);
case 0x4f: return bitBR(1, A);
case 0x48: return bitBR(1, B);
case 0x49: return bitBR(1, C);
case 0x4a: return bitBR(1, D);
case 0x4b: return bitBR(1, E);
case 0x4c: return bitBR(1, H);
case 0x4d: return bitBR(1, L);
case 0x4e: return bitBR(1, HL);
case 0x57: return bitBR(2, A);
case 0x50: return bitBR(2, B);
case 0x51: return bitBR(2, C);
case 0x52: return bitBR(2, D);
case 0x53: return bitBR(2, E);
case 0x54: return bitBR(2, H);
case 0x55: return bitBR(2, L);
case 0x56: return bitBR(2, HL);
case 0x5f: return bitBR(3, A);
case 0x58: return bitBR(3, B);
case 0x59: return bitBR(3, C);
case 0x5a: return bitBR(3, D);
case 0x5b: return bitBR(3, E);
case 0x5c: return bitBR(3, H);
case 0x5d: return bitBR(3, L);
case 0x5e: return bitBR(3, HL);
case 0x67: return bitBR(4, A);
case 0x60: return bitBR(4, B);
case 0x61: return bitBR(4, C);
case 0x62: return bitBR(4, D);
case 0x63: return bitBR(4, E);
case 0x64: return bitBR(4, H);
case 0x65: return bitBR(4, L);
case 0x66: return bitBR(4, HL);
case 0x6f: return bitBR(5, A);
case 0x68: return bitBR(5, B);
case 0x69: return bitBR(5, C);
case 0x6a: return bitBR(5, D);
case 0x6b: return bitBR(5, E);
case 0x6c: return bitBR(5, H);
case 0x6d: return bitBR(5, L);
case 0x6e: return bitBR(5, HL);
case 0x77: return bitBR(6, A);
case 0x70: return bitBR(6, B);
case 0x71: return bitBR(6, C);
case 0x72: return bitBR(6, D);
case 0x73: return bitBR(6, E);
case 0x74: return bitBR(6, H);
case 0x75: return bitBR(6, L);
case 0x76: return bitBR(6, HL);
case 0x7f: return bitBR(7, A);
case 0x78: return bitBR(7, B);
case 0x79: return bitBR(7, C);
case 0x7a: return bitBR(7, D);
case 0x7b: return bitBR(7, E);
case 0x7c: return bitBR(7, H);
case 0x7d: return bitBR(7, L);
case 0x7e: return bitBR(7, HL);
case 0xc7: return setBR(1, 0, A);
case 0xc0: return setBR(1, 0, B);
case 0xc1: return setBR(1, 0, C);
case 0xc2: return setBR(1, 0, D);
case 0xc3: return setBR(1, 0, E);
case 0xc4: return setBR(1, 0, H);
case 0xc5: return setBR(1, 0, L);
case 0xc6: return setBR(1, 0, HL);
case 0xcf: return setBR(1, 1, A);
case 0xc8: return setBR(1, 1, B);
case 0xc9: return setBR(1, 1, C);
case 0xca: return setBR(1, 1, D);
case 0xcb: return setBR(1, 1, E);
case 0xcc: return setBR(1, 1, H);
case 0xcd: return setBR(1, 1, L);
case 0xce: return setBR(1, 1, HL);
case 0xd7: return setBR(1, 2, A);
case 0xd0: return setBR(1, 2, B);
case 0xd1: return setBR(1, 2, C);
case 0xd2: return setBR(1, 2, D);
case 0xd3: return setBR(1, 2, E);
case 0xd4: return setBR(1, 2, H);
case 0xd5: return setBR(1, 2, L);
case 0xd6: return setBR(1, 2, HL);
case 0xdf: return setBR(1, 3, A);
case 0xd8: return setBR(1, 3, B);
case 0xd9: return setBR(1, 3, C);
case 0xda: return setBR(1, 3, D);
case 0xdb: return setBR(1, 3, E);
case 0xdc: return setBR(1, 3, H);
case 0xdd: return setBR(1, 3, L);
case 0xde: return setBR(1, 3, HL);
case 0xe7: return setBR(1, 4, A);
case 0xe0: return setBR(1, 4, B);
case 0xe1: return setBR(1, 4, C);
case 0xe2: return setBR(1, 4, D);
case 0xe3: return setBR(1, 4, E);
case 0xe4: return setBR(1, 4, H);
case 0xe5: return setBR(1, 4, L);
case 0xe6: return setBR(1, 4, HL);
case 0xef: return setBR(1, 5, A);
case 0xe8: return setBR(1, 5, B);
case 0xe9: return setBR(1, 5, C);
case 0xea: return setBR(1, 5, D);
case 0xeb: return setBR(1, 5, E);
case 0xec: return setBR(1, 5, H);
case 0xed: return setBR(1, 5, L);
case 0xee: return setBR(1, 5, HL);
case 0xf7: return setBR(1, 6, A);
case 0xf0: return setBR(1, 6, B);
case 0xf1: return setBR(1, 6, C);
case 0xf2: return setBR(1, 6, D);
case 0xf3: return setBR(1, 6, E);
case 0xf4: return setBR(1, 6, H);
case 0xf5: return setBR(1, 6, L);
case 0xf6: return setBR(1, 6, HL);
case 0xff: return setBR(1, 7, A);
case 0xf8: return setBR(1, 7, B);
case 0xf9: return setBR(1, 7, C);
case 0xfa: return setBR(1, 7, D);
case 0xfb: return setBR(1, 7, E);
case 0xfc: return setBR(1, 7, H);
case 0xfd: return setBR(1, 7, L);
case 0xfe: return setBR(1, 7, HL);
case 0x87: return setBR(0, 0, A);
case 0x80: return setBR(0, 0, B);
case 0x81: return setBR(0, 0, C);
case 0x82: return setBR(0, 0, D);
case 0x83: return setBR(0, 0, E);
case 0x84: return setBR(0, 0, H);
case 0x85: return setBR(0, 0, L);
case 0x86: return setBR(0, 0, HL);
case 0x8f: return setBR(0, 1, A);
case 0x88: return setBR(0, 1, B);
case 0x89: return setBR(0, 1, C);
case 0x8a: return setBR(0, 1, D);
case 0x8b: return setBR(0, 1, E);
case 0x8c: return setBR(0, 1, H);
case 0x8d: return setBR(0, 1, L);
case 0x8e: return setBR(0, 1, HL);
case 0x97: return setBR(0, 2, A);
case 0x90: return setBR(0, 2, B);
case 0x91: return setBR(0, 2, C);
case 0x92: return setBR(0, 2, D);
case 0x93: return setBR(0, 2, E);
case 0x94: return setBR(0, 2, H);
case 0x95: return setBR(0, 2, L);
case 0x96: return setBR(0, 2, HL);
case 0x9f: return setBR(0, 3, A);
case 0x98: return setBR(0, 3, B);
case 0x99: return setBR(0, 3, C);
case 0x9a: return setBR(0, 3, D);
case 0x9b: return setBR(0, 3, E);
case 0x9c: return setBR(0, 3, H);
case 0x9d: return setBR(0, 3, L);
case 0x9e: return setBR(0, 3, HL);
case 0xa7: return setBR(0, 4, A);
case 0xa0: return setBR(0, 4, B);
case 0xa1: return setBR(0, 4, C);
case 0xa2: return setBR(0, 4, D);
case 0xa3: return setBR(0, 4, E);
case 0xa4: return setBR(0, 4, H);
case 0xa5: return setBR(0, 4, L);
case 0xa6: return setBR(0, 4, HL);
case 0xaf: return setBR(0, 5, A);
case 0xa8: return setBR(0, 5, B);
case 0xa9: return setBR(0, 5, C);
case 0xaa: return setBR(0, 5, D);
case 0xab: return setBR(0, 5, E);
case 0xac: return setBR(0, 5, H);
case 0xad: return setBR(0, 5, L);
case 0xae: return setBR(0, 5, HL);
case 0xb7: return setBR(0, 6, A);
case 0xb0: return setBR(0, 6, B);
case 0xb1: return setBR(0, 6, C);
case 0xb2: return setBR(0, 6, D);
case 0xb3: return setBR(0, 6, E);
case 0xb4: return setBR(0, 6, H);
case 0xb5: return setBR(0, 6, L);
case 0xb6: return setBR(0, 6, HL);
case 0xbf: return setBR(0, 7, A);
case 0xb8: return setBR(0, 7, B);
case 0xb9: return setBR(0, 7, C);
case 0xba: return setBR(0, 7, D);
case 0xbb: return setBR(0, 7, E);
case 0xbc: return setBR(0, 7, H);
case 0xbd: return setBR(0, 7, L);
case 0xbe: return setBR(0, 7, HL);
default:
System.err.println("Unimplemented opcode: 0xcb" +
Integer.toHexString(opcode));
dumpRegisters(0);
System.exit(1);
}
return 0;
}
/**
* LD nn,n. Put value nn into n.
*
* nn = B,C,D,E,H,L
* n = 8 bit immediate value
*
* @param reg (required) register to load to
*/
private int ld_NN_N(GBRegisters.Reg reg) {
int data = memory.readByte(pc);
pc++;
registers.setReg(reg, data);
return 8;
}
/**
* Put value r1 into r2.
*
* <p> Use with: r1,r2 = A,B,C,D,E,H,L,(HL)
*
* @param dest destination register
* @param src source register
*/
private int eightBitLdR1R2(GBRegisters.Reg dest, GBRegisters.Reg src) {
if (src == HL) {
int data = memory.readByte(registers.getReg(HL));
registers.setReg(dest, data);
return 8;
} else if ((dest == HL) || (dest == BC) || (dest == DE)) {
memory.writeByte(registers.getReg(dest), registers.getReg(src));
return 8;
} else {
registers.setReg(dest, registers.getReg(src));
return 4;
}
}
/**
* Special function for opcode 0x36
*
* LD (HL), n
*/
private int eightBitLoadFromMem() {
int data = memory.readByte(pc);
pc++;
memory.writeByte(registers.getReg(GBRegisters.Reg.HL), data);
return 12;
}
/**
* LD n,a
* put value A into n
* (nn) is two byte immediate value pointing to address
* to write data
*
* LSB is first
* Special function for opcode 0xea
*/
private int eightBitLoadToMem() {
int address = readWordFromMem(pc);
pc += 2;
memory.writeByte(address, registers.getReg(A));
return 16;
}
/**
* LD A,n
*
* Put value n into A. For opcodes 0x0a, 0x1a
*
*
* @param src value n
*/
private int eightBitLdAN(GBRegisters.Reg src) {
int data = memory.readByte(registers.getReg(src));
registers.setReg(A, data);
return 8;
}
/**
* LD A,n (where n is located in rom, or an address in rom)
*
* For opcodes: 0xfa, 0x3e
*
* @param isPointer If true, next two bytes are address in memory to load
* from. If false, eight bit immediate value is loaded.
*/
private int eightBitALoadMem(boolean isPointer) {
if (isPointer) {
int address = readWordFromMem(pc);
pc += 2;
registers.setReg(A, memory.readByte(address));
return 16;
} else {
int data = memory.readByte(pc);
pc++;
registers.setReg(A, data);
return 8;
}
}
private int eightBitLDfromAC() {
int data = memory.readByte(registers.getReg(C) + 0xff00);
registers.setReg(A, data);
return 8;
}
private int eightBitLDtoAC() {
int address = registers.getReg(C);
int data = registers.getReg(A);
memory.writeByte(address + 0xff00, data);
return 8;
}
/**
* halts the cpu until an interrupt occurs
*/
private int halt() {
executionHalted = true;
return 4;
}
/** LDD A, (HL)
*
* Put value at address HL into A, decrement HL
*
*/
private int eightBitLDAHl() {
int address = registers.getReg(GBRegisters.Reg.HL);
registers.setReg(GBRegisters.Reg.A, memory.readByte(address));
registers.setReg(GBRegisters.Reg.HL, address - 1);
return 8;
}
/**
* LDD (HL), A
* Put A into memory address HL, Decrement HL
*
*/
private int eightBitStoreHL() {
int address = registers.getReg(HL);
int data = registers.getReg(A);
memory.writeByte(address, data);
registers.setReg(GBRegisters.Reg.HL, address - 1);
return 8;
}
/**
* Put value at address HL into A, increment HL
*
*/
private int eightBitLDIA() {
int address = registers.getReg(HL);
registers.setReg(A, memory.readByte(address));
registers.setReg(HL, address + 1);
return 8;
}
private int LDI_HL_A() {
int address = registers.getReg(HL);
int data = registers.getReg(A);
memory.writeByte(address, data);
registers.setReg(HL, address + 1);
return 8;
}
/**
* LDH (n), A and LDH A, (n)
*
* LDH (n), A - Put A into memory address $FF00 + n
* LDH A,(n) - Put memory address $FF00+n into A
*
* @param writeToMem (required) if true LDH (n),A. if false LDH A,(n)
*
*/
private int eightBitLdhA(boolean writeToMem) {
int offset = memory.readByte(pc);
pc++;
if (writeToMem) {
int data = registers.getReg(A);
memory.writeByte(0xff00 + offset, data);
} else {
int data = memory.readByte(0xff00 + offset);
registers.setReg(A, data);
}
return 12;
}
/**
* LD n, nn
*
* Put value nn into n
*
* nn - 16 Bit immediate value, n = BC, DE, HL
*
*/
private int ld_N_NN(GBRegisters.Reg reg) {
int data = readWordFromMem(pc);
pc += 2;
registers.setReg(reg, data);
return 12;
}
/**
* LD n, nn
* Put 2 byte immediate
* value nn into SP
*
*/
private int ld_SP_NN() {
sp = readWordFromMem(pc);
pc += 2;
return 12;
}
/**
* LD SP,HL
*
* Put HL into SP
*/
private int sixteenBitLdSpHl() {
sp = registers.getReg(GBRegisters.Reg.HL);
return 8;
}
/**
* LDHL SP,n
*
* Put SP+n effective address into HL
*
* <p>n = one byte signed immediate value
* Z - reset
* N - reset
* H - set or reset according to operation
* C - set or reset according to operation
*
*/
private int sixteenBitLdHlSp() {
byte offset = (byte)memory.readByte(pc);
pc++;
registers.setReg(HL, offset + sp);
registers.resetAll();
if ((sp & 0xf)+ (offset & 0xf) > 0xf) {
registers.setH();
}
if ((sp & 0xff) + (offset & 0xff) > 0xff) {
registers.setC();
}
return 12;
}
/**
* Put SP at address n (2 byte immediate address)
* stored little endian
*/
private int sixteenBitLdNnSp() {
int address = readWordFromMem(pc);
pc += 2;
memory.writeByte(address, sp & 0xff);
memory.writeByte(address + 1, ((sp & 0xff00) >> 8));
return 20;
}
/**
* Push Register Pair value to stack
*
* @param src (required) register pair to push to stack
*/
private int pushNN(GBRegisters.Reg src) {
int reg = registers.getReg(src);
writeWordToMem(reg);
return 16;
}
/**
* pop value off stack to a register pair
*
* @param dest (required) register to store data in
*/
private int popNN(GBRegisters.Reg dest) {
//todo OAM?
int data = readWordFromMem(sp);
sp += 2;
registers.setReg(dest, data);
return 12;
}
/**
* ADD A,n
*
* Add n to A
*
* Flags:
* Z - set if result is zero
* N - Reset
* H - set if carry from bit 3
* C - set if carry from bit 7
*
* @param src (source to add from)
* @param addCarry true if adding carry
* @param readMem true if reading immediate value from memory
* (immediate value) if true, src ignored
*/
private int addAN(GBRegisters.Reg src, boolean addCarry, boolean readMem) {
int cycles;
int regA = registers.getReg(A);
int toAdd;
if (readMem) {
toAdd = memory.readByte(pc);
pc++;
cycles = 8;
} else if (src == HL) {
toAdd = memory.readByte(registers.getReg(src));
cycles = 8;
} else {
toAdd = registers.getReg(src);
cycles = 4;
}
//if adding carry and carry is set add 1
int carryBit = (addCarry && isSet(registers.getReg(F), CARRY_F)) ? 1 : 0;
registers.setReg(A, (toAdd + regA + carryBit) & 0xff);
//flags
registers.resetAll();
if (registers.getReg(A) == 0) {
registers.setZ();
}
if ((regA & 0xf) + (toAdd & 0xf) + carryBit > 0xf) {
registers.setH();
}
if (toAdd + regA + carryBit > 0xff) {
registers.setC();
}
return cycles;
}
/**
* SUB n, SUBC A,n
* Subtract N from A
* Z- Set if result is zero
* N - Set
* H - set if no borrow from bit 4
* C - set if no borrow
*
*/
private int subAN(GBRegisters.Reg src, boolean addCarry, boolean readMem) {
int cycles;
int regA = registers.getReg(A);
int toSub;
if (readMem) {
toSub = memory.readByte(pc);
pc++;
cycles = 8;
} else if (src == HL) {
toSub = memory.readByte(registers.getReg(src));
cycles = 8;
} else {
toSub = registers.getReg(src);
cycles = 4;
}
//if subtracting carry and carry is set
int carryBit = (addCarry && isSet(registers.getReg(F), CARRY_F)) ? 1 : 0;
//sub
registers.setReg(A, regA - toSub - carryBit);
//flags
registers.resetAll();
if (registers.getReg(A) == 0) {
registers.setZ();
}
registers.setN();
if ((regA & 0xf) < (toSub & 0xf) + carryBit) {
registers.setH();
}
if (regA < (toSub + carryBit)) {
registers.setC();
}
return cycles;
}
/**
* And N with A, result in A
*
* FLAGS:
* Z - Set if result is 0
* N - Reset
* H - Set
* C - Reset
*
* @param src (required) N to and
* @param readMem (required) true if reading immediate value from
* memory (if true, src is ignored)
*/
private int andN(GBRegisters.Reg src, boolean readMem) {
int cycles;
int data;
if (readMem) {
data = memory.readByte(pc);
pc++;
cycles = 8;
} else if (src == HL) {
data = memory.readByte(registers.getReg(src));
cycles = 8;
} else {
data = registers.getReg(src);
cycles = 4;
}
int regA = registers.getReg(A);
registers.setReg(A, data & regA);
registers.resetAll();
if (((data & regA) & 0xff) == 0) {
registers.setZ();
}
registers.setH();
return cycles;
}
/**
* OR N with A, result in A
*
* FLAGS:
* Z - Set if result is 0
* N - Reset
* H - Reset
* C - Reset
*
* @param src (required) N to and
* @param readMem (required) true if reading immediate value from
* memory (if true, src is ignored)
*/
private int orN(GBRegisters.Reg src, boolean readMem) {
int cycles;
int data;
if (readMem) {
data = memory.readByte(pc);
pc++;
cycles = 8;
} else if (src == HL) {
data = memory.readByte(registers.getReg(src));
cycles = 8;
} else {
data = registers.getReg(src);
cycles = 4;
}
int regA = registers.getReg(A);
registers.setReg(A, data | regA);
registers.resetAll();
if (((data | regA) & 0xff) == 0) {
registers.setZ();
}
return cycles;
}
/**
* XOR n
*
* Logical XOR n, with A, result in A
*
* FLAGS
* Z - set if result is 0
* N, H, C = Reset
* @param src (required) src register
* @param readMem (required) true if reading immediate value from
* memory (if true src ignored)
* @return clock cycles taken
*/
private int xorN(GBRegisters.Reg src, boolean readMem) {
int cycles;
int data;
if (readMem) {
data = memory.readByte(pc);
pc++;
cycles = 8;
} else if (src == HL) {
data = memory.readByte(registers.getReg(src));
cycles = 8;
} else {
data = registers.getReg(src);
cycles = 4;
}
int regA = registers.getReg(A);
registers.setReg(A, data ^ regA);
registers.resetAll();
if (((data ^ regA) & 0xff) == 0) {
registers.setZ();
}
return cycles;
}
/**
* CP n
*
* Compare A with n. Basically A - n subtraction but
* results are thrown away
*
* FLAGS
* Z - set if result is 0 (if A == n)
* N - set
* H - Set if no borrow from bit 4
* C = set if no morrow (Set if A is less than n)
*
* @param src (required) src register
* @param readMem (required) true if reading immediate value from
* memory (if true src ignored)
* @return clock cycles taken
*/
private int cpN(GBRegisters.Reg src, boolean readMem) {
int cycles;
int data;
if (readMem) {
data = memory.readByte(pc);
pc++;
cycles = 8;
} else if (src == HL) {
data = memory.readByte(registers.getReg(src));
cycles = 8;
} else {
data = registers.getReg(src);
cycles = 4;
}
int regA = registers.getReg(A);
registers.resetAll();
if (regA == data) {
registers.setZ();
}
registers.setN();
if ((regA & 0xf) < (data & 0xf)) {
registers.setH(); //no borrow from bit 4
}
if (regA < data) { //no borrow
registers.setC();
}
return cycles;
}
/**
* INC n
*
* Increment register n.
*
* FLAGS:
* Z - Set if result is 0
* N - Reset
* H - Set if carry from bit 3
* C - Not affected
* @param src (required) register to increment
*/
private int incN(GBRegisters.Reg src) {
int reg;
if (src == HL) {
reg = memory.readByte(registers.getReg(src));
memory.writeByte(registers.getReg(src), reg + 1);
} else {
reg = registers.getReg(src);
registers.setReg(src, reg + 1);
}
registers.resetZ();
if (((reg + 1) & 0xff) == 0) {
registers.setZ();
}
registers.resetN();
registers.resetH();
if ((reg & 0xf) == 0xf) {
registers.setH();
}
return (src == HL) ? 12 : 4;
}
/**
* DEC n
*
* Decrement register n.
*
* FLAGS:
* Z - Set if result is 0
* N - Set
* H - Set if no borrow from bit 4
* C - Not affected
* @param src (required) register to decrement
*/
private int decN(GBRegisters.Reg src) {
int reg;
if (src == HL) {
reg = memory.readByte(registers.getReg(src));
reg -= 1;
memory.writeByte(registers.getReg(src), reg & 0xff);
} else {
reg = registers.getReg(src);
reg -= 1;
registers.setReg(src, reg & 0xff);
}
registers.resetZ();
if (reg == 0) {
registers.setZ();
}
registers.setN();
registers.resetH();
if (((reg + 1) & 0xf0) != (reg & 0xf0)) {
registers.setH();
}
return (src == HL) ? 12 : 4;
}
/**
* ADD HL,n
*
* Add n to HL
*
* n = BC,DE,HL,SP
*
* Flags
* Z - Not affected
* N - Reset
* H - Set if carry from bit 11
* C - Set if carry from bit 15
*
* @param src source register to add
* @param addSP boolean (if true, adds stackpointer instead of register
* to HL, ignores src)
* @return clock cycles taken
*/
private int sixteenBitAdd(GBRegisters.Reg src, boolean addSP) {
int toAdd;
int regVal = registers.getReg(HL);
if (addSP) {
toAdd = sp;
} else {
toAdd = registers.getReg(src);
}
registers.setReg(HL, regVal + toAdd);
//flags
registers.resetN();
registers.resetH();
if ((regVal & 0xfff) + (toAdd & 0xfff) > 0xfff) {
registers.setH();
}
registers.resetC();
if ((regVal + toAdd) > 0xffff) {
registers.setC();
}
return 8;
}
/**
* ADD SP,n
* Add n to sp
*
* Flags:
* Z, N - Reset
* H, C - Set/reset according to operation????
*/
private int addSPN() {
byte offset = (byte)memory.readByte(pc);
pc++;
registers.resetAll();
if ((sp & 0xf) + (offset & 0xf) > 0xf) {
registers.setH();
}
if ((sp & 0xff) + (offset & 0xff) > 0xff) {
registers.setC();
}
sp += offset;
return 16;
}
/**
* INC nn
*
* Increment register nn
*
* Affects NO FLAGS
*
* @param reg register to increment (ignored if incSP is true)
* @param incSP boolean if true, ignore reg and increment sp
*/
private int incNN(GBRegisters.Reg reg, boolean incSP) {
if (incSP) {
sp++;
sp &= 0xffff;
} else {
int value = registers.getReg(reg);
registers.setReg(reg, (value + 1) & 0xffff);
}
return 8;
}
/**
* DEC nn
*
* Decrement register nn
*
* no flags affected
*
* @param reg register to increment (ignored if incSP is true)
* @param decSP boolean if true, ignore reg and increment sp
*/
private int decNN(GBRegisters.Reg reg, boolean decSP) {
if (decSP) {
sp
} else {
int value = registers.getReg(reg);
registers.setReg(reg, value - 1);
}
return 8;
}
/**
* Swap N
*
* swap upper and lower nibbles of n
*
* Flags Affected:
* Z - set if result is 0
* NHC - reset
*
* @param reg (required) register to swap
*/
private int swapN(GBRegisters.Reg reg) {
int data;
if (reg == HL) {
data = memory.readByte(registers.getReg(reg));
} else {
data = registers.getReg(reg);
}
int lowNib = data & 0xf;
int highNib = (data & 0xf0) >> 4;
data = highNib | (lowNib << 4);
if (reg == HL) {
memory.writeByte(registers.getReg(reg), data);
} else {
registers.setReg(reg, data);
}
registers.resetAll();
if (data == 0) {
registers.setZ();
}
return (reg == HL) ? 16 : 8;
}
private int decAdjust() {
int flags = registers.getReg(F);
int regA = registers.getReg(A);
if (!isSet(flags, SUBTRACT_F)) {
if (isSet(flags, HALFCARRY_F) || (regA & 0x0f) > 0x09) {
regA += 0x06;
}
if (isSet(flags, CARRY_F) || (regA > 0x9f)) {
regA += 0x60;
}
} else {
if (isSet(flags, HALFCARRY_F)) {
regA = (regA - 0x06) & 0xff;
}
if (isSet(flags, CARRY_F)) {
regA -= 0x60;
}
}
if ((regA & 0x100) == 0x100) {
registers.setC();
}
regA &= 0xff;
registers.resetH();
if (regA == 0) {
registers.setZ();
} else {
registers.resetZ();
}
registers.setReg(A, regA);
return 4;
}
/**
* Complement register A
*
* (toggles all bits)
*
* Flags: Sets N, H
*/
private int cplRegA() {
int reg = registers.getReg(A);
registers.setReg(A, reg ^ 0xff);
registers.setN();
registers.setH();
return 4;
}
/**
* Complement carry flag
*
* FLAGS:
* Z - not affected
* H, N - reset
* C - Complemented
*/
private int ccf() {
if (isSet(registers.getReg(F), CARRY_F)) {
registers.resetC();
} else {
registers.setC();
}
registers.resetN();
registers.resetH();
return 4;
}
/**
* Set carry flag
* Flags:
* Z - Not affected
* N,H - reset
* C - Set
*/
private int scf() {
registers.resetH();
registers.resetN();
registers.setC();
return 4;
}
/**
* Jump to address
* LSB first
*/
private int jump() {
pc = readWordFromMem(pc);
return 16;
}
/**
* Conditional jump
*
*/
private int jumpC(int opcode) {
int flags = registers.getReg(F);
switch (opcode) {
case 0xca:
if (isSet(flags, ZERO_F)) {
return jump();
}
break;
case 0xc2:
if (!isSet(flags, ZERO_F)) {
return jump();
}
break;
case 0xda:
if (isSet(flags, CARRY_F)) {
return jump();
}
break;
case 0xd2:
if (!isSet(flags, CARRY_F)) {
return jump();
}
default:
break;
}
pc += 2;
return 12;
}
/**
* JP (HL)
*
* Jump to address contained in HL
*/
private int jumpHL() {
pc = registers.getReg(HL);
return 4;
}
/**
* JR n
*
* add one byte immediate
* n to current address and jump to it
*/
private int jumpN() {
byte offset = (byte)memory.readByte(pc);
pc++;
pc += offset;
return 12;
}
/**
* JR cc,n
*
* Conditional Jump with immediate offset
*
* @param opcode (required) opcode for jump condition
*/
private int jumpCN(int opcode) {
int flags = registers.getReg(GBRegisters.Reg.F);
switch (opcode) {
case 0x28:
if (isSet(flags, ZERO_F)) {
return jumpN();
}
break;
case 0x20:
if (!isSet(flags, ZERO_F)) {
return jumpN();
}
break;
case 0x38:
if (isSet(flags, CARRY_F)) {
return jumpN();
}
break;
case 0x30:
if (!isSet(flags, CARRY_F)) {
return jumpN();
}
break;
default:
break;
}
pc++;
return 8;
}
/**
* Call nn
*
* push address of next instruction onto stack and jump to address
* nn (nn is 16 bit immediate value)
*
*/
private int call() {
int address = readWordFromMem(pc);
pc += 2;
pushWordToStack(pc);
pc = address;
return 24;
}
/**
* CALL cc,nn
*
* Call address n if following condition is true
* Z flag set /reset
* C flag set/reset
* @param opcode opcode to check for condition
*/
private int callC(int opcode) {
int flags = registers.getReg(GBRegisters.Reg.F);
switch(opcode) {
case 0xc4:
if (!isSet(flags, ZERO_F)) {
return call();
}
break;
case 0xcc:
if (isSet(flags, ZERO_F)) {
return call();
}
break;
case 0xd4:
if (!isSet(flags, CARRY_F)) {
return call();
}
break;
case 0xdc:
if (isSet(flags, CARRY_F)) {
return call();
}
break;
default:
break;
}
pc += 2;
return 12;
}
/**
* RET
*
* pop two bytes from stack and jump to that address
*/
private int ret() {
pc = readWordFromMem(sp);
sp += 2;
return 16;
}
/**
* RETI
*
* pop two bytes from stack and jump to that address
* enable interrupts
*/
private int retI() {
interruptState = DELAY_ON;
pc = readWordFromMem(sp);
sp += 2;
return 16;
}
/**
* Pushes a 16 bit word to the stack
* MSB pushed first
*/
private void pushWordToStack(int word) {
sp
memory.writeByte(sp, (word & 0xff00) >> 8);
sp
memory.writeByte(sp, word & 0xff);
}
/**
* RST n
*
* Push present address onto stack, jump to address 0x0000 +n
*
*/
private int restart(int offset) {
pushWordToStack(pc);
pc = offset;
return 16;
}
/**
* RET C
*
* Return if following condition is true
*
*/
private int retC(int opcode) {
int flags = registers.getReg(F);
switch(opcode) {
case 0xc0:
if (!isSet(flags, ZERO_F)) {
return 4 + ret();
}
break;
case 0xc8:
if (isSet(flags, ZERO_F)) {
return 4 + ret();
}
break;
case 0xd0:
if (!isSet(flags, CARRY_F)) {
return 4 + ret();
}
break;
case 0xd8:
if (isSet(flags, CARRY_F)) {
return 4 + ret();
}
break;
default:
break;
}
return 8;
}
/**
* RCLA
*
* Rotate A left, Old bit 7 to Carry flag
*
* Flags
* Z - Reset
* H,N - Reset
* C - Contains old bit 7 data
*
*/
private int rlcA() {
int reg = registers.getReg(GBRegisters.Reg.A);
int msb = (reg & 0x80) >> 7;
// rotate left
reg = reg << 1;
// set lsb to previous msb
reg |= msb;
registers.resetAll();
if (msb == 0x1) {
registers.setC();
}
registers.setReg(A, reg);
return 4;
}
/**
* RLA
* Rotate A left through Carry Flag
*
* Flags Affected:
* Z - reset
* N,H - Reset
* C - contains old bit 7 data
*
*/
private int rlA() {
int reg = registers.getReg(A);
int flags = registers.getReg(F);
// rotate left
reg = reg << 1;
// set lsb to FLAG C
reg |= (flags & 0x10) >> 4;
registers.resetAll();
if ((reg & 0x100) == 0x100) {
registers.setC();
}
registers.setReg(A, reg);
return 4;
}
/**
* RRCA
*
* Rotate A right, Old bit 0 to Carry flag
*
* Flags
* Z - Reset
* H,N - Reset
* C - Contains old bit 0 data
*
*/
private int rrcA() {
int reg = registers.getReg(GBRegisters.Reg.A);
int lsb = reg & 0x1;
// rotate right
reg = reg >> 1;
// set msb to previous lsb
reg |= lsb << 7;
registers.resetAll();
if (lsb == 1) {
registers.setC();
}
registers.setReg(A, reg);
return 4;
}
/**
* RLC n
*
* Rotate n left. Old bit 7 to carry flag
*
* Flags:
* Z - set if result is zero
* N - Reset
* H - Reset
* C - Contains old bit 7 data
*
*/
private int rlcN(GBRegisters.Reg src) {
int data;
int cycles;
if (src == HL) {
data = memory.readByte(registers.getReg(src));
cycles = 16;
} else {
data = registers.getReg(src);
cycles = 8;
}
int msb = (data & 0x80) >> 7;
data = data << 1;
data |= msb;
registers.resetAll();
if (data == 0) {
registers.setZ();
}
if (msb == 1) {
registers.setC();
}
if (src == HL) {
memory.writeByte(registers.getReg(src), data);
} else {
registers.setReg(src, data);
}
return cycles;
}
/**
* RL n
*
* Rotate n left through carry flag
*
* Flags:
* Z - set if result is zero
* N - Reset
* H - Reset
* C - Contains old bit 7 data
*/
private int rlN(GBRegisters.Reg src) {
int data;
int cycles;
int flags = registers.getReg(F);
if (src == HL) {
data = memory.readByte(registers.getReg(src));
cycles = 16;
} else {
data = registers.getReg(src);
cycles = 8;
}
int msb = ((data & 0x80) >> 7) & 0x1;
int carryIn = isSet(flags, CARRY_F) ? 1 : 0;
data = (data << 1 | carryIn) & 0xff;
registers.resetAll();
if (data == 0) {
registers.setZ();
}
if (msb != 0) {
registers.setC();
}
if (src == HL) {
memory.writeByte(registers.getReg(src), data);
} else {
registers.setReg(src, data);
}
return cycles;
}
/**
* RrCn n
*
* Rotate n Right. Old bit 0 to carry flag
*
* Flags:
* Z - set if result is zero
* N - Reset
* H - Reset
* C - Contains old bit 0 data
*
*/
private int rrcN(GBRegisters.Reg src) {
int data;
int cycles;
if (src == GBRegisters.Reg.HL) {
data = memory.readByte(registers.getReg(src));
cycles = 16;
} else {
data = registers.getReg(src);
cycles = 8;
}
int lsb = data & 0x1;
data = data >> 1;
data |= lsb << 7;
registers.resetAll();
if (data == 0) {
registers.setZ();
}
if (lsb == 1) {
registers.setC();
}
if (src == GBRegisters.Reg.HL) {
memory.writeByte(registers.getReg(src), data);
} else {
registers.setReg(src, data);
}
return cycles;
}
/**
* RR n
*
* Rotate n right through carry flag
*
* 0x1f (rra is only 4 cycles)
* Flags:
* Z - Reset
* N - Reset
* H - Reset
* C - Contains old bit 0 data
*/
private int rrN(GBRegisters.Reg src, boolean setZeroFlag) {
int data;
int cycles;
int flags = registers.getReg(F);
if (src == HL) {
data = memory.readByte(registers.getReg(src));
cycles = 16;
} else {
data = registers.getReg(src);
cycles = 8;
}
int lsb = data & 0x1;
int carryIn = isSet(flags, CARRY_F) ? 1 : 0;
data = (data >> 1) | (carryIn << 7);
data &= 0xff;
registers.resetAll();
if (setZeroFlag && data == 0) {
registers.setZ();
}
if (lsb != 0) {
registers.setC();
}
if (src == HL) {
memory.writeByte(registers.getReg(src), data);
} else {
registers.setReg(src, data);
}
return (setZeroFlag) ? 4 : cycles;
}
/**
* Shift n left into Carry, lsb of n set to 0
*
* Flags
* Z - set if 0
* H, N - reset
* C - contains old bit 7 data
*/
private int slAN(GBRegisters.Reg reg) {
int cycles;
int data;
if (reg == GBRegisters.Reg.HL) {
data = memory.readByte(registers.getReg(reg));
cycles = 16;
} else {
data = registers.getReg(reg);
cycles = 8;
}
int msb = (data & 0x80) & 0xff;
data = (data << 1) & 0xff;
registers.resetAll();
if (data == 0) {
registers.setZ();
}
if (msb != 0) {
registers.setC();
}
if (reg == GBRegisters.Reg.HL) {
memory.writeByte(registers.getReg(reg), data);
} else {
registers.setReg(reg, data);
}
return cycles;
}
/**
* SRA n/SRL n
*
* Shift n right into carry, sign extended if SRA, unsigned if SRL
*
* Z - set if result is zero
* N,H - reset
* C - contains old bit 0 data
* @param unsignedShift if true SRL, if false SRA
*/
private int srAL(GBRegisters.Reg reg, boolean unsignedShift) {
int cycles;
int data;
if (reg == HL) {
data = memory.readByte(registers.getReg(reg));
cycles = 16;
} else {
data = registers.getReg(reg);
cycles = 8;
}
int lsb = data & 0x1;
if (unsignedShift) {
data = data >> 1;
if (isSet(data, 7)) {
data = data & 0x3f;
}
} else {
int bit7 = data & 0x80;
data = data >> 1;
data |= bit7;
}
registers.resetAll();
if (data == 0) {
registers.setZ();
}
if (lsb == 1) {
registers.setC();
}
if (reg == GBRegisters.Reg.HL) {
memory.writeByte(registers.getReg(reg), data);
} else {
registers.setReg(reg, data);
}
return cycles;
}
/**
* Prints the contents of the registers to STDOUT
*
*
*/
public void dumpRegisters(int opcode) {
System.out.println("A: 0x" + Integer.toHexString(registers.getReg(A)));
System.out.println("B: 0x" + Integer.toHexString(registers.getReg(B)));
System.out.println("C: 0x" + Integer.toHexString(registers.getReg(C)));
System.out.println("D: 0x" + Integer.toHexString(registers.getReg(D)));
System.out.println("E: 0x" + Integer.toHexString(registers.getReg(E)));
System.out.println("F: 0x" + Integer.toHexString(registers.getReg(F)));
System.out.println("H: 0x" + Integer.toHexString(registers.getReg(H)));
System.out.println("L: 0x" + Integer.toHexString(registers.getReg(L)));
System.out.println("PC: 0x" + Integer.toHexString(pc));
System.out.println("SP: 0x" + Integer.toHexString(sp));
}
/**
* Test bit b in register r
*
* Flags affected:
* Z - set if bit b of register r is 0
* N - reset
* H - set
* C - not affected
*
* @param bit bit number to check
* @param reg register to check
*
*/
private int bitBR(int bit, GBRegisters.Reg reg) {
int data;
int cycles;
if (reg == HL) {
data = memory.readByte(registers.getReg(reg));
cycles = 16;
} else {
data = registers.getReg(reg);
cycles = 8;
}
registers.resetZ();
if (!isSet(data, bit)) {
registers.setZ();
}
registers.setH();
registers.resetN();
return cycles;
}
/**
* isSet
*
* Tests the num if the bitNum bit is set
*
* @param num number to test
* @param bitNum bitnumber to test
*/
private boolean isSet(int num, int bitNum) {
return (((num >> bitNum) & 0x1) == 1);
}
/**
* Set bit bitNum in reg to val
*
* @param val value to set
* @param bitNum bit to set
* @param reg register to set
*/
private int setBR(int val, int bitNum, GBRegisters.Reg reg) {
if (reg == GBRegisters.Reg.HL) {
int data = memory.readByte(registers.getReg(reg));
data = setBit(val, bitNum, data);
memory.writeByte(registers.getReg(reg), data);
return 16;
} else {
int data = registers.getReg(reg);
data = setBit(val, bitNum, data);
registers.setReg(reg, data);
return 8;
}
}
/**
* sets bit bitNum to val in num
*/
private int setBit(int val, int bitNum, int num) {
if (val == 1) {
return num | 1 << bitNum;
} else {
return num & ~(1 << bitNum);
}
}
/**
* updateDivideRegister
*
* updates the divide register
* ASSUMES CLOCKSPEED OF 4194304
* TODO
* @param cycles (clock cycles passed this instruction)
*/
private void updateDivideRegister(int cycles) {
divideCounter += cycles;
if (divideCounter >= 0xff) {
divideCounter = 0;
memory.incrementDivider();
}
}
/**
* updateTimers
*
* updates the CPU timers in memory
* @param cycles number of cycles that have passed
*/
private void updateTimers(int cycles) {
//check the enable
if (!isSet(memory.readByte(0xff07), 2)) {
return;
}
timerCounter -= cycles;
//update the counter in memory
while (timerCounter <= 0) {
timerCounter += getCountFrequency();
memory.incrementTIMA();
if (memory.readByte(0xff05) == 0x0) {
memory.resetTIMA();
requestInterrupt(0x2);
}
}
}
/**
* returns the counting frequency of the timer in memory
*
* checks the timer controller register 0xff07
* and returns the appropriate clock cycle update
*/
private int getCountFrequency() {
int freq = memory.readByte(0xff07) & 0x3;
switch (freq) {
case 0: return 1024;
case 1: return 16;
case 2: return 64;
case 3: return 256;
default: return 256;
}
}
/**
* requests an interrupt to be serviced by the CPU
*
* id can be:
* 0 - V-Blank interrupt
* 1 - LCD Timer interrupt
* 2 - Timer interrupt
* 3 - (Serial) Not handled NOTE: TODO
* 4 - Joypad interrupt
*
* 0xff0f - IF Interrupt Flag
* 0xffff - IE Interrupt Enable
*
* @param id interrupt to request
*/
public void requestInterrupt(int id) {
int flags = memory.readByte(0xff0f);
flags = setBit(1, id, flags);
memory.writeByte(0xff0f, flags);
}
/**
* Checks interrupts and services them if required
*/
private void checkInterrupts() {
if (interruptState != ENABLED) {
return; //IME flag not set
}
int interruptFlag = memory.readByte(0xff0f);
int interruptEnable = memory.readByte(0xffff);
if (interruptFlag > 0 && interruptEnable > 0) {
for (int i = 0; i < 5; ++i) {
if (isSet(interruptFlag, i) && isSet(interruptEnable, i)) {
handleInterrupt(i);
}
}
}
}
/**
* Handles the interrupt
*
* id can be:
* 0 - V-Blank interrupt
* 1 - LCD Timer interrupt
* 2 - Timer interrupt
* 4 - Joypad interrupt
*
* @param id interrupt to handle
*/
private void handleInterrupt(int id) {
//clear IME flag
interruptState = DISABLED;
//reset the interrupt bit
int flags = memory.readByte(0xff0f);
flags = setBit(0, id, flags);
memory.writeByte(0xff0f, flags);
pushWordToStack(pc);
switch (id) {
case 0: pc = 0x40;
break;
case 1: pc = 0x48;
break;
case 2: pc = 0x50;
break;
case 3: System.err.println("Requested a Serial interrupt...");
break;
case 4: pc = 0x60;
break;
default: System.err.println("Invalid Interrupt Requested. Exiting");
System.exit(1);
}
}
/**
* DI
*
* disables interrupts
*/
private int disableInterrupts() {
interruptState = DELAY_OFF;
return 4;
}
/**
* EI
*
* enables interrupts
*
* TODO read one more opcode??
*/
private int enableInterrupts() {
interruptState = DELAY_ON;
return 4;
}
/**
* waits until a button is pressed
*
*TODO doesn't work
*/
private int stop() {
System.out.println("STOPPED!!!!");
isStopped = true;
pc++;
return 4;
}
/**
* resumes cpu if stopped
*
*
*/
public void resume() {
isStopped = false;
}
/**
* reads a 16 bit word from
* memory in little endian order
* (least significant byte first)
* located at address
*
* @param address to read from
* @return 16bit word from memory
*/
private int readWordFromMem(int address) {
int data = memory.readByte(address);
data = (memory.readByte(address + 1) << 8) | data;
return data;
}
/**
* writes a 16 bit word to address in memory
* at sp, decrements stack pointer twice
*
*
* @param word to write to memory
*/
private void writeWordToMem(int word) {
sp
memory.writeByte(sp, (word & 0xff00) >> 8);
sp
memory.writeByte(sp, word & 0xff);
}
}
|
package me.zzp.ar;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import me.zzp.ar.ex.IllegalFieldNameException;
import me.zzp.ar.ex.SqlExecuteException;
import me.zzp.ar.sql.SqlBuilder;
import me.zzp.ar.sql.TSqlBuilder;
import me.zzp.util.Seq;
public final class Table {
final DB dbo;
final String name;
final Map<String, Integer> columns;
final Map<String, Association> relations;
final String primaryKey;
private String foreignTable;
private final Map<String, Integer> foreignKeys = new HashMap<String, Integer>();
Table(DB dbo, String name, Map<String, Integer> columns, Map<String, Association> relations) {
this.dbo = dbo;
this.name = name;
this.columns = columns;
this.relations = relations;
this.primaryKey = name.concat(".id");
}
public Map<String, Integer> getColumns() {
return Collections.unmodifiableMap(columns);
}
/* Association */
private Association assoc(String name, boolean onlyOne, boolean ancestor) {
name = DB.parseKeyParameter(name);
Association assoc = new Association(relations, name, onlyOne, ancestor);
relations.put(name, assoc);
return assoc;
}
public Association belongsTo(String name) {
return assoc(name, true, false);
}
public Association hasOne(String name) {
return assoc(name, true, true);
}
public Association hasMany(String name) {
return assoc(name, false, true);
}
public Association hasAndBelongsToMany(String name) {
return assoc(name, false, false);
}
private String[] getForeignKeys() {
List<String> conditions = new ArrayList<String>();
for (Map.Entry<String, Integer> e : foreignKeys.entrySet()) {
conditions.add(String.format("%s.%s = %d", name, e.getKey(), e.getValue()));
}
return conditions.toArray(new String[0]);
}
public Table constrain(String key, int id) {
foreignKeys.put(DB.parseKeyParameter(key), id);
return this;
}
public Table join(String table) {
this.foreignTable = table;
return this;
}
/* CRUD */
public Record create(Object... args) {
Map<String, Object> data = new HashMap<String, Object>();
data.putAll(foreignKeys);
for (int i = 0; i < args.length; i += 2) {
String key = DB.parseKeyParameter(args[i].toString());
if (!columns.containsKey(key)) {
throw new IllegalFieldNameException(key);
}
Object value = args[i + 1];
data.put(key, value);
}
String[] fields = new String[data.size() + 2];
int[] types = new int[data.size() + 2];
Object[] values = new Object[data.size() + 2];
int index = 0;
for (Map.Entry<String, Object> e : data.entrySet()) {
fields[index] = e.getKey();
types[index] = columns.get(e.getKey());
values[index] = e.getValue();
index++;
}
Seq.assignAt(fields, Seq.array(-2, -1), "created_at", "updated_at");
Seq.assignAt(types, Seq.array(-2, -1), Types.TIMESTAMP, Types.TIMESTAMP);
Seq.assignAt(values, Seq.array(-2, -1), DB.now(), DB.now());
SqlBuilder sql = new TSqlBuilder();
sql.insert().into(name).values(fields);
PreparedStatement call = dbo.prepare(sql.toString(), values, types);
try {
int id = 0;
if (call.executeUpdate() > 0) {
ResultSet rs = call.getGeneratedKeys();
if (rs != null && rs.next()) {
id = rs.getInt(1);
rs.close();
}
}
call.close();
return id > 0 ? find(id) : null;
} catch (SQLException e) {
throw new SqlExecuteException(sql.toString(), e);
}
}
/**
* RecordRecord.
*
* @param o Record
* @return Record
*/
public Record create(Record o) {
List<Object> params = new LinkedList<Object>();
for (String key : columns.keySet()) {
if (!foreignKeys.containsKey(key)) {
params.add(key);
params.add(o.get(key));
}
}
return create(params.toArray());
}
public void update(Record record) {
String[] fields = new String[columns.size() + 1];
int[] types = new int[columns.size() + 1];
Object[] values = new Object[columns.size() + 1];
int index = 0;
for (String column : columns.keySet()) {
fields[index] = column;
types[index] = columns.get(column);
values[index] = record.get(column);
index++;
}
fields[columns.size()] = "updated_at";
types[columns.size()] = Types.TIMESTAMP;
values[columns.size()] = DB.now();
SqlBuilder sql = new TSqlBuilder();
sql.update(name).set(fields).where(String.format("%s = %d", primaryKey, record.getInt("id")));
dbo.execute(sql.toString(), values, types);
}
public void delete(Record record) {
int id = record.get("id");
SqlBuilder sql = new TSqlBuilder();
sql.delete().from(name).where(String.format("%s = %d", primaryKey, id));
dbo.execute(sql.toString());
}
public void purge() {
// TODO: need enhancement
for (Record record : all()) {
delete(record);
}
}
List<Record> query(SqlBuilder sql, Object... args) {
List<Record> records = new LinkedList<Record>();
ResultSet rs = dbo.query(sql.toString(), args);
try {
ResultSetMetaData meta = rs.getMetaData();
while (rs.next()) {
Map<String, Object> values = new LinkedHashMap<String, Object>();
for (int i = 1; i <= meta.getColumnCount(); i++) {
String label = DB.parseKeyParameter(meta.getColumnLabel(i));
values.put(label, rs.getObject(label));
}
records.add(new Record(this, values));
}
Statement call = rs.getStatement();
rs.close();
call.close();
} catch (SQLException e) {
throw new SqlExecuteException(sql.toString(), e);
}
return records;
}
public Query select(String... columns) {
Query sql = new Query(this);
if (columns == null || columns.length == 0) {
sql.select(String.format("%s.*", name));
} else {
sql.select(columns);
}
sql.from(name);
if (foreignTable != null && !foreignTable.isEmpty()) {
sql.join(foreignTable);
}
if (!foreignKeys.isEmpty()) {
for (String condition : getForeignKeys()) {
sql.where(condition);
}
}
return sql.orderBy(primaryKey);
}
public Record first() {
return select().limit(1).one();
}
public Record first(String condition, Object... args) {
return select().where(condition, args).limit(1).one();
}
public Record last() {
return select().orderBy(primaryKey.concat(" desc")).limit(1).one();
}
public Record last(String condition, Object... args) {
return select().where(condition, args).orderBy(primaryKey.concat(" desc")).limit(1).one();
}
public Record find(int id) {
return first(primaryKey.concat(" = ?"), id);
}
/**
* .
* @param key
* @param value
* @return
*/
public Record findA(String key, Object value) {
key = DB.parseKeyParameter(key);
if (value != null) {
return first(key.concat(" = ?"), value);
} else {
return first(key.concat(" is null"));
}
}
public List<Record> findBy(String key, Object value) {
key = DB.parseKeyParameter(key);
if (value != null) {
return where(key.concat(" = ?"), value);
} else {
return where(key.concat(" is null"));
}
}
public List<Record> all() {
return select().all();
}
public List<Record> where(String condition, Object... args) {
return select().where(condition, args).all();
}
public List<Record> paging(int page, int size) {
return select().limit(size).offset(page * size).all();
}
}
|
package fitnesse.wiki;
import java.util.Collection;
import java.util.List;
/**
* A wiki page. Wiki pages can have children, are versioned and are transactional.
*/
public interface WikiPage extends Comparable<WikiPage> {
/**
* @return the parent of this page. If the page is the root page, returns itself.
*/
WikiPage getParent();
/**
* @return True if this page is the wiki root.
*/
boolean isRoot();
/**
* Create a child page with a given name. Data should still be committed (see {@link #commit(PageData)})
* for the page to be persisted.
*
* @param name new page name
* @return a new wiki page.
*/
WikiPage addChildPage(String name);
boolean hasChildPage(String name);
WikiPage getChildPage(String name);
/**
* Deprecated. Use WikiPage.remove() instead.
*
* @param name change page's name
*/
@Deprecated
void removeChildPage(String name);
/**
* Remove this page.
*/
void remove();
/**
* Get child pages for this wiki page
*
* @return children, an empty list if there are none.
*/
List<WikiPage> getChildren();
String getName();
PageData getData();
/**
* Get a list/set of version info
*
* @return a collection, never null.
*/
Collection<VersionInfo> getVersions();
WikiPage getVersion(String versionName);
String getHtml();
/**
* Commit new content
*
* @param data PageData to commit
* @return version information about this new data version, may be null.
*/
VersionInfo commit(PageData data);
PageCrawler getPageCrawler();
String getVariable(String name);
}
|
package foam.dao;
import foam.core.FObject;
import foam.core.X;
import foam.mlang.order.Comparator;
import foam.mlang.predicate.Predicate;
import foam.nanos.pm.PM;
public class PipelinePMDAO
extends ProxyDAO
{
protected String putName_;
protected String findName_;
protected String removeName_;
protected String removeAllName_;
protected String delegateName_;
public PipelinePMDAO(X x, DAO delegate) {
super(x, delegate);
delegateName_ = getDelegate().getClass().getName();
init();
}
void init() {
createPipeline();
putName_ = delegateName_ + ":pipePut";
findName_ = delegateName_ + ":pipeFind";
removeName_ = delegateName_ + ":pipeRemove";
removeAllName_ = delegateName_ + ":pipeRemoveAll";
}
private void createPipeline() {
DAO delegate = getDelegate();
DAO secondaryDelegate;
if ( delegate instanceof ProxyDAO ) {
secondaryDelegate = ((ProxyDAO) delegate).getDelegate();
((ProxyDAO) delegate).setDelegate(new EndPipelinePMDAO(getX(), secondaryDelegate));
delegate = ((ProxyDAO) delegate).getDelegate();
if ( secondaryDelegate instanceof ProxyDAO ) {
((ProxyDAO) delegate).setDelegate(new PipelinePMDAO(getX(), secondaryDelegate));
}
}
}
private void createPM(String name) {
PM pm = new PM();
pm.setClassType(PipelinePMDAO.getOwnClassInfo());
pm.setName(name);
X pipeX = getX().put("pipePmStart", pm);
}
@Override
public FObject put_(X x, FObject obj) {
createPM(putName_);
return super.put_(pipeX, obj);
}
@Override
public FObject find_(X x, Object id) {
createPM(findName_);
return super.find_(pipeX, id);
}
@Override
public FObject remove_(X x, FObject obj) {
createPM(removeName_);
return super.remove_(pipeX, obj);
}
@Override
public void removeAll_(X x, long skip, long limit, Comparator order, Predicate predicate) {
createPM(removeAllName_);
super.removeAll_(pipeX, skip, limit, order, predicate);
}
public class EndPipelinePMDAO extends ProxyDAO {
public EndPipelinePMDAO(X x, DAO delegate) {
super(x, delegate);
}
@Override
public FObject put_(X x, FObject obj) {
((PM) getX().get("pipePmStart")).log(x);
return super.put_(x, obj);
}
@Override
public FObject find_(X x, Object id) {
((PM) getX().get("pipePmStart")).log(x);
return super.find_(x, id);
}
@Override
public FObject remove_(X x, FObject obj) {
((PM) getX().get("pipePmStart")).log(x);
return super.remove_(x, obj);
}
@Override
public void removeAll_(X x, long skip, long limit, Comparator order, Predicate predicate) {
((PM) getX().get("pipePmStart")).log(x);
super.removeAll_(x, skip, limit, order, predicate);
}
}
}
|
package gameEngine;
import gameEngine.actors.BaseTower;
import java.util.ArrayList;
import java.util.List;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.util.Duration;
import utilities.GSON.DataWrapper;
import utilities.chatroom.Chatroom;
import utilities.networking.HTTPConnection;
public class CoOpManager extends SingleThreadedEngineManager {
private static final String GET_PLAYERS = "get_num_players";
private static final String GET_MASTER_JSON = "get_master_json";
private static final String UPDATE_MASTER_JSON = "update_master_json";
private static final String MASTER_JSON = "master_json=";
private static final String GAME_DIRECTORY = "game_directory=";
private static final String MAKE_GAME = "make_game";
private static final String SERVER_URL = "https://voogasalad.herokuapp.com/";
private static final String JOIN_GAME = "join_game";
private static final int REQUIRED_NUM_PLAYERS = 2;
private static final HTTPConnection HTTP_CONNECTOR = new HTTPConnection(SERVER_URL);
private static final int TIMER_END = 30;
private static final double QUERY_SERVER_TIME = 1.0;
private DoubleProperty myTimer;
private boolean myInteraction;
private String myDirectory;
public CoOpManager () {
super();
myDirectory = "";
myTimer = new SimpleDoubleProperty();
}
public void startNewGame (String directory) {
myDirectory = directory;
HTTP_CONNECTOR.sendPost(MAKE_GAME, GAME_DIRECTORY + directory);
}
public boolean isReady () {
return Integer.parseInt(HTTP_CONNECTOR.sendGet(GET_PLAYERS)) >= REQUIRED_NUM_PLAYERS;
}
public DoubleProperty getTimer(){
return myTimer;
}
public boolean joinGame () {
myDirectory = HTTP_CONNECTOR.sendPost(JOIN_GAME, "");
return !myDirectory.equals("None");
}
public String initializeGame (Pane engineGroup) {
addGroups(engineGroup);
super.initializeGame(myDirectory);
new Chatroom();
allowInteraction();
return myDirectory;
}
private void allowInteraction () {
myTimer.set(30);
Timeline timeline = new Timeline();
timeline.setCycleCount(TIMER_END);
timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(QUERY_SERVER_TIME),
event -> getTowersFromServer()));
timeline.setOnFinished(event -> startLevel());
timeline.play();
}
@Override
public void changeRunSpeed(double d){
// nothing
}
private void startLevel () {
getTowersFromServer();
myTimer.set(0);
super.resume();
}
@Override
protected void onLevelEnd () {
super.onLevelEnd();
allowInteraction();
}
private void writeTowersToServer () {
HTTP_CONNECTOR.sendPost(UPDATE_MASTER_JSON, MASTER_JSON + convertTowersToString());
}
private String convertTowersToString () {
List<DataWrapper> wrapper = new ArrayList<>();
for (BaseTower tower : myTowerGroup) {
wrapper.add(new DataWrapper(tower));
}
return myFileWriter.convertWrappersToJson(wrapper);
}
private void getTowersFromServer () {
myTimer.set(myTimer.get()-QUERY_SERVER_TIME);
String response = HTTP_CONNECTOR.sendGet(GET_MASTER_JSON);
if(response.trim().equals("None")){
return;
}
List<DataWrapper> listFromServer = myFileReader.readWrappers(response);
for (BaseTower tower : myTowerGroup) {
if (!listFromServer.contains(new DataWrapper(tower))) {
myTowerGroup.addActorToRemoveBuffer(tower);
}
else {
listFromServer.remove(new DataWrapper(tower));
}
}
for (DataWrapper wrapper : listFromServer) {
super.addTower(wrapper.getName(), wrapper.getX(), wrapper.getY());
}
}
@Override
public void removeTower (ImageView node) {
if (myInteraction) {
getTowersFromServer();
super.removeTower(node);
writeTowersToServer();
}
}
@Override
public ImageView addTower (String name, double x, double y) {
if (myInteraction) {
getTowersFromServer();
ImageView ans = super.addTower(name, x, y);
writeTowersToServer();
return ans;
}
else {
return null;
}
}
}
|
package yuku.alkitab.yes2;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import yuku.afw.D;
import yuku.alkitab.base.model.Ari;
import yuku.alkitab.base.model.Book;
import yuku.alkitab.base.model.PericopeBlock;
import yuku.alkitab.base.model.SingleChapterVerses;
import yuku.alkitab.base.model.Version;
import yuku.alkitab.base.storage.BibleReader;
import yuku.alkitab.yes2.io.RandomInputStream;
import yuku.alkitab.yes2.io.Yes2VerseTextDecoder;
import yuku.alkitab.yes2.model.SectionIndex;
import yuku.alkitab.yes2.model.Yes2Book;
import yuku.alkitab.yes2.section.BooksInfoSection;
import yuku.alkitab.yes2.section.PericopesSection;
import yuku.alkitab.yes2.section.TextSection;
import yuku.alkitab.yes2.section.VersionInfoSection;
import yuku.bintex.BintexReader;
import yuku.bintex.ValueMap;
import yuku.snappy.codec.Snappy;
public class Yes2Reader implements BibleReader {
private static final String TAG = Yes2Reader.class.getSimpleName();
private RandomInputStream file_;
private SectionIndex sectionIndex_;
// cached in memory
private VersionInfoSection versionInfo_;
private PericopesSection pericopesSection_;
private TextSectionReader textSectionReader_;
static class Yes2SingleChapterVerses extends SingleChapterVerses {
private final String[] verses;
public Yes2SingleChapterVerses(String[] verses) {
this.verses = verses;
}
@Override public String getVerse(int verse_0) {
return verses[verse_0];
}
@Override public int getVerseCount() {
return verses.length;
}
}
static class SnappyInputStream extends InputStream {
private final Snappy snappy;
private final RandomInputStream file;
private final long baseOffset;
private final int[] compressed_block_sizes;
private final int[] compressed_block_offsets;
private int current_block_index;
private int current_block_skip;
private byte[] compressed_buf;
private int uncompressed_block_index = -1;
private byte[] uncompressed_buf;
private int uncompressed_len;
public SnappyInputStream(RandomInputStream file, long baseOffset, int block_size, int[] compressed_block_sizes, int[] compressed_block_offsets) {
this.snappy = new Snappy.Factory().newInstance();
this.file = file;
this.baseOffset = baseOffset;
this.compressed_block_sizes = compressed_block_sizes;
this.compressed_block_offsets = compressed_block_offsets;
if (compressed_buf == null || compressed_buf.length < snappy.maxCompressedLength(block_size)) {
compressed_buf = new byte[snappy.maxCompressedLength(block_size)];
}
if (uncompressed_buf == null || uncompressed_buf.length != block_size) {
uncompressed_buf = new byte[block_size];
}
}
public void prepareForRead(int current_block_index, int current_block_skip) throws IOException {
this.current_block_index = current_block_index;
this.current_block_skip = current_block_skip;
prepareBuffer();
}
private void prepareBuffer() throws IOException {
int block_index = current_block_index;
// if uncompressed_block_index is already equal to the requested block_index
// then we do not need to re-decompress again
if (uncompressed_block_index != block_index) {
file.seek(baseOffset + compressed_block_offsets[block_index]);
file.read(compressed_buf, 0, compressed_block_sizes[block_index]);
uncompressed_len = snappy.decompress(compressed_buf, 0, uncompressed_buf, 0, compressed_block_sizes[block_index]);
if (uncompressed_len < 0) {
throw new IOException("Error in decompressing: " + uncompressed_len);
}
uncompressed_block_index = block_index;
}
}
@Override public int read() throws IOException {
int can_read = uncompressed_len - current_block_skip;
if (can_read == 0) {
if (current_block_index >= compressed_block_sizes.length) {
return -1; // EOF
} else {
// need to move to the next block
current_block_index++;
current_block_skip = 0;
prepareBuffer();
}
}
int res = /* need to convert to uint8: */ 0xff & uncompressed_buf[current_block_skip];
current_block_skip++;
return res;
}
@Override public int read(byte[] buffer, int offset, int length) throws IOException {
int res = 0;
int want_read = length;
while (want_read > 0) {
int can_read = uncompressed_len - current_block_skip;
if (can_read == 0) {
if (current_block_index >= compressed_block_sizes.length) { // EOF
if (res == 0) return -1; // we didn't manage to read any
return res;
} else {
// need to move to the next block
current_block_index++;
current_block_skip = 0;
prepareBuffer();
can_read = uncompressed_len;
}
}
int will_read = want_read > can_read? can_read: want_read;
System.arraycopy(uncompressed_buf, current_block_skip, buffer, offset, will_read);
current_block_skip += will_read;
offset += will_read;
want_read -= will_read;
res += will_read;
}
return res;
}
}
/**
* This class simplify many operations regarding reading the verse texts from the yes file.
* This stores the offset to the beginning of text section content
* and also understands the text section attributes (compression, encryption etc.)
*/
static class TextSectionReader {
private RandomInputStream file_;
private final Yes2VerseTextDecoder decoder_;
private final long sectionContentOffset_;
private int block_size = 0; // 0 means no compression
private SnappyInputStream snappyInputStream;
private int[] compressed_block_sizes;
private int[] compressed_block_offsets;
public TextSectionReader(RandomInputStream file, Yes2VerseTextDecoder decoder, ValueMap sectionAttributes, long sectionContentOffset) throws Exception {
file_ = file;
decoder_ = decoder;
sectionContentOffset_ = sectionContentOffset;
if (sectionAttributes != null) {
String compressionName = sectionAttributes.getString("compression.name");
if (compressionName != null) {
if ("snappy-blocks".equals(compressionName)) {
int compressionVersion = sectionAttributes.getInt("compression.version", 0);
if (compressionVersion > 1) {
throw new Exception("Compression " + compressionName + " version " + compressionVersion + " is not supported");
}
ValueMap compressionInfo = sectionAttributes.getSimpleMap("compression.info");
block_size = compressionInfo.getInt("block_size");
compressed_block_sizes = compressionInfo.getIntArray("compressed_block_sizes");
{ // convert compressed_block_sizes into offsets
compressed_block_offsets = new int[compressed_block_sizes.length + 1];
int c = 0;
for (int i = 0, len = compressed_block_sizes.length; i < len; i++) {
compressed_block_offsets[i] = c;
c += compressed_block_sizes[i];
}
compressed_block_offsets[compressed_block_sizes.length] = c;
}
snappyInputStream = new SnappyInputStream(file_, sectionContentOffset, block_size, compressed_block_sizes, compressed_block_offsets);
} else {
throw new Exception("Compression " + compressionName + " is not supported");
}
}
}
}
public Yes2SingleChapterVerses loadVerseText(Yes2Book yes2Book, int chapter_1, boolean dontSeparateVerses, boolean lowercase) throws Exception {
int contentOffset = yes2Book.offset;
contentOffset += yes2Book.chapter_offsets[chapter_1 - 1];
BintexReader br;
if (block_size != 0) { // compressed!
int block_index = contentOffset / block_size;
int block_skip = contentOffset % block_size;
if (D.EBUG) {
Log.d(TAG, "want to read contentOffset=" + contentOffset + " but compressed");
Log.d(TAG, "so going to block " + block_index + " where compressed offset is " + compressed_block_offsets[block_index]);
Log.d(TAG, "skipping " + block_skip + " uncompressed bytes");
}
snappyInputStream.prepareForRead(block_index, block_skip);
br = new BintexReader(snappyInputStream);
} else {
file_.seek(sectionContentOffset_ + contentOffset);
br = new BintexReader(file_);
}
int verse_count = yes2Book.verse_counts[chapter_1 - 1];
if (dontSeparateVerses) {
return new Yes2SingleChapterVerses(new String[] {
decoder_.makeIntoSingleString(br, verse_count, lowercase),
});
} else {
return new Yes2SingleChapterVerses(decoder_.separateIntoVerses(br, verse_count, lowercase));
}
}
}
public Yes2Reader(RandomInputStream input) {
this.file_ = input;
}
/** Read section index */
private synchronized void loadSectionIndex() throws Exception {
if (sectionIndex_ != null) { // we have read it previously.
return;
}
file_.seek(0);
{ // check header
byte[] buf = new byte[8];
file_.read(buf);
if (!Arrays.equals(buf, new byte[] { (byte) 0x98, 0x58, 0x0d, 0x0a, 0x00, 0x5d, (byte) 0xe0, 0x02 /* yes version 2 */})) {
throw new RuntimeException("YES2: Header is incorrect. Found: " + Arrays.toString(buf)); //$NON-NLS-1$
}
}
file_.seek(12); // start of sectionIndex
sectionIndex_ = SectionIndex.read(file_);
}
private synchronized void loadVersionInfo() throws Exception {
if (seekToSection("versionInfo")) {
versionInfo_ = new VersionInfoSection.Reader().read(file_);
}
}
private synchronized boolean seekToSection(String sectionName) throws Exception {
loadSectionIndex();
if (sectionIndex_ == null) {
Log.e(TAG, "@@seekToSection Could not load section index");
return false;
}
if (sectionIndex_.seekToSectionContent(sectionName, file_)) {
return true;
} else {
Log.e(TAG, "@@seekToSection Could not seek to section: " + sectionName);
return false;
}
}
@Override public String getShortName() {
try {
loadVersionInfo();
return versionInfo_.shortName;
} catch (Exception e) {
Log.e(TAG, "yes load version info error", e); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
@Override public String getLongName() {
try {
loadVersionInfo();
return versionInfo_.longName;
} catch (Exception e) {
Log.e(TAG, "yes load version info error", e); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
public String getDescription() {
try {
loadVersionInfo();
return versionInfo_.description;
} catch (Exception e) {
Log.e(TAG, "yes load version info error", e); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
@Override public Book[] loadBooks() {
try {
loadVersionInfo();
if (seekToSection(BooksInfoSection.SECTION_NAME)) {
BooksInfoSection section = new BooksInfoSection.Reader().read(file_);
List<Yes2Book> books = section.yes2Books;
return books.toArray(new Yes2Book[books.size()]);
}
Log.e(TAG, "no section named " + BooksInfoSection.SECTION_NAME); //$NON-NLS-1$
return null;
} catch (Exception e) {
Log.e(TAG, "loadBooks error", e); //$NON-NLS-1$
return null;
}
}
@Override public Yes2SingleChapterVerses loadVerseText(Book book, int chapter_1, boolean dontSeparateVerses, boolean lowercase) {
Yes2Book yes2Book = (Yes2Book) book;
try {
if (chapter_1 <= 0 || chapter_1 > yes2Book.chapter_count) {
return null;
}
if (textSectionReader_ == null) {
ValueMap sectionAttributes = sectionIndex_.getSectionAttributes(TextSection.SECTION_NAME, file_);
long sectionContentOffset = sectionIndex_.getAbsoluteOffsetForSectionContent(TextSection.SECTION_NAME);
// init text decoder
Yes2VerseTextDecoder decoder;
int textEncoding = versionInfo_.textEncoding;
if (textEncoding == 1) {
decoder = new Yes2VerseTextDecoder.Ascii();
} else if (textEncoding == 2) {
decoder = new Yes2VerseTextDecoder.Utf8();
} else {
Log.e(TAG, "Text encoding " + textEncoding + " not supported! Fallback to ascii."); //$NON-NLS-1$ //$NON-NLS-2$
decoder = new Yes2VerseTextDecoder.Ascii();
}
textSectionReader_ = new TextSectionReader(file_, decoder, sectionAttributes, sectionContentOffset);
}
return textSectionReader_.loadVerseText(yes2Book, chapter_1, dontSeparateVerses, lowercase);
} catch (Exception e) {
Log.e(TAG, "loadVerseText error", e); //$NON-NLS-1$
return null;
}
}
@Override public int loadPericope(Version version, int bookId, int chapter_1, int[] aris, PericopeBlock[] blocks, int max) {
try {
loadVersionInfo();
if (versionInfo_.hasPericopes == 0) {
return 0;
}
if (pericopesSection_ == null) { // not yet loaded!
if (seekToSection(PericopesSection.SECTION_NAME)) {
pericopesSection_ = new PericopesSection.Reader().read(file_);
} else {
return 0;
}
}
if (pericopesSection_ == null) {
Log.e(TAG, "Didn't succeed in loading pericopes section");
return 0;
}
int ariMin = Ari.encode(bookId, chapter_1, 0);
int ariMax = Ari.encode(bookId, chapter_1 + 1, 0);
return pericopesSection_.getPericopesForAris(ariMin, ariMax, aris, blocks, max);
} catch (Exception e) {
Log.e(TAG, "General exception in loading pericope block", e); //$NON-NLS-1$
return 0;
}
}
}
|
package com.racoon.ampache;
import java.io.Serializable;
/**
* @author Daniel Schruhl
*
*/
public class Playlist implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String owner;
private String items;
private String type;
public Playlist() {
// TODO Auto-generated constructor stub
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the owner
*/
public String getOwner() {
return owner;
}
/**
* @param owner the owner to set
*/
public void setOwner(String owner) {
this.owner = owner;
}
/**
* @return the items
*/
public String getItems() {
return items;
}
/**
* @param items the items to set
*/
public void setItems(String items) {
this.items = items;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(String type) {
this.type = type;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return name;
}
}
|
package taskDo;
import org.joda.time.DateTime;
/*
* @author Paing Zin Oo(Jack)
*/
public class Task implements Comparable<Task>{
private final int INCREMENT = 1;
private static int lastTaskId = 0;
private int id;
private String category;
private String title;
private String note;
private boolean important;
private DateTime dueDate;
private DateTime startDate;
private boolean completed;
private TaskType type;
public Task( String category, String description,
boolean important, DateTime dueDate, DateTime startDate,
boolean completed) {
super();
lastTaskId++;
this.id = lastTaskId+INCREMENT;
this.category = category;
this.title = description;
this.important = important;
this.dueDate = dueDate;
this.startDate = startDate;
this.completed = completed;
}
public Task(){
lastTaskId++;
this.id = lastTaskId+INCREMENT;
this.title = "";
this.type = TaskType.TODO;
this.category = "Others";
}
public Task(String description){
this.title = description;
}
public static int getLastTaskId(){
return lastTaskId;
}
//for testing only
public Task (DateTime dueDate){
this.id=lastTaskId+1;
lastTaskId++;
this.dueDate = dueDate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isImportant() {
return important;
}
public void setImportant(boolean important) {
this.important = important;
}
public DateTime getDueDate() {
return dueDate;
}
public void setDueDate(DateTime dueDate) {
this.dueDate = dueDate;
}
public DateTime getStartDate() {
return startDate;
}
public void setStartDate(DateTime startDate) {
this.startDate = startDate;
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
public TaskType getTaskType() {
return this.type;
}
public void setTaskType(TaskType taskType) {
this.type = taskType;
}
public String getNote() {
return this.note;
}
public void setNote(String taskNote) {
this.note = taskNote;
}
public String toString() {
return "ID" + this.id + "[Catogory: "+ this.getCategory()+ " Task:"
+this.getTitle();
}
@Override
public int compareTo(Task task) {
if (getDueDate() == null || task.getDueDate() == null){
return -1;
}
return getDueDate().compareTo(task.getDueDate());
}
}
|
package ucar.nc2.iosp.grid;
import ucar.nc2.*;
import ucar.nc2.iosp.AbstractIOServiceProvider;
import ucar.nc2.constants._Coordinate;
import ucar.nc2.constants.FeatureType;
import ucar.nc2.dt.fmr.FmrcCoordSys;
import ucar.nc2.units.DateFormatter;
import ucar.nc2.util.CancelTask;
import ucar.grid.*;
import ucar.grib.grib2.Grib2GridTableLookup;
import java.io.*;
import java.util.*;
public class GridIndexToNC {
/**
* logger
*/
static private org.slf4j.Logger logger =
org.slf4j.LoggerFactory.getLogger(GridIndexToNC.class);
/**
* map of horizontal coordinate systems
*/
private HashMap hcsHash = new HashMap(10); // GridHorizCoordSys
/**
* date formattter
*/
private DateFormatter formatter = new DateFormatter();
/**
* debug flag
*/
private boolean debug = false;
/**
* flag for using GridParameter description for variable names
*/
private boolean useDescriptionForVariableName = true;
//TODO: how to make format specific names if these are static
/**
* Make the level name
*
* @param gr grid record
* @param lookup lookup table
* @return name for the level
*/
public static String makeLevelName(GridRecord gr, GridTableLookup lookup) {
String vname = lookup.getLevelName(gr);
boolean isGrib1 = true; // same for GEMPAK //TODO:
if (isGrib1) {
return vname;
}
// for grib2, we need to add the layer to disambiguate
return lookup.isLayer(gr)
? vname + "_layer"
: vname;
}
/**
* Make the ensemble name
*
* @param gr grid record
* @param lookup lookup table
* @return name for the level
*/
public static String makeEnsembleName(GridRecord gr, GridTableLookup lookup) {
if (!lookup.getGridType().equals("GRIB2"))
return "";
Grib2GridTableLookup g2lookup = (Grib2GridTableLookup) lookup;
if (!g2lookup.isEnsemble(gr)) {
return "";
}
int productDef = g2lookup.getProductDefinition(gr);
if (productDef == 2) {
// Grib 2 table 4.7
// 0 Unweighted Mean of All Members
// 1 Weighted Mean of All Members
// 2 Standard Deviation with respect to Cluster Mean
// 3 Standard Deviation with respect to Cluster Mean, Normalized
// 4 Spread of All Members
// 5 Large Anomaly Index of All Members (see note below)
// 6 Unweighted Mean of the Cluster Members
int ensemble = g2lookup.getTypeGenProcess(gr);
String ensembleS;
if (ensemble < 41000) {
ensembleS = "unweightedMean" + Integer.toString(ensemble - 40000);
} else if (ensemble < 42000) {
ensembleS = "weightedMean" + Integer.toString(ensemble - 41000);
} else if (ensemble < 43000) {
ensembleS = "stdDev" + Integer.toString(ensemble - 42000);
} else if (ensemble < 44000) {
ensembleS = "stdDevNor" + Integer.toString(ensemble - 43000);
} else if (ensemble < 45000) {
ensembleS = "spread" + Integer.toString(ensemble - 44000);
} else if (ensemble < 46000) {
ensembleS = "anomaly" + Integer.toString(ensemble - 45000);
} else {
ensembleS = "unweightedMeanCluster" + Integer.toString(ensemble - 46000);
}
return ensembleS;
}
return "";
}
/**
* Make the variable name
*
* @param gr grid record
* @param lookup lookup table
* @return variable name
*/
public String makeVariableName(GridRecord gr, GridTableLookup lookup) {
GridParameter param = lookup.getParameter(gr);
String levelName = makeLevelName(gr, lookup);
String ensembleName = makeEnsembleName(gr, lookup);
String paramName = (useDescriptionForVariableName)
? param.getDescription()
: param.getName();
paramName = (ensembleName.length() == 0)
? paramName : paramName + "_" + ensembleName;
paramName = (levelName.length() == 0)
? paramName : paramName + "_" + levelName;
return paramName;
}
/**
* TODO: moved to GridVariable = made sense since it knows what it is
* Make a long name for the variable
*
* @param gr grid record
* @param lookup lookup table
*
* @return long variable name
public static String makeLongName(GridRecord gr, GridTableLookup lookup) {
GridParameter param = lookup.getParameter(gr);
String levelName = makeLevelName(gr, lookup);
return (levelName.length() == 0)
? param.getDescription()
: param.getDescription() + " @ " + makeLevelName(gr, lookup);
}
*/
/**
* Fill in the netCDF file
*
* @param index grid index
* @param lookup lookup table
* @param version version of data
* @param ncfile netCDF file to fill in
* @param fmrcCoordSys forecast model run CS
* @param cancelTask cancel task
* @throws IOException Problem reading from the file
*/
public void open(GridIndex index, GridTableLookup lookup, int version,
NetcdfFile ncfile, FmrcCoordSys fmrcCoordSys,
CancelTask cancelTask)
throws IOException {
// create the HorizCoord Systems : one for each gds
List hcsList = index.getHorizCoordSys();
boolean needGroups = (hcsList.size() > 1);
for (int i = 0; i < hcsList.size(); i++) {
GridDefRecord gdsIndex = (GridDefRecord) hcsList.get(i);
Group g = null;
if (needGroups) {
//g = new Group(ncfile, null, "proj" + i);
g = new Group(ncfile, null, gdsIndex.getGroupName());
ncfile.addGroup(null, g);
}
// (GridDefRecord gdsIndex, String grid_name, String shape_name, Group g)
GridHorizCoordSys hcs = new GridHorizCoordSys(gdsIndex, lookup, g);
hcsHash.put(gdsIndex.getParam(gdsIndex.GDS_KEY), hcs);
}
// run through each record
GridRecord firstRecord = null;
List records = index.getGridRecords();
if (GridServiceProvider.debugOpen) {
System.out.println(" number of products = " + records.size());
}
for (int i = 0; i < records.size(); i++) {
GridRecord gribRecord = (GridRecord) records.get(i);
if (firstRecord == null) {
firstRecord = gribRecord;
}
GridHorizCoordSys hcs = (GridHorizCoordSys) hcsHash.get(
gribRecord.getGridDefRecordId());
String name = makeVariableName(gribRecord, lookup);
GridVariable pv = (GridVariable) hcs.varHash.get(name); // combo gds, param name and level name
if (null == pv) {
String pname =
lookup.getParameter(gribRecord).getDescription();
pv = new GridVariable(name, pname, hcs, lookup);
hcs.varHash.put(name, pv);
// keep track of all products with same parameter name
ArrayList plist = (ArrayList) hcs.productHash.get(pname);
if (null == plist) {
plist = new ArrayList();
hcs.productHash.put(pname, plist);
}
plist.add(pv);
}
pv.addProduct(gribRecord);
}
// global stuff
ncfile.addAttribute(null, new Attribute("Conventions", "CF-1.0"));
/* TODO: figure out what to do with these
String creator = lookup.getFirstCenterName() + " subcenter = "+lookup.getFirstSubcenterId();
if (creator != null)
ncfile.addAttribute(null, new Attribute("Originating_center", creator) );
String genType = lookup.getTypeGenProcessName( firstRecord);
if (genType != null)
ncfile.addAttribute(null, new Attribute("Generating_Process_or_Model", genType) );
if (null != lookup.getFirstProductStatusName())
ncfile.addAttribute(null, new Attribute("Product_Status", lookup.getFirstProductStatusName()) );
ncfile.addAttribute(null, new Attribute("Product_Type", lookup.getFirstProductTypeName()) );
*/
// dataset discovery
ncfile.addAttribute(null, new Attribute("cdm_data_type", FeatureType.GRID.toString()));
String gridType = lookup.getGridType();
//ncfile.addAttribute(null, new Attribute("creator_name", creator));
ncfile.addAttribute(null, new Attribute("file_format", gridType + "-" + version));
ncfile.addAttribute(null,
new Attribute("location", ncfile.getLocation()));
ncfile.addAttribute(
null,
new Attribute(
"history", "Direct read of " + gridType + " into NetCDF-Java 2.2 API"));
ncfile.addAttribute(
null,
new Attribute(
_Coordinate.ModelRunDate,
formatter.toDateTimeStringISO(lookup.getFirstBaseTime())));
if (fmrcCoordSys != null) {
makeDefinedCoordSys(ncfile, lookup, fmrcCoordSys);
/* else if (GribServiceProvider.useMaximalCoordSys)
makeMaximalCoordSys(ncfile, lookup, cancelTask); */
} else {
makeDenseCoordSys(ncfile, lookup, cancelTask);
}
if (GridServiceProvider.debugMissing) {
int count = 0;
Iterator iterHcs = hcsHash.values().iterator();
while (iterHcs.hasNext()) {
GridHorizCoordSys hcs = (GridHorizCoordSys) iterHcs.next();
ArrayList gribvars = new ArrayList(hcs.varHash.values());
for (int i = 0; i < gribvars.size(); i++) {
GridVariable gv = (GridVariable) gribvars.get(i);
count += gv.dumpMissingSummary();
}
}
System.out.println(" total missing= " + count);
}
if (GridServiceProvider.debugMissingDetails) {
Iterator iterHcs = hcsHash.values().iterator();
while (iterHcs.hasNext()) { // loop over HorizCoordSys
GridHorizCoordSys hcs = (GridHorizCoordSys) iterHcs.next();
System.out.println("******** Horiz Coordinate= "
+ hcs.getGridName());
String lastVertDesc = null;
ArrayList gribvars = new ArrayList(hcs.varHash.values());
Collections.sort(gribvars,
new CompareGridVariableByVertName());
for (int i = 0; i < gribvars.size(); i++) {
GridVariable gv = (GridVariable) gribvars.get(i);
String vertDesc = gv.getVertName();
if (!vertDesc.equals(lastVertDesc)) {
System.out.println("---Vertical Coordinate= "
+ vertDesc);
lastVertDesc = vertDesc;
}
gv.dumpMissing();
}
}
}
}
/**
* Make coordinate system without missing data - means that we
* have to make a coordinate axis for each unique set
* of time or vertical levels.
*
* @param ncfile netCDF file
* @param lookup lookup table
* @param cancelTask cancel task
* @throws IOException problem reading file
*/
private void makeDenseCoordSys(NetcdfFile ncfile, GridTableLookup lookup,
CancelTask cancelTask)
throws IOException {
ArrayList timeCoords = new ArrayList();
ArrayList vertCoords = new ArrayList();
// loop over HorizCoordSys
Iterator iterHcs = hcsHash.values().iterator();
while (iterHcs.hasNext()) {
GridHorizCoordSys hcs = (GridHorizCoordSys) iterHcs.next();
// loop over GridVariables in the HorizCoordSys
// create the time and vertical coordinates
Iterator iter = hcs.varHash.values().iterator();
while (iter.hasNext()) {
GridVariable pv = (GridVariable) iter.next();
List recordList = pv.getRecords();
GridRecord record = (GridRecord) recordList.get(0);
String vname = makeLevelName(record, lookup);
// look to see if vertical already exists
GridVertCoord useVertCoord = null;
for (int i = 0; i < vertCoords.size(); i++) {
GridVertCoord gvcs = (GridVertCoord) vertCoords.get(i);
if (vname.equals(gvcs.getLevelName())) {
if (gvcs.matchLevels(recordList)) { // must have the same levels
useVertCoord = gvcs;
}
}
}
if (useVertCoord == null) { // nope, got to create it
useVertCoord = new GridVertCoord(recordList, vname,
lookup);
vertCoords.add(useVertCoord);
}
pv.setVertCoord(useVertCoord);
// look to see if time coord already exists
GridTimeCoord useTimeCoord = null;
for (int i = 0; i < timeCoords.size(); i++) {
GridTimeCoord gtc = (GridTimeCoord) timeCoords.get(i);
if (gtc.matchLevels(recordList)) { // must have the same levels
useTimeCoord = gtc;
}
}
if (useTimeCoord == null) { // nope, got to create it
useTimeCoord = new GridTimeCoord(recordList, lookup);
timeCoords.add(useTimeCoord);
}
pv.setTimeCoord(useTimeCoord);
}
//// assign time coordinate names
// find time dimensions with largest length
GridTimeCoord tcs0 = null;
int maxTimes = 0;
for (int i = 0; i < timeCoords.size(); i++) {
GridTimeCoord tcs = (GridTimeCoord) timeCoords.get(i);
if (tcs.getNTimes() > maxTimes) {
tcs0 = tcs;
maxTimes = tcs.getNTimes();
}
}
// add time dimensions, give time dimensions unique names
int seqno = 1;
for (int i = 0; i < timeCoords.size(); i++) {
GridTimeCoord tcs = (GridTimeCoord) timeCoords.get(i);
if (tcs != tcs0) {
tcs.setSequence(seqno++);
}
tcs.addDimensionsToNetcdfFile(ncfile, hcs.getGroup());
}
// add x, y dimensions
hcs.addDimensionsToNetcdfFile(ncfile);
// add vertical dimensions, give them unique names
Collections.sort(vertCoords);
int vcIndex = 0;
String listName = null;
int start = 0;
for (vcIndex = 0; vcIndex < vertCoords.size(); vcIndex++) {
GridVertCoord gvcs = (GridVertCoord) vertCoords.get(vcIndex);
String vname = gvcs.getLevelName();
if (listName == null) {
listName = vname; // initial
}
if (!vname.equals(listName)) {
makeVerticalDimensions(vertCoords.subList(start,
vcIndex), ncfile, hcs.getGroup());
listName = vname;
start = vcIndex;
}
}
makeVerticalDimensions(vertCoords.subList(start, vcIndex),
ncfile, hcs.getGroup());
// create a variable for each entry, but check for other products with same desc
// to disambiguate by vertical coord
ArrayList products = new ArrayList(hcs.productHash.values());
Collections.sort(products, new CompareGridVariableListByName());
for (int i = 0; i < products.size(); i++) {
ArrayList plist = (ArrayList) products.get(i); // all the products with the same name
if (plist.size() == 1) {
GridVariable pv = (GridVariable) plist.get(0);
Variable v = pv.makeVariable(ncfile, hcs.getGroup(),
useDescriptionForVariableName);
ncfile.addVariable(hcs.getGroup(), v);
} else {
Collections.sort(
plist, new CompareGridVariableByNumberVertLevels());
/* find the one with the most vertical levels
int maxLevels = 0;
GridVariable maxV = null;
for (int j = 0; j < plist.size(); j++) {
GridVariable pv = (GridVariable) plist.get(j);
if (pv.getVertCoord().getNLevels() > maxLevels) {
maxLevels = pv.getVertCoord().getNLevels();
maxV = pv;
}
} */
// finally, add the variables
for (int k = 0; k < plist.size(); k++) {
GridVariable pv = (GridVariable) plist.get(k);
//int nlevels = pv.getVertNlevels();
//boolean useDesc = (k == 0) && (nlevels > 1); // keep using the level name if theres only one level
// TODO: is there a better way to do this?
boolean useDesc = (k == 0 && useDescriptionForVariableName);
ncfile.addVariable(hcs.getGroup(),
pv.makeVariable(ncfile,
hcs.getGroup(), useDesc));
}
} // multipe vertical levels
} // create variable
// add coordinate variables at the end
for (int i = 0; i < timeCoords.size(); i++) {
GridTimeCoord tcs = (GridTimeCoord) timeCoords.get(i);
tcs.addToNetcdfFile(ncfile, hcs.getGroup());
}
hcs.addToNetcdfFile(ncfile);
for (int i = 0; i < vertCoords.size(); i++) {
GridVertCoord gvcs = (GridVertCoord) vertCoords.get(i);
gvcs.addToNetcdfFile(ncfile, hcs.getGroup());
}
} // loop over hcs
}
/**
* Make a vertical dimensions
*
* @param vertCoordList vertCoords all with the same name
* @param ncfile netCDF file to add to
* @param group group in ncfile
*/
private void makeVerticalDimensions(List vertCoordList,
NetcdfFile ncfile, Group group) {
// find biggest vert coord
GridVertCoord gvcs0 = null;
int maxLevels = 0;
for (int i = 0; i < vertCoordList.size(); i++) {
GridVertCoord gvcs = (GridVertCoord) vertCoordList.get(i);
if (gvcs.getNLevels() > maxLevels) {
gvcs0 = gvcs;
maxLevels = gvcs.getNLevels();
}
}
int seqno = 1;
for (int i = 0; i < vertCoordList.size(); i++) {
GridVertCoord gvcs = (GridVertCoord) vertCoordList.get(i);
if (gvcs != gvcs0) {
gvcs.setSequence(seqno++);
}
gvcs.addDimensionsToNetcdfFile(ncfile, group);
}
}
/**
* Make coordinate system from a Definition object
*
* @param ncfile netCDF file to add to
* @param lookup lookup table
* @param fmr FmrcCoordSys
* @throws IOException problem reading from file
*/
private void makeDefinedCoordSys(NetcdfFile ncfile,
GridTableLookup lookup, FmrcCoordSys fmr)
throws IOException {
ArrayList timeCoords = new ArrayList();
ArrayList vertCoords = new ArrayList();
ArrayList removeVariables = new ArrayList();
// loop over HorizCoordSys
Iterator iterHcs = hcsHash.values().iterator();
while (iterHcs.hasNext()) {
GridHorizCoordSys hcs = (GridHorizCoordSys) iterHcs.next();
// loop over GridVariables in the HorizCoordSys
// create the time and vertical coordinates
Iterator iterKey = hcs.varHash.keySet().iterator();
while (iterKey.hasNext()) {
String key = (String) iterKey.next();
GridVariable pv = (GridVariable) hcs.varHash.get(key);
GridRecord record = pv.getFirstRecord();
// we dont know the name for sure yet, so have to try several
String searchName = findVariableName(ncfile, record, lookup,
fmr);
System.out.println("Search name = " + searchName);
if (searchName == null) { // cant find - just remove
System.out.println("removing " + searchName);
removeVariables.add(key); // cant remove (concurrentModException) so save for later
continue;
}
pv.setVarName(searchName);
// get the vertical coordinate for this variable, if it exists
FmrcCoordSys.VertCoord vc_def =
fmr.findVertCoordForVariable(searchName);
if (vc_def != null) {
String vc_name = vc_def.getName();
// look to see if GridVertCoord already made
GridVertCoord useVertCoord = null;
for (int i = 0; i < vertCoords.size(); i++) {
GridVertCoord gvcs =
(GridVertCoord) vertCoords.get(i);
if (vc_name.equals(gvcs.getLevelName())) {
useVertCoord = gvcs;
}
}
if (useVertCoord == null) { // nope, got to create it
useVertCoord = new GridVertCoord(record, vc_name,
lookup, vc_def.getValues1(),
vc_def.getValues2());
useVertCoord.addDimensionsToNetcdfFile(ncfile,
hcs.getGroup());
vertCoords.add(useVertCoord);
}
pv.setVertCoord(useVertCoord);
} else {
pv.setVertCoord(new GridVertCoord(searchName)); // fake
}
// get the time coordinate for this variable
FmrcCoordSys.TimeCoord tc_def =
fmr.findTimeCoordForVariable(searchName,
lookup.getFirstBaseTime());
String tc_name = tc_def.getName();
// look to see if GridTimeCoord already made
GridTimeCoord useTimeCoord = null;
for (int i = 0; i < timeCoords.size(); i++) {
GridTimeCoord gtc = (GridTimeCoord) timeCoords.get(i);
if (tc_name.equals(gtc.getName())) {
useTimeCoord = gtc;
}
}
if (useTimeCoord == null) { // nope, got to create it
useTimeCoord = new GridTimeCoord(tc_name,
tc_def.getOffsetHours(), lookup);
useTimeCoord.addDimensionsToNetcdfFile(ncfile,
hcs.getGroup());
timeCoords.add(useTimeCoord);
}
pv.setTimeCoord(useTimeCoord);
}
// any need to be removed?
for (int i = 0; i < removeVariables.size(); i++) {
String key = (String) removeVariables.get(i);
hcs.varHash.remove(key);
}
// add x, y dimensions
hcs.addDimensionsToNetcdfFile(ncfile);
// create a variable for each entry
Iterator iter2 = hcs.varHash.values().iterator();
while (iter2.hasNext()) {
GridVariable pv = (GridVariable) iter2.next();
Variable v = pv.makeVariable(ncfile, hcs.getGroup(),
true);
ncfile.addVariable(hcs.getGroup(), v);
}
// add coordinate variables at the end
for (int i = 0; i < timeCoords.size(); i++) {
GridTimeCoord tcs = (GridTimeCoord) timeCoords.get(i);
tcs.addToNetcdfFile(ncfile, hcs.getGroup());
}
hcs.addToNetcdfFile(ncfile);
for (int i = 0; i < vertCoords.size(); i++) {
GridVertCoord gvcs = (GridVertCoord) vertCoords.get(i);
gvcs.addToNetcdfFile(ncfile, hcs.getGroup());
}
} // loop over hcs
if (debug) {
System.out.println("GridIndexToNC.makeDefinedCoordSys for "
+ ncfile.getLocation());
}
}
/**
* Find the variable name for the grid
*
* @param ncfile netCDF file
* @param gr grid record
* @param lookup lookup table
* @param fmr FmrcCoordSys
* @return name for the grid
*/
private String findVariableName(NetcdfFile ncfile, GridRecord gr,
GridTableLookup lookup,
FmrcCoordSys fmr) {
// first lookup with name & vert name
String name =
AbstractIOServiceProvider.createValidNetcdfObjectName(makeVariableName(gr,
lookup));
if (fmr.hasVariable(name)) {
return name;
}
// now try just the name
String pname = AbstractIOServiceProvider.createValidNetcdfObjectName(
lookup.getParameter(gr).getDescription());
if (fmr.hasVariable(pname)) {
return pname;
}
logger.warn(
"GridIndexToNC: FmrcCoordSys does not have the variable named ="
+ name + " or " + pname + " for file " + ncfile.getLocation());
return null;
}
/**
* Comparable object for grid variable
*
* @author IDV Development Team
* @version $Revision: 1.3 $
*/
private class CompareGridVariableListByName implements Comparator {
/**
* Compare the two lists of names
*
* @param o1 first list
* @param o2 second list
* @return comparison
*/
public int compare(Object o1, Object o2) {
ArrayList list1 = (ArrayList) o1;
ArrayList list2 = (ArrayList) o2;
GridVariable gv1 = (GridVariable) list1.get(0);
GridVariable gv2 = (GridVariable) list2.get(0);
return gv1.getName().compareToIgnoreCase(gv2.getName());
}
}
/**
* Comparator for grids by vertical variable name
*
* @author IDV Development Team
* @version $Revision: 1.3 $
*/
private class CompareGridVariableByVertName implements Comparator {
/**
* Compare the two lists of names
*
* @param o1 first list
* @param o2 second list
* @return comparison
*/
public int compare(Object o1, Object o2) {
GridVariable gv1 = (GridVariable) o1;
GridVariable gv2 = (GridVariable) o2;
return gv1.getVertName().compareToIgnoreCase(gv2.getVertName());
}
}
/**
* Comparator for grid variables by number of vertical levels
*
* @author IDV Development Team
* @version $Revision: 1.3 $
*/
private class CompareGridVariableByNumberVertLevels implements Comparator {
/**
* Compare the two lists of names
*
* @param o1 first list
* @param o2 second list
* @return comparison
*/
public int compare(Object o1, Object o2) {
GridVariable gv1 = (GridVariable) o1;
GridVariable gv2 = (GridVariable) o2;
int n1 = gv1.getVertCoord().getNLevels();
int n2 = gv2.getVertCoord().getNLevels();
if (n1 == n2) { // break ties for consistency
return gv1.getVertCoord().getLevelName().compareTo(
gv2.getVertCoord().getLevelName());
} else {
return n2 - n1; // highest number first
}
}
}
/**
* Should use the description for the variable name.
*
* @param value false to use name instead of description
*/
public void setUseDescriptionForVariableName(boolean value) {
useDescriptionForVariableName = value;
}
}
|
package installer;
import installer.SshCommandExecutor.ExecutionError;
import installer.exception.InstallationError;
import installer.exception.InstallationFatalError;
import installer.fileio.ConfigurationReader;
import installer.fileio.ConfigurationReader.ConfigurationReadError;
import installer.fileio.MD5Calculator;
import installer.model.Host;
import installer.model.InstallerConfiguration;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.SimpleLog;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.VFS;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class Installer {
private InstallerConfiguration configuration;
private FileObject dependencies;
private FileSystemManager fsManager;
private JSch jsch;
private Log log;
private FileSystemOptions sftpOptions;
public Installer(Log aLog) throws InstallationFatalError {
setLog(aLog);
getLog().info(Messages.getString("Installer.ConfiguringInstaller")); //$NON-NLS-1$
initializeFsManager();
String localDirectoryPath = System.getProperty("user.dir"); //$NON-NLS-1$
FileObject localDirectory = openLocalDirectory(localDirectoryPath);
openDependenciesDirectory(localDirectory);
loadConfiguration(localDirectory);
configureVFS2SFTP();
configureJSch();
getLog().info(
Messages.getString("Installer.VerifyingInstallationFiles")); //$NON-NLS-1$
calculateDependenciesMD5();
obtainDependenciesPath(localDirectoryPath);
}
private void obtainDependenciesPath(String localDirectory) {
for (String fileType : configuration.getFiles().keySet()) {
String fileName = configuration.getFiles().get(fileType);
try {
String path = MessageFormat.format(
"tgz://{0}/dependencies/{1}", localDirectory, fileName); //$NON-NLS-1$
FileName fname = fsManager.resolveFile(path).getChildren()[0]
.getName();
String message = MessageFormat
.format(Messages.getString("Installer.DirectoryOfIs"), fileType, //$NON-NLS-1$
fname.getBaseName());
getLog().trace(message);
} catch (FileSystemException e) {
String message = MessageFormat.format(Messages
.getString("Installer.CouldNotOpenDependencyFile"), //$NON-NLS-1$
fileType, fileName);
getLog().error(message, e);
}
}
}
private void calculateDependenciesMD5() throws InstallationFatalError {
for (String fileType : configuration.getFiles().keySet()) {
String fileName = configuration.getFiles().get(fileType);
try {
FileObject file = dependencies.resolveFile(fileName);
if (file.getType().equals(FileType.FILE)) {
getLog().trace(
MessageFormat.format(Messages
.getString("Installer.CalculatingMD5Of"), //$NON-NLS-1$
file.getName().getBaseName()));
String md5 = calculateMd5Of(file);
Md5ComparingFileSelector.getFilesMd5().put(fileName, md5);
getLog().trace(
MessageFormat.format(
Messages.getString("Installer.MD5OfIs"), file //$NON-NLS-1$
.getName().getBaseName(), md5));
}
file.close();
} catch (FileSystemException e) {
throw new InstallationFatalError(
MessageFormat.format(
Messages.getString("Installer.FileNotFoundInDependencies"), fileName), //$NON-NLS-1$
e);
}
}
}
private String calculateMd5Of(FileObject file)
throws InstallationFatalError {
try {
return new MD5Calculator().calculateFor(file);
} catch (FileSystemException e) {
throw new InstallationFatalError(
MessageFormat.format(
Messages.getString("Installer.CouldNotReadFileContents"), file.getName() //$NON-NLS-1$
.getBaseName()), e);
} catch (NoSuchAlgorithmException e) {
throw new InstallationFatalError(
Messages.getString("Installer.MD5AlgorighmNotFound"), e); //$NON-NLS-1$
} catch (IOException e) {
throw new InstallationFatalError(
MessageFormat.format(
Messages.getString("Installer.CouldNotCalculateMD5Of"), file.getName() //$NON-NLS-1$
.getBaseName()), e);
}
}
private void closeInstallationDirectory(FileObject remoteDirectory,
Host host) {
try {
remoteDirectory.close();
getLog().debug(
MessageFormat.format(Messages
.getString("Installer.ClosedSFTPConnectionWith"), //$NON-NLS-1$
host.getHostname()));
} catch (FileSystemException e) {
getLog().warn(
MessageFormat.format(
Messages.getString("Installer.ErrorClosingSFTPConnectionWith"), //$NON-NLS-1$
host.getHostname()), e);
}
}
private void configureJSch() throws InstallationFatalError {
try {
// TODO sacar policy de archivo de configuraacion (yes/no/ask).
JSch.setConfig("StrictHostKeyChecking", "ask"); //$NON-NLS-1$//$NON-NLS-2$
jsch = new JSch();
// JSch.setLogger(new MyLogger());
jsch.addIdentity(configuration.sshKeyFile(),
configuration.sshKeyFile() + ".pub", null); //$NON-NLS-1$
jsch.setKnownHosts("~/.ssh/known_hosts"); //$NON-NLS-1$
} catch (JSchException e) {
throw new InstallationFatalError(
Messages.getString("Installer.ErrorConfiguringJSCH"), e); //$NON-NLS-1$
}
getLog().trace(Messages.getString("Installer.ConfiguredJSCH")); //$NON-NLS-1$
}
private void configureVFS2SFTP() throws InstallationFatalError {
sftpOptions = new FileSystemOptions();
try {
SftpFileSystemConfigBuilder builder = SftpFileSystemConfigBuilder
.getInstance();
// TODO- bypass known_hosts from configuration, (yes/no/ask)
// TODO- get known hosts directory from configuration (absolute)
builder.setKnownHosts(sftpOptions,
new File(System.getProperty("user.home") //$NON-NLS-1$
+ "/.ssh/known_hosts")); //$NON-NLS-1$
builder.setStrictHostKeyChecking(sftpOptions, "ask"); //$NON-NLS-1$
builder.setUserDirIsRoot(sftpOptions, false);
File identities[] = new File[1];
identities[0] = new File(configuration.sshKeyFile());
builder.setIdentities(sftpOptions, identities);
} catch (FileSystemException e) {
throw new InstallationFatalError(
Messages.getString("Installer.ErrorConfiguringSFTP"), e); //$NON-NLS-1$
}
getLog().trace(Messages.getString("Installer.ConfiguredSFTP")); //$NON-NLS-1$
}
private Session connectTo(Host host) throws JSchException {
Session session;
session = jsch.getSession(host.getUsername(), host.getHostname(),
host.getPort());
session.connect();
return session;
}
private void initializeFsManager() throws InstallationFatalError {
try {
fsManager = VFS.getManager();
} catch (FileSystemException e) {
throw new InstallationFatalError(
Messages.getString("Installer.ErrorObtainingVFSManager"), e); //$NON-NLS-1$
}
}
private void install(Host host) throws InstallationError {
FileObject remoteDirectory;
getLog().info(
MessageFormat.format(
Messages.getString("Installer.BeginInstalling"), host.getHostname())); //$NON-NLS-1$
Session session = null;
try {
session = connectTo(host);
remoteDirectory = openInstallationDirectory(host);
try {
remoteDirectory.copyFrom(dependencies,
new Md5ComparingFileSelector(host, session));
} catch (FileSystemException e) {
throw new InstallationError(MessageFormat.format(Messages
.getString("Installer.ErrorUploadingcompressedFiles"), //$NON-NLS-1$
remoteDirectory.getName()), e);
}
getLog().info(
MessageFormat.format(Messages
.getString("Installer.CompressedFilesUploadedTo"), //$NON-NLS-1$
remoteDirectory.getName()));
uncompressFiles(host, session);
getLog().info(
MessageFormat.format(
Messages.getString("Installer.UncompresseedUploadedFilesIn"), //$NON-NLS-1$
host.getHostname()));
} catch (JSchException e) {
throw new InstallationError(
MessageFormat.format(
Messages.getString("Installer.ErrorWhenConnectingToAs"), host.getHostname(), //$NON-NLS-1$
host.getUsername()), e);
} catch (FileSystemException e) {
throw new InstallationError(
Messages.getString("Installer.ErrorObtainingFIlesToUncompress"), //$NON-NLS-1$
e);
} finally {
if (session != null && session.isConnected()) {
session.disconnect();
}
}
// TODO! pasar archivos de configuracion
closeInstallationDirectory(remoteDirectory, host);
getLog().info(
Messages.getString("Installer.FinishedInstalling") + host.getHostname()); //$NON-NLS-1$
}
private void loadConfiguration(FileObject localDirectory)
throws InstallationFatalError {
FileObject configurationFile;
String fileName = "configuration.xml"; //$NON-NLS-1$
try {
configurationFile = localDirectory.resolveFile(fileName);
} catch (FileSystemException e) {
throw new InstallationFatalError(MessageFormat.format(Messages
.getString("Installer.CouldNotResolveConfigurationFile"), //$NON-NLS-1$
fileName), e);
}
getLog().debug(Messages.getString("Installer.FoundConfigurationFile")); //$NON-NLS-1$
try {
configuration = new ConfigurationReader()
.readFrom(configurationFile);
} catch (ConfigurationReadError e) {
throw new InstallationFatalError(
Messages.getString("Installer.ErrorReadingConfigurationFile"), e); //$NON-NLS-1$
}
getLog().trace(Messages.getString("Installer.ParsedConfigurationFile")); //$NON-NLS-1$
}
private void openDependenciesDirectory(FileObject localDirectory)
throws InstallationFatalError {
String folderName = "dependencies"; //$NON-NLS-1$
try {
dependencies = localDirectory.resolveFile(folderName);
} catch (FileSystemException e) {
throw new InstallationFatalError(MessageFormat.format(Messages
.getString("Installer.CouldNotResolveDependenciesFolder"), //$NON-NLS-1$
folderName), e);
}
getLog().debug(
Messages.getString("Installer.FoundDependenciesDirectory")); //$NON-NLS-1$
}
private FileObject openInstallationDirectory(Host host)
throws InstallationError {
FileObject remoteDirectory;
try {
remoteDirectory = fsManager.resolveFile(uriFor(host), sftpOptions);
if (!remoteDirectory.exists()) {
remoteDirectory.createFolder();
}
} catch (FileSystemException | URISyntaxException e) {
throw new InstallationError(
MessageFormat.format(
Messages.getString("Installer.ErrorEstablishingSFTPConnectionWith"), //$NON-NLS-1$
host.getHostname()), e);
}
getLog().debug(
MessageFormat.format(Messages
.getString("Installer.EstablishedSFTPConnectionWith"), //$NON-NLS-1$
host.getHostname()));
return remoteDirectory;
}
private FileObject openLocalDirectory(String localPath)
throws InstallationFatalError {
FileObject localDirectory;
try {
localDirectory = fsManager.resolveFile(localPath);
} catch (FileSystemException e) {
throw new InstallationFatalError(
MessageFormat
.format(Messages
.getString("Installer.CouldNotOpenLocalDirectory"), localPath), e); //$NON-NLS-1$
}
getLog().trace(
MessageFormat.format(
Messages.getString("Installer.OpenedLocalDirectory"), localPath)); //$NON-NLS-1$
return localDirectory;
}
public void run() throws InstallationError {
getLog().info(Messages.getString("Installer.InstallationStarted")); //$NON-NLS-1$
for (Host host : configuration.getNodes()) {
install(host);
}
getLog().info(Messages.getString("Installer.InstallationFinished")); //$NON-NLS-1$
}
private void uncompressFiles(Host host, Session session)
throws FileSystemException, InstallationError {
for (FileObject file : dependencies.getChildren()) {
String commandString = MessageFormat
.format("cd {0}; tar -zxf {1}", host.getInstallationDirectory(), file.getName().getBaseName()); //$NON-NLS-1$
SshCommandExecutor command = new SshCommandExecutor(session);
try {
command.execute(commandString);
if (!command.getOutput().isEmpty()) {
for (String line : command.getOutput()) {
getLog().trace(line);
}
}
} catch (ExecutionError e) {
throw new InstallationError(MessageFormat.format(Messages
.getString("Installer.CommandExecutionFailedAt"), //$NON-NLS-1$
host.getHostname()), e);
}
}
}
private String uriFor(Host host) throws URISyntaxException {
return new URI("sftp", host.getUsername(), host.getHostname(), //$NON-NLS-1$
host.getPort(), host.getInstallationDirectory(), null, null)
.toString();
}
private Log getLog() {
if (this.log == null) {
setLog(new SimpleLog(Messages.getString("Installer.DefaultLogName"))); //$NON-NLS-1$
}
return log;
}
private void setLog(Log log) {
this.log = log;
}
}
|
package org.jfree.chart.axis;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.ValueAxisPlot;
import org.jfree.data.Range;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.TextAnchor;
/**
* A numerical axis that uses a logarithmic scale.
*/
public class LogarithmicAxis extends NumberAxis {
/** For serialization. */
private static final long serialVersionUID = 2502918599004103054L;
/** Useful constant for log(10). */
public static final double LOG10_VALUE = Math.log(10.0);
/** Smallest arbitrarily-close-to-zero value allowed. */
public static final double SMALL_LOG_VALUE = 1e-100;
/** Flag set true to allow negative values in data. */
protected boolean allowNegativesFlag = false;
/**
* Flag set true make axis throw exception if any values are
* <= 0 and 'allowNegativesFlag' is false.
*/
protected boolean strictValuesFlag = true;
/** Number formatter for generating numeric strings. */
protected final NumberFormat numberFormatterObj
= NumberFormat.getInstance();
/** Flag set true for "1e#"-style tick labels. */
protected boolean expTickLabelsFlag = false;
/** Flag set true for "10^n"-style tick labels. */
protected boolean log10TickLabelsFlag = false;
/** True to make 'autoAdjustRange()' select "10^n" values. */
protected boolean autoRangeNextLogFlag = false;
/** Helper flag for log axis processing. */
protected boolean smallLogFlag = false;
/**
* Creates a new axis.
*
* @param label the axis label.
*/
public LogarithmicAxis(String label) {
super(label);
setupNumberFmtObj(); //setup number formatter obj
}
/**
* Sets the 'allowNegativesFlag' flag; true to allow negative values
* in data, false to be able to plot positive values arbitrarily close to
* zero.
*
* @param flgVal the new value of the flag.
*/
public void setAllowNegativesFlag(boolean flgVal) {
this.allowNegativesFlag = flgVal;
}
/**
* Returns the 'allowNegativesFlag' flag; true to allow negative values
* in data, false to be able to plot positive values arbitrarily close
* to zero.
*
* @return The flag.
*/
public boolean getAllowNegativesFlag() {
return this.allowNegativesFlag;
}
/**
* Sets the 'strictValuesFlag' flag; if true and 'allowNegativesFlag'
* is false then this axis will throw a runtime exception if any of its
* values are less than or equal to zero; if false then the axis will
* adjust for values less than or equal to zero as needed.
*
* @param flgVal true for strict enforcement.
*/
public void setStrictValuesFlag(boolean flgVal) {
this.strictValuesFlag = flgVal;
}
/**
* Returns the 'strictValuesFlag' flag; if true and 'allowNegativesFlag'
* is false then this axis will throw a runtime exception if any of its
* values are less than or equal to zero; if false then the axis will
* adjust for values less than or equal to zero as needed.
*
* @return <code>true</code> if strict enforcement is enabled.
*/
public boolean getStrictValuesFlag() {
return this.strictValuesFlag;
}
/**
* Sets the 'expTickLabelsFlag' flag. If the 'log10TickLabelsFlag'
* is false then this will set whether or not "1e#"-style tick labels
* are used. The default is to use regular numeric tick labels.
*
* @param flgVal true for "1e#"-style tick labels, false for
* log10 or regular numeric tick labels.
*/
public void setExpTickLabelsFlag(boolean flgVal) {
this.expTickLabelsFlag = flgVal;
setupNumberFmtObj(); //setup number formatter obj
}
/**
* Returns the 'expTickLabelsFlag' flag.
*
* @return <code>true</code> for "1e#"-style tick labels,
* <code>false</code> for log10 or regular numeric tick labels.
*/
public boolean getExpTickLabelsFlag() {
return this.expTickLabelsFlag;
}
/**
* Sets the 'log10TickLabelsFlag' flag. The default value is false.
*
* @param flag true for "10^n"-style tick labels, false for "1e#"-style
* or regular numeric tick labels.
*/
public void setLog10TickLabelsFlag(boolean flag) {
this.log10TickLabelsFlag = flag;
}
/**
* Returns the 'log10TickLabelsFlag' flag.
*
* @return <code>true</code> for "10^n"-style tick labels,
* <code>false</code> for "1e#"-style or regular numeric tick
* labels.
*/
public boolean getLog10TickLabelsFlag() {
return this.log10TickLabelsFlag;
}
/**
* Sets the 'autoRangeNextLogFlag' flag. This determines whether or
* not the 'autoAdjustRange()' method will select the next "10^n"
* values when determining the upper and lower bounds. The default
* value is false.
*
* @param flag <code>true</code> to make the 'autoAdjustRange()'
* method select the next "10^n" values, <code>false</code> to not.
*/
public void setAutoRangeNextLogFlag(boolean flag) {
this.autoRangeNextLogFlag = flag;
}
/**
* Returns the 'autoRangeNextLogFlag' flag.
*
* @return <code>true</code> if the 'autoAdjustRange()' method will
* select the next "10^n" values, <code>false</code> if not.
*/
public boolean getAutoRangeNextLogFlag() {
return this.autoRangeNextLogFlag;
}
/**
* Overridden version that calls original and then sets up flag for
* log axis processing.
*
* @param range the new range.
*/
public void setRange(Range range) {
super.setRange(range); // call parent method
setupSmallLogFlag(); // setup flag based on bounds values
}
/**
* Sets up flag for log axis processing. Set true if negative values
* not allowed and the lower bound is between 0 and 10.
*/
protected void setupSmallLogFlag() {
// set flag true if negative values not allowed and the
// lower bound is between 0 and 10:
double lowerVal = getRange().getLowerBound();
this.smallLogFlag = (!this.allowNegativesFlag && lowerVal < 10.0
&& lowerVal > 0.0);
}
/**
* Sets up the number formatter object according to the
* 'expTickLabelsFlag' flag.
*/
protected void setupNumberFmtObj() {
if (this.numberFormatterObj instanceof DecimalFormat) {
//setup for "1e#"-style tick labels or regular
// numeric tick labels, depending on flag:
((DecimalFormat) this.numberFormatterObj).applyPattern(
this.expTickLabelsFlag ? "0E0" : "0.
}
}
/**
* Returns the log10 value, depending on if values between 0 and
* 1 are being plotted. If negative values are not allowed and
* the lower bound is between 0 and 10 then a normal log is
* returned; otherwise the returned value is adjusted if the
* given value is less than 10.
*
* @param val the value.
*
* @return log<sub>10</sub>(val).
*
* @see #switchedPow10(double)
*/
protected double switchedLog10(double val) {
return this.smallLogFlag ? Math.log(val)
/ LOG10_VALUE : adjustedLog10(val);
}
/**
* Returns a power of 10, depending on if values between 0 and
* 1 are being plotted. If negative values are not allowed and
* the lower bound is between 0 and 10 then a normal power is
* returned; otherwise the returned value is adjusted if the
* given value is less than 1.
*
* @param val the value.
*
* @return 10<sup>val</sup>.
*
* @since 1.0.5
* @see #switchedLog10(double)
*/
public double switchedPow10(double val) {
return this.smallLogFlag ? Math.pow(10.0, val) : adjustedPow10(val);
}
/**
* Returns an adjusted log10 value for graphing purposes. The first
* adjustment is that negative values are changed to positive during
* the calculations, and then the answer is negated at the end. The
* second is that, for values less than 10, an increasingly large
* (0 to 1) scaling factor is added such that at 0 the value is
* adjusted to 1, resulting in a returned result of 0.
*
* @param val value for which log10 should be calculated.
*
* @return An adjusted log<sub>10</sub>(val).
*
* @see #adjustedPow10(double)
*/
public double adjustedLog10(double val) {
boolean negFlag = (val < 0.0);
if (negFlag) {
val = -val; // if negative then set flag and make positive
}
if (val < 10.0) { // if < 10 then
val += (10.0 - val) / 10.0; //increase so 0 translates to 0
}
//return value; negate if original value was negative:
double res = Math.log(val) / LOG10_VALUE;
return negFlag ? (-res) : res;
}
/**
* Returns an adjusted power of 10 value for graphing purposes. The first
* adjustment is that negative values are changed to positive during
* the calculations, and then the answer is negated at the end. The
* second is that, for values less than 1, a progressive logarithmic
* offset is subtracted such that at 0 the returned result is also 0.
*
* @param val value for which power of 10 should be calculated.
*
* @return An adjusted 10<sup>val</sup>.
*
* @since 1.0.5
* @see #adjustedLog10(double)
*/
public double adjustedPow10(double val) {
boolean negFlag = (val < 0.0);
if (negFlag) {
val = -val; // if negative then set flag and make positive
}
double res;
if (val < 1.0) {
res = (Math.pow(10, val + 1.0) - 10.0) / 9.0; //invert adjustLog10
}
else {
res = Math.pow(10, val);
}
return negFlag ? (-res) : res;
}
/**
* Returns the largest (closest to positive infinity) double value that is
* not greater than the argument, is equal to a mathematical integer and
* satisfying the condition that log base 10 of the value is an integer
* (i.e., the value returned will be a power of 10: 1, 10, 100, 1000, etc.).
*
* @param lower a double value below which a floor will be calcualted.
*
* @return 10<sup>N</sup> with N .. { 1 ... }
*/
protected double computeLogFloor(double lower) {
double logFloor;
if (this.allowNegativesFlag) {
//negative values are allowed
if (lower > 10.0) { //parameter value is > 10
// The Math.log() function is based on e not 10.
logFloor = Math.log(lower) / LOG10_VALUE;
logFloor = Math.floor(logFloor);
logFloor = Math.pow(10, logFloor);
}
else if (lower < -10.0) { //parameter value is < -10
//calculate log using positive value:
logFloor = Math.log(-lower) / LOG10_VALUE;
//calculate floor using negative value:
logFloor = Math.floor(-logFloor);
//calculate power using positive value; then negate
logFloor = -Math.pow(10, -logFloor);
}
else {
//parameter value is -10 > val < 10
logFloor = Math.floor(lower); //use as-is
}
}
else {
//negative values not allowed
if (lower > 0.0) { //parameter value is > 0
// The Math.log() function is based on e not 10.
logFloor = Math.log(lower) / LOG10_VALUE;
logFloor = Math.floor(logFloor);
logFloor = Math.pow(10, logFloor);
}
else {
//parameter value is <= 0
logFloor = Math.floor(lower); //use as-is
}
}
return logFloor;
}
/**
* Returns the smallest (closest to negative infinity) double value that is
* not less than the argument, is equal to a mathematical integer and
* satisfying the condition that log base 10 of the value is an integer
* (i.e., the value returned will be a power of 10: 1, 10, 100, 1000, etc.).
*
* @param upper a double value above which a ceiling will be calcualted.
*
* @return 10<sup>N</sup> with N .. { 1 ... }
*/
protected double computeLogCeil(double upper) {
double logCeil;
if (this.allowNegativesFlag) {
//negative values are allowed
if (upper > 10.0) {
//parameter value is > 10
// The Math.log() function is based on e not 10.
logCeil = Math.log(upper) / LOG10_VALUE;
logCeil = Math.ceil(logCeil);
logCeil = Math.pow(10, logCeil);
}
else if (upper < -10.0) {
//parameter value is < -10
//calculate log using positive value:
logCeil = Math.log(-upper) / LOG10_VALUE;
//calculate ceil using negative value:
logCeil = Math.ceil(-logCeil);
//calculate power using positive value; then negate
logCeil = -Math.pow(10, -logCeil);
}
else {
//parameter value is -10 > val < 10
logCeil = Math.ceil(upper); //use as-is
}
}
else {
//negative values not allowed
if (upper > 0.0) {
//parameter value is > 0
// The Math.log() function is based on e not 10.
logCeil = Math.log(upper) / LOG10_VALUE;
logCeil = Math.ceil(logCeil);
logCeil = Math.pow(10, logCeil);
}
else {
//parameter value is <= 0
logCeil = Math.ceil(upper); //use as-is
}
}
return logCeil;
}
/**
* Rescales the axis to ensure that all data is visible.
*/
public void autoAdjustRange() {
Plot plot = getPlot();
if (plot == null) {
return; // no plot, no data.
}
if (plot instanceof ValueAxisPlot) {
ValueAxisPlot vap = (ValueAxisPlot) plot;
double lower;
Range r = vap.getDataRange(this);
if (r == null) {
//no real data present
r = getDefaultAutoRange();
lower = r.getLowerBound(); //get lower bound value
}
else {
//actual data is present
lower = r.getLowerBound(); //get lower bound value
if (this.strictValuesFlag
&& !this.allowNegativesFlag && lower <= 0.0) {
//strict flag set, allow-negatives not set and values <= 0
throw new RuntimeException("Values less than or equal to "
+ "zero not allowed with logarithmic axis");
}
}
//apply lower margin by decreasing lower bound:
final double lowerMargin;
if (lower > 0.0 && (lowerMargin = getLowerMargin()) > 0.0) {
//lower bound and margin OK; get log10 of lower bound
final double logLower = (Math.log(lower) / LOG10_VALUE);
double logAbs; //get absolute value of log10 value
if ((logAbs = Math.abs(logLower)) < 1.0) {
logAbs = 1.0; //if less than 1.0 then make it 1.0
} //subtract out margin and get exponential value:
lower = Math.pow(10, (logLower - (logAbs * lowerMargin)));
}
//if flag then change to log version of lowest value
// to make range begin at a 10^n value:
if (this.autoRangeNextLogFlag) {
lower = computeLogFloor(lower);
}
if (!this.allowNegativesFlag && lower >= 0.0
&& lower < SMALL_LOG_VALUE) {
//negatives not allowed and lower range bound is zero
lower = r.getLowerBound(); //use data range bound instead
}
double upper = r.getUpperBound();
//apply upper margin by increasing upper bound:
final double upperMargin;
if (upper > 0.0 && (upperMargin = getUpperMargin()) > 0.0) {
//upper bound and margin OK; get log10 of upper bound
final double logUpper = (Math.log(upper) / LOG10_VALUE);
double logAbs; //get absolute value of log10 value
if ((logAbs = Math.abs(logUpper)) < 1.0) {
logAbs = 1.0; //if less than 1.0 then make it 1.0
} //add in margin and get exponential value:
upper = Math.pow(10, (logUpper + (logAbs * upperMargin)));
}
if (!this.allowNegativesFlag && upper < 1.0 && upper > 0.0
&& lower > 0.0) {
//negatives not allowed and upper bound between 0 & 1
//round up to nearest significant digit for bound:
//get negative exponent:
double expVal = Math.log(upper) / LOG10_VALUE;
expVal = Math.ceil(-expVal + 0.001); //get positive exponent
expVal = Math.pow(10, expVal); //create multiplier value
//multiply, round up, and divide for bound value:
upper = (expVal > 0.0) ? Math.ceil(upper * expVal) / expVal
: Math.ceil(upper);
}
else {
//negatives allowed or upper bound not between 0 & 1
//if flag then change to log version of highest value to
// make range begin at a 10^n value; else use nearest int
upper = (this.autoRangeNextLogFlag) ? computeLogCeil(upper)
: Math.ceil(upper);
}
// ensure the autorange is at least <minRange> in size...
double minRange = getAutoRangeMinimumSize();
if (upper - lower < minRange) {
upper = (upper + lower + minRange) / 2;
lower = (upper + lower - minRange) / 2;
//if autorange still below minimum then adjust by 1%
// (can be needed when minRange is very small):
if (upper - lower < minRange) {
double absUpper = Math.abs(upper);
//need to account for case where upper==0.0
double adjVal = (absUpper > SMALL_LOG_VALUE) ? absUpper
/ 100.0 : 0.01;
upper = (upper + lower + adjVal) / 2;
lower = (upper + lower - adjVal) / 2;
}
}
setRange(new Range(lower, upper), false, false);
setupSmallLogFlag(); //setup flag based on bounds values
}
}
/**
* Converts a data value to a coordinate in Java2D space, assuming that
* the axis runs along one edge of the specified plotArea.
* Note that it is possible for the coordinate to fall outside the
* plotArea.
*
* @param value the data value.
* @param plotArea the area for plotting the data.
* @param edge the axis location.
*
* @return The Java2D coordinate.
*/
public double valueToJava2D(double value, Rectangle2D plotArea,
RectangleEdge edge) {
Range range = getRange();
double axisMin = switchedLog10(range.getLowerBound());
double axisMax = switchedLog10(range.getUpperBound());
double min = 0.0;
double max = 0.0;
if (RectangleEdge.isTopOrBottom(edge)) {
min = plotArea.getMinX();
max = plotArea.getMaxX();
}
else if (RectangleEdge.isLeftOrRight(edge)) {
min = plotArea.getMaxY();
max = plotArea.getMinY();
}
value = switchedLog10(value);
if (isInverted()) {
return max - (((value - axisMin) / (axisMax - axisMin))
* (max - min));
}
else {
return min + (((value - axisMin) / (axisMax - axisMin))
* (max - min));
}
}
/**
* Converts a coordinate in Java2D space to the corresponding data
* value, assuming that the axis runs along one edge of the specified
* plotArea.
*
* @param java2DValue the coordinate in Java2D space.
* @param plotArea the area in which the data is plotted.
* @param edge the axis location.
*
* @return The data value.
*/
public double java2DToValue(double java2DValue, Rectangle2D plotArea,
RectangleEdge edge) {
Range range = getRange();
double axisMin = switchedLog10(range.getLowerBound());
double axisMax = switchedLog10(range.getUpperBound());
double plotMin = 0.0;
double plotMax = 0.0;
if (RectangleEdge.isTopOrBottom(edge)) {
plotMin = plotArea.getX();
plotMax = plotArea.getMaxX();
}
else if (RectangleEdge.isLeftOrRight(edge)) {
plotMin = plotArea.getMaxY();
plotMax = plotArea.getMinY();
}
if (isInverted()) {
return switchedPow10(axisMax - ((java2DValue - plotMin)
/ (plotMax - plotMin)) * (axisMax - axisMin));
}
else {
return switchedPow10(axisMin + ((java2DValue - plotMin)
/ (plotMax - plotMin)) * (axisMax - axisMin));
}
}
/**
* Zooms in on the current range.
*
* @param lowerPercent the new lower bound.
* @param upperPercent the new upper bound.
*/
public void zoomRange(double lowerPercent, double upperPercent) {
double startLog = switchedLog10(getRange().getLowerBound());
double lengthLog = switchedLog10(getRange().getUpperBound()) - startLog;
Range adjusted;
if (isInverted()) {
adjusted = new Range(
switchedPow10(
startLog + (lengthLog * (1 - upperPercent))),
switchedPow10(
startLog + (lengthLog * (1 - lowerPercent))));
}
else {
adjusted = new Range(
switchedPow10(startLog + (lengthLog * lowerPercent)),
switchedPow10(startLog + (lengthLog * upperPercent)));
}
setRange(adjusted);
}
/**
* Calculates the positions of the tick labels for the axis, storing the
* results in the tick label list (ready for drawing).
*
* @param g2 the graphics device.
* @param dataArea the area in which the plot should be drawn.
* @param edge the location of the axis.
*
* @return A list of ticks.
*/
protected List refreshTicksHorizontal(Graphics2D g2,
Rectangle2D dataArea,
RectangleEdge edge) {
List ticks = new java.util.ArrayList();
Range range = getRange();
//get lower bound value:
double lowerBoundVal = range.getLowerBound();
//if small log values and lower bound value too small
// then set to a small value (don't allow <= 0):
if (this.smallLogFlag && lowerBoundVal < SMALL_LOG_VALUE) {
lowerBoundVal = SMALL_LOG_VALUE;
}
//get upper bound value
double upperBoundVal = range.getUpperBound();
//get log10 version of lower bound and round to integer:
int iBegCount = (int) Math.rint(switchedLog10(lowerBoundVal));
//get log10 version of upper bound and round to integer:
int iEndCount = (int) Math.rint(switchedLog10(upperBoundVal));
if (iBegCount == iEndCount && iBegCount > 0
&& Math.pow(10, iBegCount) > lowerBoundVal) {
//only 1 power of 10 value, it's > 0 and its resulting
// tick value will be larger than lower bound of data
--iBegCount; //decrement to generate more ticks
}
double currentTickValue;
String tickLabel;
boolean zeroTickFlag = false;
for (int i = iBegCount; i <= iEndCount; i++) {
//for each power of 10 value; create ten ticks
for (int j = 0; j < 10; ++j) {
//for each tick to be displayed
if (this.smallLogFlag) {
//small log values in use; create numeric value for tick
currentTickValue = Math.pow(10, i) + (Math.pow(10, i) * j);
if (this.expTickLabelsFlag
|| (i < 0 && currentTickValue > 0.0
&& currentTickValue < 1.0)) {
//showing "1e#"-style ticks or negative exponent
// generating tick value between 0 & 1; show fewer
if (j == 0 || (i > -4 && j < 2)
|| currentTickValue >= upperBoundVal) {
//first tick of series, or not too small a value and
// one of first 3 ticks, or last tick to be displayed
// set exact number of fractional digits to be shown
// (no effect if showing "1e#"-style ticks):
this.numberFormatterObj
.setMaximumFractionDigits(-i);
//create tick label (force use of fmt obj):
tickLabel = makeTickLabel(currentTickValue, true);
}
else { //no tick label to be shown
tickLabel = "";
}
}
else { //tick value not between 0 & 1
//show tick label if it's the first or last in
// the set, or if it's 1-5; beyond that show
// fewer as the values get larger:
tickLabel = (j < 1 || (i < 1 && j < 5) || (j < 4 - i)
|| currentTickValue >= upperBoundVal)
? makeTickLabel(currentTickValue) : "";
}
}
else { //not small log values in use; allow for values <= 0
if (zeroTickFlag) { //if did zero tick last iter then
--j; //decrement to do 1.0 tick now
} //calculate power-of-ten value for tick:
currentTickValue = (i >= 0)
? Math.pow(10, i) + (Math.pow(10, i) * j)
: -(Math.pow(10, -i) - (Math.pow(10, -i - 1) * j));
if (!zeroTickFlag) { // did not do zero tick last iteration
if (Math.abs(currentTickValue - 1.0) < 0.0001
&& lowerBoundVal <= 0.0 && upperBoundVal >= 0.0) {
//tick value is 1.0 and 0.0 is within data range
currentTickValue = 0.0; //set tick value to zero
zeroTickFlag = true; //indicate zero tick
}
}
else { //did zero tick last iteration
zeroTickFlag = false; //clear flag
} //create tick label string:
//show tick label if "1e#"-style and it's one
// of the first two, if it's the first or last
// in the set, or if it's 1-5; beyond that
// show fewer as the values get larger:
tickLabel = ((this.expTickLabelsFlag && j < 2)
|| j < 1
|| (i < 1 && j < 5) || (j < 4 - i)
|| currentTickValue >= upperBoundVal)
? makeTickLabel(currentTickValue) : "";
}
if (currentTickValue > upperBoundVal) {
return ticks; // if past highest data value then exit
// method
}
if (currentTickValue >= lowerBoundVal - SMALL_LOG_VALUE) {
//tick value not below lowest data value
TextAnchor anchor = null;
TextAnchor rotationAnchor = null;
double angle = 0.0;
if (isVerticalTickLabels()) {
anchor = TextAnchor.CENTER_RIGHT;
rotationAnchor = TextAnchor.CENTER_RIGHT;
if (edge == RectangleEdge.TOP) {
angle = Math.PI / 2.0;
}
else {
angle = -Math.PI / 2.0;
}
}
else {
if (edge == RectangleEdge.TOP) {
anchor = TextAnchor.BOTTOM_CENTER;
rotationAnchor = TextAnchor.BOTTOM_CENTER;
}
else {
anchor = TextAnchor.TOP_CENTER;
rotationAnchor = TextAnchor.TOP_CENTER;
}
}
Tick tick = new NumberTick(new Double(currentTickValue),
tickLabel, anchor, rotationAnchor, angle);
ticks.add(tick);
}
}
}
return ticks;
}
/**
* Calculates the positions of the tick labels for the axis, storing the
* results in the tick label list (ready for drawing).
*
* @param g2 the graphics device.
* @param dataArea the area in which the plot should be drawn.
* @param edge the location of the axis.
*
* @return A list of ticks.
*/
protected List refreshTicksVertical(Graphics2D g2,
Rectangle2D dataArea,
RectangleEdge edge) {
List ticks = new java.util.ArrayList();
//get lower bound value:
double lowerBoundVal = getRange().getLowerBound();
//if small log values and lower bound value too small
// then set to a small value (don't allow <= 0):
if (this.smallLogFlag && lowerBoundVal < SMALL_LOG_VALUE) {
lowerBoundVal = SMALL_LOG_VALUE;
}
//get upper bound value
double upperBoundVal = getRange().getUpperBound();
//get log10 version of lower bound and round to integer:
int iBegCount = (int) Math.rint(switchedLog10(lowerBoundVal));
//get log10 version of upper bound and round to integer:
int iEndCount = (int) Math.rint(switchedLog10(upperBoundVal));
if (iBegCount == iEndCount && iBegCount > 0
&& Math.pow(10, iBegCount) > lowerBoundVal) {
//only 1 power of 10 value, it's > 0 and its resulting
// tick value will be larger than lower bound of data
--iBegCount; //decrement to generate more ticks
}
double tickVal;
String tickLabel;
boolean zeroTickFlag = false;
for (int i = iBegCount; i <= iEndCount; i++) {
//for each tick with a label to be displayed
int jEndCount = 10;
if (i == iEndCount) {
jEndCount = 1;
}
for (int j = 0; j < jEndCount; j++) {
//for each tick to be displayed
if (this.smallLogFlag) {
//small log values in use
tickVal = Math.pow(10, i) + (Math.pow(10, i) * j);
if (j == 0) {
//first tick of group; create label text
if (this.log10TickLabelsFlag) {
//if flag then
tickLabel = "10^" + i; //create "log10"-type label
}
else { //not "log10"-type label
if (this.expTickLabelsFlag) {
//if flag then
tickLabel = "1e" + i; //create "1e#"-type label
}
else { //not "1e#"-type label
if (i >= 0) { // if positive exponent then
// make integer
NumberFormat format
= getNumberFormatOverride();
if (format != null) {
tickLabel = format.format(tickVal);
}
else {
tickLabel = Long.toString((long)
Math.rint(tickVal));
}
}
else {
//negative exponent; create fractional value
//set exact number of fractional digits to
// be shown:
this.numberFormatterObj
.setMaximumFractionDigits(-i);
//create tick label:
tickLabel = this.numberFormatterObj.format(
tickVal);
}
}
}
}
else { //not first tick to be displayed
tickLabel = ""; //no tick label
}
}
else { //not small log values in use; allow for values <= 0
if (zeroTickFlag) { //if did zero tick last iter then
--j;
} //decrement to do 1.0 tick now
tickVal = (i >= 0) ? Math.pow(10, i) + (Math.pow(10, i) * j)
: -(Math.pow(10, -i) - (Math.pow(10, -i - 1) * j));
if (j == 0) { //first tick of group
if (!zeroTickFlag) { // did not do zero tick last
// iteration
if (i > iBegCount && i < iEndCount
&& Math.abs(tickVal - 1.0) < 0.0001) {
// not first or last tick on graph and value
// is 1.0
tickVal = 0.0; //change value to 0.0
zeroTickFlag = true; //indicate zero tick
tickLabel = "0"; //create label for tick
}
else {
//first or last tick on graph or value is 1.0
//create label for tick:
if (this.log10TickLabelsFlag) {
//create "log10"-type label
tickLabel = (((i < 0) ? "-" : "")
+ "10^" + Math.abs(i));
}
else {
if (this.expTickLabelsFlag) {
//create "1e#"-type label
tickLabel = (((i < 0) ? "-" : "")
+ "1e" + Math.abs(i));
}
else {
NumberFormat format
= getNumberFormatOverride();
if (format != null) {
tickLabel = format.format(tickVal);
}
else {
tickLabel = Long.toString(
(long) Math.rint(tickVal));
}
}
}
}
}
else { // did zero tick last iteration
tickLabel = ""; //no label
zeroTickFlag = false; //clear flag
}
}
else { // not first tick of group
tickLabel = ""; //no label
zeroTickFlag = false; //make sure flag cleared
}
}
if (tickVal > upperBoundVal) {
return ticks; //if past highest data value then exit method
}
if (tickVal >= lowerBoundVal - SMALL_LOG_VALUE) {
//tick value not below lowest data value
TextAnchor anchor = null;
TextAnchor rotationAnchor = null;
double angle = 0.0;
if (isVerticalTickLabels()) {
if (edge == RectangleEdge.LEFT) {
anchor = TextAnchor.BOTTOM_CENTER;
rotationAnchor = TextAnchor.BOTTOM_CENTER;
angle = -Math.PI / 2.0;
}
else {
anchor = TextAnchor.BOTTOM_CENTER;
rotationAnchor = TextAnchor.BOTTOM_CENTER;
angle = Math.PI / 2.0;
}
}
else {
if (edge == RectangleEdge.LEFT) {
anchor = TextAnchor.CENTER_RIGHT;
rotationAnchor = TextAnchor.CENTER_RIGHT;
}
else {
anchor = TextAnchor.CENTER_LEFT;
rotationAnchor = TextAnchor.CENTER_LEFT;
}
}
//create tick object and add to list:
ticks.add(new NumberTick(new Double(tickVal), tickLabel,
anchor, rotationAnchor, angle));
}
}
}
return ticks;
}
/**
* Converts the given value to a tick label string.
*
* @param val the value to convert.
* @param forceFmtFlag true to force the number-formatter object
* to be used.
*
* @return The tick label string.
*/
protected String makeTickLabel(double val, boolean forceFmtFlag) {
if (this.expTickLabelsFlag || forceFmtFlag) {
//using exponents or force-formatter flag is set
// (convert 'E' to lower-case 'e'):
return this.numberFormatterObj.format(val).toLowerCase();
}
return getTickUnit().valueToString(val);
}
/**
* Converts the given value to a tick label string.
* @param val the value to convert.
*
* @return The tick label string.
*/
protected String makeTickLabel(double val) {
return makeTickLabel(val, false);
}
}
|
package org.jivesoftware.smack.packet;
import org.jivesoftware.smack.util.StringUtils;
import java.util.*;
import java.io.*;
/**
* Base class for XMPP packets. Every packet has a unique ID (which is automatically
* generated, but can be overriden). Optionally, the "to" and "from" fields can be set,
* as well as an arbitrary number of properties.
*
* Properties provide an easy mechanism for clients to share data. Each property has a
* String name, and a value that is a Java primitive (int, long, float, double, boolean)
* or any Serializable object (a Java object is Serializable when it implements the
* Serializable interface).
*
* @author Matt Tucker
*/
public abstract class Packet {
/**
* A prefix helps to make sure that ID's are unique across mutliple instances.
*/
private static String prefix = StringUtils.randomString(5);
/**
* Keeps track of the current increment, which is appended to the prefix to
* forum a unique ID.
*/
private static long id = 0;
/**
* Returns the next unique id. Each id made up of a short alphanumeric
* prefix along with a unique numeric value.
*
* @return the next id.
*/
private static synchronized String nextID() {
return prefix + Long.toString(id++);
}
private String packetID = nextID();
private String to = null;
private String from = null;
private Map properties = null;
private Error error = null;
/**
* Returns the unique ID of the packet.
*
* @return the packet's unique ID.
*/
public String getPacketID() {
return packetID;
}
/**
* Sets the unique ID of the packet.
*
* @param packetID the unique ID for the packet.
*/
public void setPacketID(String packetID) {
this.packetID = packetID;
}
/**
* Returns who the packet is being sent "to", or <tt>null</tt> if
* the value is not set. The XMPP protocol often makes the "to"
* attribute optional, so it does not always need to be set.
*
* @return who the packet is being sent to, or <tt>null</tt> if the
* value has not been set.
*/
public String getTo() {
return to;
}
/**
* Sets who the packet is being sent "to". The XMPP protocol often makes
* the "to" attribute optional, so it does not always need to be set.
*
* @param to who the packet is being sent to.
*/
public void setTo(String to) {
this.to = to;
}
/**
* Returns who the packet is being sent "from" or <tt>null</tt> if
* the value is not set. The XMPP protocol often makes the "from"
* attribute optional, so it does not always need to be set.
*
* @return who the packet is being sent from, or <tt>null</tt> if the
* valud has not been set.
*/
public String getFrom() {
return from;
}
/**
* Sets who the packet is being sent "from". The XMPP protocol often
* makes the "from" attribute optional, so it does not always need to
* be set.
*
* @param from who the packet is being sent to.
*/
public void setFrom(String from) {
this.from = from;
}
/**
* Returns the error associated with this packet, or <tt>null</tt> if there are
* no errors.
*
* @return the error sub-packet or <tt>null</tt> if there isn't an error.
*/
public Error getError() {
return error;
}
/**
* Sets the error for this packet.
*
* @param error the error to associate with this packet.
*/
public void setError(Error error) {
this.error = error;
}
/**
* Returns the packet property with the specified name or <tt>null</tt> if the
* property doesn't exist. Property values that were orginally primitives will
* be returned as their object equivalent. For example, an int property will be
* returned as an Integer, a double as a Double, etc.
*
* @param name the name of the property.
* @return the property, or <tt>null</tt> if the property doesn't exist.
*/
public synchronized Object getProperty(String name) {
if (properties == null) {
return null;
}
return properties.get(name);
}
/**
* Sets a packet property with an int value.
*
* @param name the name of the property.
* @param value the value of the property.
*/
public void setProperty(String name, int value) {
setProperty(name, new Integer(value));
}
/**
* Sets a packet property with a long value.
*
* @param name the name of the property.
* @param value the value of the property.
*/
public void setProperty(String name, long value) {
setProperty(name, new Long(value));
}
/**
* Sets a packet property with a float value.
*
* @param name the name of the property.
* @param value the value of the property.
*/
public void setProperty(String name, float value) {
setProperty(name, new Float(value));
}
/**
* Sets a packet property with a double value.
*
* @param name the name of the property.
* @param value the value of the property.
*/
public void setProperty(String name, double value) {
setProperty(name, new Double(value));
}
/**
* Sets a packet property with a bboolean value.
*
* @param name the name of the property.
* @param value the value of the property.
*/
public void setProperty(String name, boolean value) {
setProperty(name, new Boolean(value));
}
public synchronized void setProperty(String name, Object value) {
if (!(value instanceof Serializable)) {
throw new IllegalArgumentException("Value must be serialiazble");
}
if (properties == null) {
properties = new HashMap();
}
properties.put(name, value);
}
/**
* Deletes a property.
*
* @param name the name of the property to delete.
*/
public synchronized void deleteProperty(String name) {
if (properties == null) {
return;
}
properties.remove(name);
}
/**
* Returns an Iterator for all the property names that are set.
*
* @return an Iterator for all property names.
*/
public synchronized Iterator getPropertyNames() {
if (properties == null) {
return Collections.EMPTY_LIST.iterator();
}
return properties.keySet().iterator();
}
/**
* Returns the packet as XML. Every concrete extension of Packet must implement
* this method. In addition to writing out packet-specific data, each extension should
* also write out the error and the properties data if they are defined.
*
* @return the XML format of the packet as a String.
*/
public abstract String toXML();
/**
* Returns the properties portion of the packet as XML or <tt>null</tt> if there are
* no properties.
*
* @return the properties data as XML or <tt>null</tt> if there are no properties.
*/
protected synchronized String getPropertiesXML() {
// Return null if there are no properties.
if (properties == null || properties.isEmpty()) {
return null;
}
StringBuffer buf = new StringBuffer();
buf.append("<x xmlns=\"http:
// Loop through all properties and write them out.
for (Iterator i=getPropertyNames(); i.hasNext(); ) {
String name = (String)i.next();
Object value = getProperty(name);
buf.append("<property>");
buf.append("<name>").append(StringUtils.escapeForXML(name)).append("</name>");
buf.append("<value type=\"");
if (value instanceof Integer) {
buf.append("integer\">").append(value).append("</value>");
}
else if (value instanceof Long) {
buf.append("long\">").append(value).append("</value>");
}
else if (value instanceof Float) {
buf.append("float\">").append(value).append("</value>");
}
else if (value instanceof Double) {
buf.append("double\">").append(value).append("</value>");
}
else if (value instanceof Boolean) {
buf.append("boolean\">").append(value).append("</value>");
}
else if (value instanceof String) {
buf.append("string\">");
buf.append(StringUtils.escapeForXML((String)value));
buf.append("</value>");
}
// Otherwise, it's a generic Serializable object. Serialized objects are in
// a binary format, which won't work well inside of XML. Therefore, we base-64
// encode the binary data before adding it to the SOAP payload.
else {
try {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteStream);
out.writeObject(value);
String encodedVal = StringUtils.encodeBase64(byteStream.toByteArray());
buf.append("java-object\">");
buf.append(encodedVal).append("</value>");
}
catch (Exception e) {
}
}
buf.append("</property>");
}
buf.append("</x>");
return buf.toString();
}
}
|
package org.jetel.util.file;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.Adler32;
import java.util.zip.Checksum;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.data.Defaults;
import org.jetel.enums.ArchiveType;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.graph.ContextProvider;
import org.jetel.graph.TransformationGraph;
import org.jetel.util.MultiOutFile;
import org.jetel.util.bytes.SystemOutByteChannel;
import org.jetel.util.protocols.ftp.FTPStreamHandler;
import org.jetel.util.protocols.proxy.ProxyHandler;
import org.jetel.util.protocols.proxy.ProxyProtocolEnum;
import org.jetel.util.protocols.sandbox.SandboxStreamHandler;
import org.jetel.util.protocols.sftp.SFTPConnection;
import org.jetel.util.protocols.sftp.SFTPStreamHandler;
import com.ice.tar.TarEntry;
import com.ice.tar.TarInputStream;
import com.jcraft.jsch.ChannelSftp;
/**
* Helper class with some useful methods regarding file manipulation
*
* @author dpavlis
* @since May 24, 2002
* @revision $Revision$
*/
public class FileUtils {
// for embedded source
// "something : ( something ) [#something]?
// ([^:]*) (:) (\\() (.*) (\\)) (((
private final static Pattern INNER_SOURCE = Pattern.compile("(([^:]*)([:])([\\(]))(.*)(\\))(((
// standard input/output source
private final static String STD_SOURCE = "-";
// sftp protocol handler
public static final SFTPStreamHandler sFtpStreamHandler = new SFTPStreamHandler();
// ftp protocol handler
public static final FTPStreamHandler ftpStreamHandler = new FTPStreamHandler();
// proxy protocol handler
public static final ProxyHandler proxyHandler = new ProxyHandler();
// file protocol name
private static final String FILE_PROTOCOL = "file";
private static final String FILE_PROTOCOL_ABSOLUTE_MARK = "file:./";
private static final Log log = LogFactory.getLog(FileUtils.class);
public static URL getFileURL(String fileURL) throws MalformedURLException {
return getFileURL((URL) null, fileURL);
}
public static URL getFileURL(String contextURL, String fileURL) throws MalformedURLException {
return getFileURL(getFileURL((URL) null, contextURL), fileURL);
}
/**
* Creates URL object based on specified fileURL string. Handles
* situations when <code>fileURL</code> contains only path to file
* <i>(without "file:" string)</i>.
*
* @param contextURL context URL for converting relative to absolute path (see TransformationGraph.getProjectURL())
* @param fileURL string containing file URL
* @return URL object or NULL if object can't be created (due to Malformed URL)
* @throws MalformedURLException
*/
public static URL getFileURL(URL contextURL, String fileURL) throws MalformedURLException {
// remove mark for absolute path
if (contextURL != null && fileURL.startsWith(FILE_PROTOCOL_ABSOLUTE_MARK)) {
fileURL = fileURL.substring((FILE_PROTOCOL+":").length());
}
// standard url
try {
return new URL(contextURL, fileURL);
} catch(MalformedURLException ex) {}
// sftp url
try {
// ftp connection is connected via sftp handler, 22 port is ok but 21 is somehow blocked for the same connection
return new URL(contextURL, fileURL, sFtpStreamHandler);
} catch(MalformedURLException e) {}
// proxy url
try {
return new URL(contextURL, fileURL, proxyHandler);
} catch(MalformedURLException e) {}
// sandbox url
try {
if (fileURL.startsWith(SandboxStreamHandler.SANDBOX_PROTOCOL)){
TransformationGraph graph = ContextProvider.getGraph();
if (graph == null)
throw new NullPointerException("Graph reference cannot be null when \""+SandboxStreamHandler.SANDBOX_PROTOCOL+"\" protocol is used.");
return new URL(contextURL, fileURL, new SandboxStreamHandler(graph));
}
} catch(MalformedURLException e) {}
// file url
return new URL(contextURL, "file:" + fileURL);
}
/**
* Calculates checksum of specified file.<br>Is suitable for short files (not very much buffered).
*
* @param filename Filename (full path) of file to calculate checksum for
* @return Calculated checksum or -1 if some error (IO) occured
*/
public static long calculateFileCheckSum(String filename) {
byte[] buffer = new byte[1024];
Checksum checksum = new Adler32(); // we use Adler - should be faster
int length = 0;
try {
FileInputStream dataFile = new FileInputStream(filename);
try {
while (length != -1) {
length = dataFile.read(buffer);
if (length > 0) {
checksum.update(buffer, 0, length);
}
}
} finally {
dataFile.close();
}
} catch (IOException ex) {
return -1;
}
return checksum.getValue();
}
/**
* Reads file specified by URL. The content is returned as String
* @param contextURL context URL for converting relative to absolute path (see TransformationGraph.getProjectURL())
* @param fileURL URL specifying the location of file from which to read
* @return
*/
public static String getStringFromURL(URL contextURL, String fileURL, String charset){
URL url;
String chSet = charset != null ? charset : Defaults.DataParser.DEFAULT_CHARSET_DECODER;
try {
url = FileUtils.getFileURL(contextURL, fileURL);
}catch(MalformedURLException ex){
throw new RuntimeException("Wrong URL of file specified: "+ex.getMessage());
}
StringBuffer sb = new StringBuffer(2048);
char[] charBuf=new char[256];
try {
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), chSet));
try {
int readNum;
while ((readNum = in.read(charBuf, 0, charBuf.length)) != -1) {
sb.append(charBuf, 0, readNum);
}
} finally {
in.close();
}
} catch (IOException ex) {
throw new RuntimeException("Can't get string from file " + fileURL + " : " + ex.getMessage());
}
return sb.toString();
}
/**
* Creates ReadableByteChannel from the url definition.
* <p>
* All standard url format are acceptable plus extended form of url by zip & gzip construction:
* </p>
* Examples:
* <dl>
* <dd>zip:<url_to_zip_file>#<inzip_path_to_file></dd>
* <dd>gzip:<url_to_gzip_file></dd>
* </dl>
*
* @param contextURL
* context URL for converting relative to absolute path (see TransformationGraph.getProjectURL())
* @param input
* URL of file to read
* @return
* @throws IOException
*/
public static ReadableByteChannel getReadableChannel(URL contextURL, String input) throws IOException {
InputStream in = getInputStream(contextURL, input);
//incremental reader needs FileChannel:
return in instanceof FileInputStream ? ((FileInputStream)in).getChannel() : Channels.newChannel(in);
}
/**
* Creates InputStream from the url definition.
* <p>
* All standard url format are acceptable plus extended form of url by zip & gzip construction:
* </p>
* Examples:
* <dl>
* <dd>zip:<url_to_zip_file>#<inzip_path_to_file></dd>
* <dd>gzip:<url_to_gzip_file></dd>
* </dl>
* For zip file, if anchor is not set there is return first zip entry.
*
* @param contextURL
* context URL for converting relative to absolute path (see TransformationGraph.getProjectURL())
* @param input
* URL of file to read
* @return
* @throws IOException
* @throws IOException
*/
public static InputStream getInputStream(URL contextURL, String input) throws IOException {
// std input (console)
if (input.equals(STD_SOURCE)) {
return System.in;
}
// get inner source
Matcher matcher = FileURLParser.getURLMatcher(input);
String innerSource;
InputStream innerStream = null;
if (matcher != null && (innerSource = matcher.group(5)) != null) {
// get and set proxy and go to inner source
Proxy proxy = getProxy(innerSource);
input = matcher.group(2) + matcher.group(3) + matcher.group(7);
innerStream = proxy == null ? getInputStream(contextURL, innerSource)
: getAuthorizedProxyConnection(getFileURL(contextURL, input), proxy).getInputStream();
}
// get archive type
StringBuilder sbAnchor = new StringBuilder();
StringBuilder sbInnerInput = new StringBuilder();
ArchiveType archiveType = getArchiveType(input, sbInnerInput, sbAnchor);
input = sbInnerInput.toString();
//open channel
URL url = null;
if (innerStream == null) {
url = FileUtils.getFileURL(contextURL, input);
// creates file input stream for incremental reading (random access file)
if (archiveType == null && url.getProtocol().equals(FILE_PROTOCOL)) {
return new FileInputStream(url.getFile());
} else if (archiveType == null && url.getProtocol().equals(SandboxStreamHandler.SANDBOX_PROTOCOL)) {
TransformationGraph graph = ContextProvider.getGraph();
if (graph == null)
throw new NullPointerException("Graph reference cannot be null when \""+SandboxStreamHandler.SANDBOX_PROTOCOL+"\" protocol is used.");
return graph.getAuthorityProxy().getSandboxResourceInput(graph.getRuntimeContext().getRunId(), url.getHost(), url.getPath());
}
try {
innerStream = getAuthorizedConnection(url).getInputStream();
} catch (IOException e) {
log.debug("IOException occured for URL - host: '" + url.getHost() + "', userinfo: '" + url.getUserInfo() + "', path: '" + url.getPath() + "'");
throw e;
}
}
// create archive streams
if (archiveType == ArchiveType.ZIP) {
List<InputStream> lIs = getZipInputStreamsInner(innerStream, sbAnchor.toString(), 0, null);
return lIs.size() > 0 ? lIs.get(0) : null;
} else if (archiveType == ArchiveType.GZIP) {
return new GZIPInputStream(innerStream, Defaults.DEFAULT_IOSTREAM_CHANNEL_BUFFER_SIZE);
} else if (archiveType == ArchiveType.TAR) {
List<InputStream> lIs = getTarInputStreamsInner(innerStream, sbAnchor.toString(), 0, null);
return lIs.size() > 0 ? lIs.get(0) : null;
}
return innerStream;
}
/**
* Gets archive type.
* @param input - input file
* @param innerInput - output parameter
* @param anchor - output parameter
* @return
*/
public static ArchiveType getArchiveType(String input, StringBuilder innerInput, StringBuilder anchor) {
// result value
ArchiveType archiveType = null;
//resolve url format for zip files
if (input.startsWith("zip:")) archiveType = ArchiveType.ZIP;
else if (input.startsWith("tar:")) archiveType = ArchiveType.TAR;
else if (input.startsWith("gzip:")) archiveType = ArchiveType.GZIP;
// parse the archive
if((archiveType == ArchiveType.ZIP) || (archiveType == ArchiveType.TAR)) {
if(!input.contains("#")) { //url is given without anchor - later is returned channel from first zip entry
anchor = null;
innerInput.append(input.substring(input.indexOf(':') + 1));
} else {
anchor.append(input.substring(input.lastIndexOf('
innerInput.append(input.substring(input.indexOf(':') + 1, input.lastIndexOf('
}
}
else if (archiveType == ArchiveType.GZIP) {
innerInput.append(input.substring(input.indexOf(':') + 1));
}
// if doesn't exist inner input, inner input is input
if (innerInput.length() == 0) innerInput.append(input);
return archiveType;
}
/**
* Creates a zip input stream.
* @param innerStream
* @param anchor
* @param resolvedAnchors - output parameter
* @return
* @throws IOException
*/
public static List<InputStream> getZipInputStreams(InputStream innerStream, String anchor, List<String> resolvedAnchors) throws IOException {
return getZipInputStreamsInner(innerStream, anchor, 0, resolvedAnchors);
}
/**
* Creates list of zip input streams.
* @param innerStream
* @param anchor
* @param matchFilesFrom
* @param resolvedAnchors
* @return
* @throws IOException
*/
private static List<InputStream> getZipInputStreamsInner(InputStream innerStream, String anchor,
int matchFilesFrom, List<String> resolvedAnchors) throws IOException {
// result list of input streams
List<InputStream> streams = new ArrayList<InputStream>();
// check and prepare support for wild card matching
Matcher matcher;
Pattern WILDCARD_PATTERS = null;
boolean bWildsCardedAnchor = anchor.contains("?") || anchor.contains("*");
if (bWildsCardedAnchor)
WILDCARD_PATTERS = Pattern.compile(anchor.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\.", "\\\\.").replaceAll("\\?", "\\.").replaceAll("\\*", ".*"));
// the input stream must support a buffer for wild cards.
if (bWildsCardedAnchor) {
if (!innerStream.markSupported()) {
innerStream = new BufferedInputStream(innerStream);
}
innerStream.mark(Integer.MAX_VALUE);
}
//resolve url format for zip files
ZipInputStream zin = new ZipInputStream(innerStream) ;
ZipEntry entry;
// find entries
int iMatched = 0;
while((entry = zin.getNextEntry()) != null) { // zin is changing -> recursion !!!
// wild cards
if (bWildsCardedAnchor) {
matcher = WILDCARD_PATTERS.matcher(entry.getName());
if (matcher.find() && iMatched++ == matchFilesFrom) {
streams.add(zin);
if (resolvedAnchors != null) resolvedAnchors.add(entry.getName());
innerStream.reset();
streams.addAll(getZipInputStreamsInner(innerStream, anchor, ++matchFilesFrom, resolvedAnchors));
innerStream.reset();
return streams;
}
// without wild cards
} else if(anchor == null || anchor.equals("") || entry.getName().equals(anchor)) { //url is given without anchor; first entry in zip file is used
streams.add(zin);
if (resolvedAnchors != null) resolvedAnchors.add(anchor);
return streams;
}
//finish up with entry
zin.closeEntry();
}
if (matchFilesFrom > 0 || streams.size() > 0) return streams;
// if no wild carded entry found, it is ok, return null
if (bWildsCardedAnchor) return null;
//close the archive
zin.close();
//no channel found report
if(anchor == null) {
throw new IOException("Zip file is empty.");
} else {
throw new IOException("Wrong anchor (" + anchor + ") to zip file.");
}
}
/**
* Creates a tar input stream.
* @param innerStream
* @param anchor
* @param resolvedAnchors - output parameter
* @return
* @throws IOException
*/
public static List<InputStream> getTarInputStreams(InputStream innerStream, String anchor, List<String> resolvedAnchors) throws IOException {
return getTarInputStreamsInner(innerStream, anchor, 0, resolvedAnchors);
}
/**
* Creates list of tar input streams.
* @param innerStream
* @param anchor
* @param matchFilesFrom
* @param resolvedAnchors
* @return
* @throws IOException
*/
private static List<InputStream> getTarInputStreamsInner(InputStream innerStream, String anchor,
int matchFilesFrom, List<String> resolvedAnchors) throws IOException {
// result list of input streams
List<InputStream> streams = new ArrayList<InputStream>();
// check and prepare support for wild card matching
Matcher matcher;
Pattern WILDCARD_PATTERS = null;
boolean bWildsCardedAnchor = anchor.contains("?") || anchor.contains("*");
if (bWildsCardedAnchor)
WILDCARD_PATTERS = Pattern.compile(anchor.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\.", "\\\\.").replaceAll("\\?", "\\.").replaceAll("\\*", ".*"));
// the input stream must support a buffer for wild cards.
if (bWildsCardedAnchor) {
if (!innerStream.markSupported()) {
innerStream = new BufferedInputStream(innerStream);
}
innerStream.mark(Integer.MAX_VALUE);
}
//resolve url format for zip files
TarInputStream tin = new TarInputStream(innerStream);
TarEntry entry;
// find entries
int iMatched = 0;
while((entry = tin.getNextEntry()) != null) { // tin is changing -> recursion !!!
// wild cards
if (bWildsCardedAnchor) {
matcher = WILDCARD_PATTERS.matcher(entry.getName());
if (matcher.find() && iMatched++ == matchFilesFrom) {
streams.add(tin);
if (resolvedAnchors != null) resolvedAnchors.add(entry.getName());
innerStream.reset();
streams.addAll(getTarInputStreamsInner(innerStream, anchor, ++matchFilesFrom, resolvedAnchors));
innerStream.reset();
return streams;
}
// without wild cards
} else if(anchor == null || anchor.equals("") || entry.getName().equals(anchor)) { //url is given without anchor; first entry in zip file is used
streams.add(tin);
if (resolvedAnchors != null) resolvedAnchors.add(anchor);
return streams;
}
}
if (matchFilesFrom > 0 || streams.size() > 0) return streams;
// if no wild carded entry found, it is ok, return null
if (bWildsCardedAnchor) return null;
//close the archive
tin.close();
//no channel found report
if(anchor == null) {
throw new IOException("Tar file is empty.");
} else {
throw new IOException("Wrong anchor (" + anchor + ") to tar file.");
}
}
/**
* Creates authorized url connection.
* @param url
* @return
* @throws IOException
*/
public static URLConnection getAuthorizedConnection(URL url) throws IOException {
return URLConnectionRequest.getAuthorizedConnection(
url.openConnection(),
url.getUserInfo(),
URLConnectionRequest.URL_CONNECTION_AUTHORIZATION);
}
/**
* Creates an authorized stream.
* @param url
* @return
* @throws IOException
*/
private static URLConnection getAuthorizedProxyConnection(URL url, Proxy proxy) throws IOException {
return URLConnectionRequest.getAuthorizedConnection(
url.openConnection(proxy),
url.getUserInfo(),
URLConnectionRequest.URL_CONNECTION_PROXY_AUTHORIZATION);
}
/**
* Creates an proxy from the file url string.
* @param fileURL
* @return
*/
public static Proxy getProxy(String fileURL) {
// create an url
URL url;
try {
url = getFileURL(fileURL);
} catch (MalformedURLException e) {
return null;
}
// get proxy type
ProxyProtocolEnum proxyProtocolEnum;
if ((proxyProtocolEnum = ProxyProtocolEnum.fromString(url.getProtocol())) == null) {
return null;
}
// no proxy
if (proxyProtocolEnum == ProxyProtocolEnum.NO_PROXY) {
return Proxy.NO_PROXY;
}
// create a proxy
SocketAddress addr = new InetSocketAddress(url.getHost(), url.getPort() < 0 ? 8080 : url.getPort());
Proxy proxy = new Proxy(Proxy.Type.valueOf(proxyProtocolEnum.getProxyString()), addr);
return proxy;
}
public static WritableByteChannel getWritableChannel(URL contextURL, String input, boolean appendData, int compressLevel) throws IOException {
return Channels.newChannel(getOutputStream(contextURL, input, appendData, compressLevel));
}
public static WritableByteChannel getWritableChannel(URL contextURL, String input, boolean appendData) throws IOException {
return getWritableChannel(contextURL, input, appendData, -1);
}
public static OutputStream getOutputStream(URL contextURL, String input, boolean appendData, int compressLevel)
throws IOException {
// std input (console)
if (input.equals(STD_SOURCE)) {
return Channels.newOutputStream(new SystemOutByteChannel());
}
// get inner source
Matcher matcher = getInnerInput(input);
String innerSource;
OutputStream os = null;
if (matcher != null && (innerSource = matcher.group(5)) != null) {
// get and set proxy and go to inner source
Proxy proxy = getProxy(innerSource);
input = matcher.group(2) + matcher.group(3) + matcher.group(7);
os = proxy == null ? getOutputStream(null, innerSource, appendData, compressLevel) : getAuthorizedProxyConnection(getFileURL((URL)null, input), proxy).getOutputStream();
}
// get archive type
StringBuilder sbAnchor = new StringBuilder();
StringBuilder sbInnerInput = new StringBuilder();
ArchiveType archiveType = getArchiveType(input, sbInnerInput, sbAnchor);
input = sbInnerInput.toString();
boolean isFtp = false;
if (input.startsWith("ftp") || input.startsWith("sftp") || input.startsWith("scp")) {
isFtp = true;
}
//open channel
if (os == null) {
// create output stream
if(isFtp) {
// ftp output stream
URL url = FileUtils.getFileURL(contextURL, input);
URLConnection urlConnection = url.openConnection();
if (urlConnection instanceof SFTPConnection) {
((SFTPConnection)urlConnection).setMode(appendData? ChannelSftp.APPEND : ChannelSftp.OVERWRITE);
}
try {
os = urlConnection.getOutputStream();
} catch (IOException e) {
log.debug("IOException occured for URL - host: '" + url.getHost() + "', userinfo: '" + url.getUserInfo() + "', path: '" + url.getPath() + "'");
throw e;
}
} else if (input.startsWith(SandboxStreamHandler.SANDBOX_PROTOCOL)) {
TransformationGraph graph = ContextProvider.getGraph();
if (graph == null)
throw new NullPointerException("Graph reference cannot be null when \""+SandboxStreamHandler.SANDBOX_PROTOCOL+"\" protocol is used.");
URL url = FileUtils.getFileURL(contextURL, input);
return graph.getAuthorityProxy().getSandboxResourceOutput(graph.getRuntimeContext().getRunId(), url.getHost(), url.getPath());
} else {
// file input stream
String filePath = FileUtils.getFile(contextURL, input);
os = new FileOutputStream(filePath, appendData);
}
}
// create writable channel
// zip channel
if(archiveType == ArchiveType.ZIP) {
// resolve url format for zip files
ZipOutputStream zout = new ZipOutputStream(os);
if (compressLevel != -1) {
zout.setLevel(compressLevel);
}
String anchor = sbAnchor.toString();
ZipEntry entry = new ZipEntry(anchor.equals("") ? "default_output" : anchor);
zout.putNextEntry(entry);
return zout;
}
// gzip channel
else if (archiveType == ArchiveType.GZIP) {
GZIPOutputStream gzos = new GZIPOutputStream(os, Defaults.DEFAULT_IOSTREAM_CHANNEL_BUFFER_SIZE);
return gzos;
}
// other channel
return os;
}
/**
* This method checks whether it is possible to write to given file.
*
* @param contextURL
* @param fileURL
* @param mkDirs - tries to make directories if it is necessary
* @return true if can write, false otherwise
* @throws ComponentNotReadyException
*/
public static boolean canWrite(URL contextURL, String fileURL, boolean mkDirs) throws ComponentNotReadyException {
// get inner source
Matcher matcher = getInnerInput(fileURL);
String innerSource;
if (matcher != null && (innerSource = matcher.group(5)) != null) {
return canWrite(contextURL, innerSource, mkDirs);
}
String fileName;
if (fileURL.startsWith("zip:") || fileURL.startsWith("tar:")){
int pos;
fileName = fileURL.substring(fileURL.indexOf(':') + 1,
(pos = fileURL.indexOf('#')) == -1 ? fileURL.length() : pos);
}else if (fileURL.startsWith("gzip:")){
fileName = fileURL.substring(fileURL.indexOf(':') + 1);
}else{
fileName = fileURL;
}
MultiOutFile multiOut = new MultiOutFile(fileName);
File file;
URL url;
boolean tmp = false;
//create file on given URL
try {
String filename = multiOut.next();
if(filename.startsWith("port:")) return true;
if(filename.startsWith("dict:")) return true;
url = getFileURL(contextURL, filename);
if(!url.getProtocol().equalsIgnoreCase("file")) return true;
// if the url is a path, make a fake file
String sUrl = url.getPath();
boolean isFile = !sUrl.endsWith("/") && !sUrl.endsWith("\\");
if (!isFile) sUrl = sUrl + "tmpfile" + Math.abs(sUrl.hashCode());
file = new File(sUrl);
} catch (Exception e) {
throw new ComponentNotReadyException(e + ": " + fileURL);
}
//check if can write to this file
tmp = file.exists() ? file.canWrite() : createFile(file, mkDirs);
if (!tmp) {
throw new ComponentNotReadyException("Can't write to: " + fileURL);
}
return true;
}
/**
* Creates directory for fileURL if it is necessary.
* @param contextURL
* @param fileURL
* @return created parent directory
* @throws ComponentNotReadyException
*/
public static File makeDirs(URL contextURL, String fileURL) throws ComponentNotReadyException {
if (contextURL == null && fileURL == null) return null;
URL url;
try {
url = FileUtils.getFileURL(contextURL, FileURLParser.getMostInnerAddress(fileURL));
} catch (MalformedURLException e) {
return null;
}
if (!url.getProtocol().equals(FILE_PROTOCOL)) return null;
//find the first non-existing directory
File file = new File(url.getPath());
File fileTmp = file;
File createDir = null;
while (fileTmp != null && !fileTmp.exists()) {
createDir = fileTmp;
fileTmp = fileTmp.getParentFile();
}
if (createDir != null && !file.mkdirs()) throw new ComponentNotReadyException("Cannot create directory: " + file);
return createDir;
}
/**
* Tries to create file and directories.
* @param fileURL
* @return
* @throws ComponentNotReadyException
*/
private static boolean createFile(File file, boolean mkDirs) throws ComponentNotReadyException {
boolean tmp = false;
boolean fails = false;
try {
tmp = file.createNewFile();
} catch (IOException e) {
if (!mkDirs) throw new ComponentNotReadyException(e + ": " + file);
fails = true;
}
File createdDir = null;
if (fails) {
createdDir = file.getParentFile();
createdDir = makeDirs(null, createdDir.getAbsolutePath());
try {
tmp = file.createNewFile();
} catch (IOException e) {
if (createdDir != null) {
if (!deleteFile(createdDir)) {
log.error("error delete " + createdDir);
}
}
throw new ComponentNotReadyException(e + ": " + file);
}
}
if (tmp) {
if (!file.delete()) {
log.error("error delete " + file.getAbsolutePath());
}
}
if (createdDir != null) {
if (!deleteFile(createdDir)) {
log.error("error delete " + createdDir);
}
}
return tmp;
}
/**
* Deletes file.
* @param file
* @return true if the file is deleted
*/
private static boolean deleteFile(File file) {
if (!file.exists()) return true;
//list and delete all sub-directories
for (File child: file.listFiles()) {
if (!deleteFile(child)) {
return false;
}
}
return file.delete();
}
/**
* This method checks whether is is possible to write to given file
*
* @param contextURL
* @param fileURL
* @return true if can write, false otherwise
* @throws ComponentNotReadyException
*/
public static boolean canWrite(URL contextURL, String fileURL) throws ComponentNotReadyException {
return canWrite(contextURL, fileURL, false);
}
/**
* This method checks whether is is possible to write to given directory
*
* @param dest
* @return true if can write, false otherwise
*/
public static boolean canWrite(File dest){
if (dest.exists()) return dest.canWrite();
List<File> dirs = getDirs(dest);
boolean result = dest.mkdirs();
//clean up
for (File dir : dirs) {
if (dir.exists()) {
boolean deleted = dir.delete();
if( !deleted ){
log.error("error delete " + dir.getAbsolutePath());
}
}
}
return result;
}
/**
* @param file
* @return list of directories, which have to be created to create this directory (don't exist),
* empty list if requested directory exists
*/
private static List<File> getDirs(File file){
ArrayList<File> dirs = new ArrayList<File>();
File dir = file;
if (file.exists()) return dirs;
dirs.add(file);
while (!(dir = dir.getParentFile()).exists()) {
dirs.add(dir);
}
return dirs;
}
public static Matcher getInnerInput(String source) {
Matcher matcher = INNER_SOURCE.matcher(source);
return matcher.find() ? matcher : null;
}
/**
* Returns file name of input (URL).
*
* @param input - url file name
* @return file name
* @throws MalformedURLException
*
* @see java.net.URL#getFile()
*/
public static String getFile(URL contextURL, String input) throws MalformedURLException {
Matcher matcher = getInnerInput(input);
String innerSource2, innerSource3;
if (matcher != null && (innerSource2 = matcher.group(5)) != null) {
if (!(innerSource3 = matcher.group(7)).equals("")) {
return innerSource3.substring(1);
} else {
input = getFile(null, innerSource2);
}
}
URL url = getFileURL(contextURL, input);
if (url.getRef() != null) return url.getRef();
else {
input = url.getFile();
if (input.startsWith("zip:") || input.startsWith("tar:")) {
input = input.contains("
input.substring(input.lastIndexOf('
input.substring(input.indexOf(':') + 1);
} else if (input.startsWith("gzip:")) {
input = input.substring(input.indexOf(':') + 1);
}
return input;
}
}
/**
* Adds final slash to the directory path, if it is necessary.
* @param directoryPath
* @return
*/
public static String appendSlash(String directoryPath) {
if(directoryPath.length() == 0 || directoryPath.endsWith("/") || directoryPath.endsWith("\\")) {
return directoryPath;
} else {
return directoryPath + "/";
}
}
/**
* Parses address and returns true if the address contains a server.
*
* @param input
* @return
* @throws IOException
*/
public static boolean isServerURL(URL url) throws IOException {
return url != null && !url.getProtocol().equals(FILE_PROTOCOL);
}
/**
* Creates URL connection and connect the server.
*
* @param url
* @throws IOException
*/
public static void checkServer(URL url) throws IOException {
if (url == null) {
return;
}
URLConnection connection = url.openConnection();
connection.connect();
if (connection instanceof SFTPConnection) {
((SFTPConnection) connection).disconnect();
}
}
/**
* Gets the most inner url address.
* @param contextURL
*
* @param input
* @return
* @throws IOException
*/
public static URL getInnerAddress(URL contextURL, String input) throws IOException {
URL url = null;
// get inner source
Matcher matcher = getInnerInput(input);
String innerSource;
if (matcher != null && (innerSource = matcher.group(5)) != null) {
url = getInnerAddress(contextURL, innerSource);
input = matcher.group(2) + matcher.group(3) + matcher.group(7);
}
// std input (console)
if (input.equals(STD_SOURCE)) {
return null;
}
//resolve url format for zip files
if(input.startsWith("zip:") || input.startsWith("tar:")) {
if(!input.contains("#")) { //url is given without anchor - later is returned channel from first zip entry
input = input.substring(input.indexOf(':') + 1);
} else {
input = input.substring(input.indexOf(':') + 1, input.lastIndexOf('
}
}
else if (input.startsWith("gzip:")) {
input = input.substring(input.indexOf(':') + 1);
}
return url == null ? FileUtils.getFileURL(contextURL, input) : url;
}
}
/*
* End class FileUtils
*/
|
package model.state;
import exceptions.InvalidDimensionException;
import exceptions.InvalidStringRepresentationException;
/**
* A class to imitate a FuzzyState
* @author Balazs Pete
*
*/
public class PseudoState extends FuzzyPoint {
/**
* Create an instance of PseudoState
* @param x x-value
* @param y y-value
* @param z z-value
*/
public PseudoState(FuzzyNumber x, FuzzyNumber y, FuzzyNumber z) {
this.x = x;
this.y = y;
this.z = z;
}
/**
* Create an instance of PseudoState from its string representation
* @param stringRepresentation the string representation
* @throws InvalidStringRepresentationException Thrown if string representation is not correct
*/
public PseudoState(String stringRepresentation) throws InvalidStringRepresentationException {
fromString(stringRepresentation);
}
/**
* Get a String representation of the object
*/
public String toString() {
return (x == null ? ", " : x.toString()) + ", " + (y == null ? "," : y.toString()) + ", " + (z==null ? "," : z.toString());
}
/**
* Calculate a PseudoState representing a Vector |point2 - point1|
* @param point1
* @param point2
* @return the resulting PseudoState
*/
public static PseudoState getDifference(FuzzyPoint point1, FuzzyPoint point2) {
return getDifference(point1, point2, 100);
}
/**
* Calculate a PseudoState representing a Vector |point2 - point1| within a given scale
* @param point1
* @param point2
* @param The scale of the calculation
* @return the resulting PseudoState
*/
public static PseudoState getDifference(FuzzyPoint point1, FuzzyPoint point2, double scale) {
FuzzyNumber x, y, z;
try {
x = getDifferenceHelper(point1.getX(), point2.getX(), scale);
} catch (InvalidDimensionException e) {
x = null;
}
try {
y = getDifferenceHelper(point1.getY(), point2.getY(), scale);
} catch (InvalidDimensionException e) {
y = null;
}
try {
z = getDifferenceHelper(point1.getZ(), point2.getZ(), scale);
} catch (InvalidDimensionException e) {
z = null;
}
return new PseudoState(x, y, z);
}
/**
* A Method to help calculate the difference between two FuzzyNumbers
* @param a Fuzzy number 1
* @param b Fuzzy number 2
* @param scale
* @return
*/
private static FuzzyNumber getDifferenceHelper(FuzzyNumber a, FuzzyNumber b, double scale) {
double value = b.getValue() - a.getValue();
double errorValue = ((a.getError() + b.getError()) / 100) * scale;
return new FuzzyNumber(value, errorValue / value);
}
/**
* Parse the string and populate instance variables
* @param strRep The String representation
* @throws InvalidStringRepresentationException Thrown if string representation is not correct
*/
private void fromString(String strRep) throws InvalidStringRepresentationException {
String[] rep = strRep.split(",");
if(rep.length != 6) throw new InvalidStringRepresentationException(strRep);
this.x = getFuzzyNumber(rep, 0);
this.y = getFuzzyNumber(rep, 2);
this.z = getFuzzyNumber(rep, 4);
}
/**
* Method to get a FuzzyNumber
* @param rep The split String representation
* @param i The index of the value
* @return The creates FuzzyNumber
*/
private FuzzyNumber getFuzzyNumber(String[] rep, int i) {
if(i > rep.length - 1 || i < 0) return null;
return this.x = rep[i].equals("") ? null : new FuzzyNumber(Double.parseDouble(rep[i]), Double.parseDouble(rep[i + 1]));
}
}
|
package java.lang;
public class String implements CharSequence {
char[] _value;
int _count;
// use this constructor as it includes "count"
// ignore offset at the moment
public String(char[] ca, int offset, int count) {
_value = ca;
_count = count;
}
public int length() {
return _count;
}
public String toString() {
return this;
}
public boolean equals(String s) {
return _value == s._value;
}
public int indexOf(String str) {
return indexOf(str, 0);
}
public int indexOf(String str, int fromIndex) {
int src_len = _count;
int tgt_len = str._count;
if (fromIndex >= src_len) {
if (tgt_len == 0) return src_len;
else return -1;
}
if (fromIndex < 0) fromIndex = 0;
if (tgt_len == 0) return fromIndex;
int index = fromIndex;
int gap = src_len - tgt_len;
while (index <= gap) {
boolean mismatch = false;
int i = 0;
while (i < tgt_len && !mismatch) {
if (_value[index + i] != str._value[i]) {
mismatch = true;
}
i = i + 1;
}
if (!mismatch) return index;
index = index + 1;
}
return -1;
}
}
|
package com.fsck.k9.activity;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.text.TextWatcher;
import android.text.util.Rfc822Tokenizer;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AutoCompleteTextView.Validator;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;
import com.fsck.k9.Account;
import com.fsck.k9.Account.MessageFormat;
import com.fsck.k9.Account.QuoteStyle;
import com.fsck.k9.EmailAddressAdapter;
import com.fsck.k9.EmailAddressValidator;
import com.fsck.k9.FontSizes;
import com.fsck.k9.Identity;
import com.fsck.k9.K9;
import com.fsck.k9.Preferences;
import com.fsck.k9.R;
import com.fsck.k9.activity.loader.AttachmentContentLoader;
import com.fsck.k9.activity.loader.AttachmentInfoLoader;
import com.fsck.k9.activity.misc.Attachment;
import com.fsck.k9.controller.MessagingController;
import com.fsck.k9.controller.MessagingListener;
import com.fsck.k9.crypto.CryptoProvider;
import com.fsck.k9.crypto.PgpData;
import com.fsck.k9.fragment.ProgressDialogFragment;
import com.fsck.k9.helper.ContactItem;
import com.fsck.k9.helper.Contacts;
import com.fsck.k9.helper.HtmlConverter;
import com.fsck.k9.helper.StringUtils;
import com.fsck.k9.helper.Utility;
import com.fsck.k9.mail.Address;
import com.fsck.k9.mail.Body;
import com.fsck.k9.mail.Flag;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.Message.RecipientType;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Multipart;
import com.fsck.k9.mail.Part;
import com.fsck.k9.mail.internet.MimeBodyPart;
import com.fsck.k9.mail.internet.MimeHeader;
import com.fsck.k9.mail.internet.MimeMessage;
import com.fsck.k9.mail.internet.MimeMultipart;
import com.fsck.k9.mail.internet.MimeUtility;
import com.fsck.k9.mail.internet.TextBody;
import com.fsck.k9.mail.store.LocalStore.LocalAttachmentBody;
import com.fsck.k9.mail.store.LocalStore.TempFileBody;
import com.fsck.k9.mail.store.LocalStore.TempFileMessageBody;
import com.fsck.k9.view.MessageWebView;
import org.apache.james.mime4j.codec.EncoderUtil;
import org.apache.james.mime4j.util.MimeUtil;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.SimpleHtmlSerializer;
import org.htmlcleaner.TagNode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MessageCompose extends K9Activity implements OnClickListener,
ProgressDialogFragment.CancelListener {
private static final int DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE = 1;
private static final int DIALOG_REFUSE_TO_SAVE_DRAFT_MARKED_ENCRYPTED = 2;
private static final int DIALOG_CONTINUE_WITHOUT_PUBLIC_KEY = 3;
private static final int DIALOG_CONFIRM_DISCARD_ON_BACK = 4;
private static final int DIALOG_CHOOSE_IDENTITY = 5;
private static final long INVALID_DRAFT_ID = MessagingController.INVALID_MESSAGE_ID;
private static final String ACTION_COMPOSE = "com.fsck.k9.intent.action.COMPOSE";
private static final String ACTION_REPLY = "com.fsck.k9.intent.action.REPLY";
private static final String ACTION_REPLY_ALL = "com.fsck.k9.intent.action.REPLY_ALL";
private static final String ACTION_FORWARD = "com.fsck.k9.intent.action.FORWARD";
private static final String ACTION_EDIT_DRAFT = "com.fsck.k9.intent.action.EDIT_DRAFT";
private static final String EXTRA_ACCOUNT = "account";
private static final String EXTRA_MESSAGE_BODY = "messageBody";
private static final String EXTRA_MESSAGE_REFERENCE = "message_reference";
private static final String STATE_KEY_ATTACHMENTS =
"com.fsck.k9.activity.MessageCompose.attachments";
private static final String STATE_KEY_CC_SHOWN =
"com.fsck.k9.activity.MessageCompose.ccShown";
private static final String STATE_KEY_BCC_SHOWN =
"com.fsck.k9.activity.MessageCompose.bccShown";
private static final String STATE_KEY_QUOTED_TEXT_MODE =
"com.fsck.k9.activity.MessageCompose.QuotedTextShown";
private static final String STATE_KEY_SOURCE_MESSAGE_PROCED =
"com.fsck.k9.activity.MessageCompose.stateKeySourceMessageProced";
private static final String STATE_KEY_DRAFT_ID = "com.fsck.k9.activity.MessageCompose.draftId";
private static final String STATE_KEY_HTML_QUOTE = "com.fsck.k9.activity.MessageCompose.HTMLQuote";
private static final String STATE_IDENTITY_CHANGED =
"com.fsck.k9.activity.MessageCompose.identityChanged";
private static final String STATE_IDENTITY =
"com.fsck.k9.activity.MessageCompose.identity";
private static final String STATE_PGP_DATA = "pgpData";
private static final String STATE_IN_REPLY_TO = "com.fsck.k9.activity.MessageCompose.inReplyTo";
private static final String STATE_REFERENCES = "com.fsck.k9.activity.MessageCompose.references";
private static final String STATE_KEY_READ_RECEIPT = "com.fsck.k9.activity.MessageCompose.messageReadReceipt";
private static final String STATE_KEY_DRAFT_NEEDS_SAVING = "com.fsck.k9.activity.MessageCompose.mDraftNeedsSaving";
private static final String STATE_KEY_FORCE_PLAIN_TEXT =
"com.fsck.k9.activity.MessageCompose.forcePlainText";
private static final String STATE_KEY_QUOTED_TEXT_FORMAT =
"com.fsck.k9.activity.MessageCompose.quotedTextFormat";
private static final String STATE_KEY_NUM_ATTACHMENTS_LOADING = "numAttachmentsLoading";
private static final String STATE_KEY_WAITING_FOR_ATTACHMENTS = "waitingForAttachments";
private static final String LOADER_ARG_ATTACHMENT = "attachment";
private static final String FRAGMENT_WAITING_FOR_ATTACHMENT = "waitingForAttachment";
private static final int MSG_PROGRESS_ON = 1;
private static final int MSG_PROGRESS_OFF = 2;
private static final int MSG_SKIPPED_ATTACHMENTS = 3;
private static final int MSG_SAVED_DRAFT = 4;
private static final int MSG_DISCARDED_DRAFT = 5;
private static final int MSG_PERFORM_STALLED_ACTION = 6;
private static final int ACTIVITY_REQUEST_PICK_ATTACHMENT = 1;
private static final int CONTACT_PICKER_TO = 4;
private static final int CONTACT_PICKER_CC = 5;
private static final int CONTACT_PICKER_BCC = 6;
private static final int CONTACT_PICKER_TO2 = 7;
private static final int CONTACT_PICKER_CC2 = 8;
private static final int CONTACT_PICKER_BCC2 = 9;
private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[0];
/**
* Regular expression to remove the first localized "Re:" prefix in subjects.
*
* Currently:
* - "Aw:" (german: abbreviation for "Antwort")
*/
private static final Pattern PREFIX = Pattern.compile("^AW[:\\s]\\s*", Pattern.CASE_INSENSITIVE);
/**
* The account used for message composition.
*/
private Account mAccount;
private Contacts mContacts;
/**
* This identity's settings are used for message composition.
* Note: This has to be an identity of the account {@link #mAccount}.
*/
private Identity mIdentity;
private boolean mIdentityChanged = false;
private boolean mSignatureChanged = false;
/**
* Reference to the source message (in case of reply, forward, or edit
* draft actions).
*/
private MessageReference mMessageReference;
private Message mSourceMessage;
/**
* "Original" message body
*
* <p>
* The contents of this string will be used instead of the body of a referenced message when
* replying to or forwarding a message.<br>
* Right now this is only used when replying to a signed or encrypted message. It then contains
* the stripped/decrypted body of that message.
* </p>
* <p><strong>Note:</strong>
* When this field is not {@code null} we assume that the message we are composing right now
* should be encrypted.
* </p>
*/
private String mSourceMessageBody;
/**
* Indicates that the source message has been processed at least once and should not
* be processed on any subsequent loads. This protects us from adding attachments that
* have already been added from the restore of the view state.
*/
private boolean mSourceMessageProcessed = false;
private int mMaxLoaderId = 0;
enum Action {
COMPOSE,
REPLY,
REPLY_ALL,
FORWARD,
EDIT_DRAFT
}
/**
* Contains the action we're currently performing (e.g. replying to a message)
*/
private Action mAction;
private enum QuotedTextMode {
NONE,
SHOW,
HIDE
}
private boolean mReadReceipt = false;
private QuotedTextMode mQuotedTextMode = QuotedTextMode.NONE;
/**
* Contains the format of the quoted text (text vs. HTML).
*/
private SimpleMessageFormat mQuotedTextFormat;
/**
* When this it {@code true} the message format setting is ignored and we're always sending
* a text/plain message.
*/
private boolean mForcePlainText = false;
private Button mChooseIdentityButton;
private LinearLayout mCcWrapper;
private LinearLayout mBccWrapper;
private MultiAutoCompleteTextView mToView;
private MultiAutoCompleteTextView mCcView;
private MultiAutoCompleteTextView mBccView;
private EditText mSubjectView;
private EolConvertingEditText mSignatureView;
private EolConvertingEditText mMessageContentView;
private LinearLayout mAttachments;
private Button mQuotedTextShow;
private View mQuotedTextBar;
private ImageButton mQuotedTextEdit;
private ImageButton mQuotedTextDelete;
private EolConvertingEditText mQuotedText;
private MessageWebView mQuotedHTML;
private InsertableHtmlContent mQuotedHtmlContent; // Container for HTML reply as it's being built.
private View mEncryptLayout;
private CheckBox mCryptoSignatureCheckbox;
private CheckBox mEncryptCheckbox;
private TextView mCryptoSignatureUserId;
private TextView mCryptoSignatureUserIdRest;
private ImageButton mAddToFromContacts;
private ImageButton mAddCcFromContacts;
private ImageButton mAddBccFromContacts;
private PgpData mPgpData = null;
private boolean mAutoEncrypt = false;
private boolean mContinueWithoutPublicKey = false;
private String mReferences;
private String mInReplyTo;
private Menu mMenu;
private boolean mSourceProcessed = false;
enum SimpleMessageFormat {
TEXT,
HTML
}
/**
* The currently used message format.
*
* <p>
* <strong>Note:</strong>
* Don't modify this field directly. Use {@link #updateMessageFormat()}.
* </p>
*/
private SimpleMessageFormat mMessageFormat;
private QuoteStyle mQuoteStyle;
private boolean mDraftNeedsSaving = false;
private boolean mPreventDraftSaving = false;
/**
* If this is {@code true} we don't save the message as a draft in {@link #onPause()}.
*/
private boolean mIgnoreOnPause = false;
/**
* The database ID of this message's draft. This is used when saving drafts so the message in
* the database is updated instead of being created anew. This property is INVALID_DRAFT_ID
* until the first save.
*/
private long mDraftId = INVALID_DRAFT_ID;
/**
* Number of attachments currently being fetched.
*/
private int mNumAttachmentsLoading = 0;
private enum WaitingAction {
NONE,
SEND,
SAVE
}
/**
* Specifies what action to perform once attachments have been fetched.
*/
private WaitingAction mWaitingForAttachments = WaitingAction.NONE;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case MSG_PROGRESS_ON:
setSupportProgressBarIndeterminateVisibility(true);
break;
case MSG_PROGRESS_OFF:
setSupportProgressBarIndeterminateVisibility(false);
break;
case MSG_SKIPPED_ATTACHMENTS:
Toast.makeText(
MessageCompose.this,
getString(R.string.message_compose_attachments_skipped_toast),
Toast.LENGTH_LONG).show();
break;
case MSG_SAVED_DRAFT:
Toast.makeText(
MessageCompose.this,
getString(R.string.message_saved_toast),
Toast.LENGTH_LONG).show();
break;
case MSG_DISCARDED_DRAFT:
Toast.makeText(
MessageCompose.this,
getString(R.string.message_discarded_toast),
Toast.LENGTH_LONG).show();
break;
case MSG_PERFORM_STALLED_ACTION:
performStalledAction();
break;
default:
super.handleMessage(msg);
break;
}
}
};
private Listener mListener = new Listener();
private EmailAddressAdapter mAddressAdapter;
private Validator mAddressValidator;
private FontSizes mFontSizes = K9.getFontSizes();
private ContextThemeWrapper mThemeContext;
/**
* Compose a new message using the given account. If account is null the default account
* will be used.
* @param context
* @param account
*/
public static void actionCompose(Context context, Account account) {
String accountUuid = (account == null) ?
Preferences.getPreferences(context).getDefaultAccount().getUuid() :
account.getUuid();
Intent i = new Intent(context, MessageCompose.class);
i.putExtra(EXTRA_ACCOUNT, accountUuid);
i.setAction(ACTION_COMPOSE);
context.startActivity(i);
}
/**
* Get intent for composing a new message as a reply to the given message. If replyAll is true
* the function is reply all instead of simply reply.
* @param context
* @param account
* @param message
* @param replyAll
* @param messageBody optional, for decrypted messages, null if it should be grabbed from the given message
*/
public static Intent getActionReplyIntent(
Context context,
Account account,
Message message,
boolean replyAll,
String messageBody) {
Intent i = new Intent(context, MessageCompose.class);
i.putExtra(EXTRA_MESSAGE_BODY, messageBody);
i.putExtra(EXTRA_MESSAGE_REFERENCE, message.makeMessageReference());
if (replyAll) {
i.setAction(ACTION_REPLY_ALL);
} else {
i.setAction(ACTION_REPLY);
}
return i;
}
/**
* Compose a new message as a reply to the given message. If replyAll is true the function
* is reply all instead of simply reply.
* @param context
* @param account
* @param message
* @param replyAll
* @param messageBody optional, for decrypted messages, null if it should be grabbed from the given message
*/
public static void actionReply(
Context context,
Account account,
Message message,
boolean replyAll,
String messageBody) {
context.startActivity(getActionReplyIntent(context, account, message, replyAll, messageBody));
}
/**
* Compose a new message as a forward of the given message.
* @param context
* @param account
* @param message
* @param messageBody optional, for decrypted messages, null if it should be grabbed from the given message
*/
public static void actionForward(
Context context,
Account account,
Message message,
String messageBody) {
Intent i = new Intent(context, MessageCompose.class);
i.putExtra(EXTRA_MESSAGE_BODY, messageBody);
i.putExtra(EXTRA_MESSAGE_REFERENCE, message.makeMessageReference());
i.setAction(ACTION_FORWARD);
context.startActivity(i);
}
/**
* Continue composition of the given message. This action modifies the way this Activity
* handles certain actions.
* Save will attempt to replace the message in the given folder with the updated version.
* Discard will delete the message from the given folder.
* @param context
* @param message
*/
public static void actionEditDraft(Context context, MessageReference messageReference) {
Intent i = new Intent(context, MessageCompose.class);
i.putExtra(EXTRA_MESSAGE_REFERENCE, messageReference);
i.setAction(ACTION_EDIT_DRAFT);
context.startActivity(i);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setSupportProgressBarIndeterminateVisibility(false);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (UpgradeDatabases.actionUpgradeDatabases(this, getIntent())) {
finish();
return;
}
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
if (K9.getK9ComposerThemeSetting() != K9.Theme.USE_GLOBAL) {
// theme the whole content according to the theme (except the action bar)
mThemeContext = new ContextThemeWrapper(this,
K9.getK9ThemeResourceId(K9.getK9ComposerTheme()));
View v = ((LayoutInflater) mThemeContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).
inflate(R.layout.message_compose, null);
TypedValue outValue = new TypedValue();
// background color needs to be forced
mThemeContext.getTheme().resolveAttribute(R.attr.messageViewHeaderBackgroundColor, outValue, true);
v.setBackgroundColor(outValue.data);
setContentView(v);
} else {
setContentView(R.layout.message_compose);
mThemeContext = this;
}
final Intent intent = getIntent();
mMessageReference = intent.getParcelableExtra(EXTRA_MESSAGE_REFERENCE);
mSourceMessageBody = intent.getStringExtra(EXTRA_MESSAGE_BODY);
if (K9.DEBUG && mSourceMessageBody != null)
Log.d(K9.LOG_TAG, "Composing message with explicitly specified message body.");
final String accountUuid = (mMessageReference != null) ?
mMessageReference.accountUuid :
intent.getStringExtra(EXTRA_ACCOUNT);
mAccount = Preferences.getPreferences(this).getAccount(accountUuid);
if (mAccount == null) {
mAccount = Preferences.getPreferences(this).getDefaultAccount();
}
if (mAccount == null) {
/*
* There are no accounts set up. This should not have happened. Prompt the
* user to set up an account as an acceptable bailout.
*/
startActivity(new Intent(this, Accounts.class));
mDraftNeedsSaving = false;
finish();
return;
}
mContacts = Contacts.getInstance(MessageCompose.this);
mAddressAdapter = new EmailAddressAdapter(mThemeContext);
mAddressValidator = new EmailAddressValidator();
mChooseIdentityButton = (Button) findViewById(R.id.identity);
mChooseIdentityButton.setOnClickListener(this);
if (mAccount.getIdentities().size() == 1 &&
Preferences.getPreferences(this).getAvailableAccounts().size() == 1) {
mChooseIdentityButton.setVisibility(View.GONE);
}
mToView = (MultiAutoCompleteTextView) findViewById(R.id.to);
mCcView = (MultiAutoCompleteTextView) findViewById(R.id.cc);
mBccView = (MultiAutoCompleteTextView) findViewById(R.id.bcc);
mSubjectView = (EditText) findViewById(R.id.subject);
mSubjectView.getInputExtras(true).putBoolean("allowEmoji", true);
mAddToFromContacts = (ImageButton) findViewById(R.id.add_to);
mAddCcFromContacts = (ImageButton) findViewById(R.id.add_cc);
mAddBccFromContacts = (ImageButton) findViewById(R.id.add_bcc);
mCcWrapper = (LinearLayout) findViewById(R.id.cc_wrapper);
mBccWrapper = (LinearLayout) findViewById(R.id.bcc_wrapper);
if (mAccount.isAlwaysShowCcBcc()) {
onAddCcBcc();
}
EolConvertingEditText upperSignature = (EolConvertingEditText)findViewById(R.id.upper_signature);
EolConvertingEditText lowerSignature = (EolConvertingEditText)findViewById(R.id.lower_signature);
mMessageContentView = (EolConvertingEditText)findViewById(R.id.message_content);
mMessageContentView.getInputExtras(true).putBoolean("allowEmoji", true);
mAttachments = (LinearLayout)findViewById(R.id.attachments);
mQuotedTextShow = (Button)findViewById(R.id.quoted_text_show);
mQuotedTextBar = findViewById(R.id.quoted_text_bar);
mQuotedTextEdit = (ImageButton)findViewById(R.id.quoted_text_edit);
mQuotedTextDelete = (ImageButton)findViewById(R.id.quoted_text_delete);
mQuotedText = (EolConvertingEditText)findViewById(R.id.quoted_text);
mQuotedText.getInputExtras(true).putBoolean("allowEmoji", true);
mQuotedHTML = (MessageWebView) findViewById(R.id.quoted_html);
mQuotedHTML.configure();
// Disable the ability to click links in the quoted HTML page. I think this is a nice feature, but if someone
// feels this should be a preference (or should go away all together), I'm ok with that too. -achen 20101130
mQuotedHTML.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return true;
}
});
TextWatcher watcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int before, int after) {
/* do nothing */
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mDraftNeedsSaving = true;
}
@Override
public void afterTextChanged(android.text.Editable s) { /* do nothing */ }
};
// For watching changes to the To:, Cc:, and Bcc: fields for auto-encryption on a matching
// address.
TextWatcher recipientWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int before, int after) {
/* do nothing */
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mDraftNeedsSaving = true;
}
@Override
public void afterTextChanged(android.text.Editable s) {
final CryptoProvider crypto = mAccount.getCryptoProvider();
if (mAutoEncrypt && crypto.isAvailable(getApplicationContext())) {
for (Address address : getRecipientAddresses()) {
if (crypto.hasPublicKeyForEmail(getApplicationContext(),
address.getAddress())) {
mEncryptCheckbox.setChecked(true);
mContinueWithoutPublicKey = false;
break;
}
}
}
}
};
TextWatcher sigwatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int before, int after) {
/* do nothing */
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mDraftNeedsSaving = true;
mSignatureChanged = true;
}
@Override
public void afterTextChanged(android.text.Editable s) { /* do nothing */ }
};
mToView.addTextChangedListener(recipientWatcher);
mCcView.addTextChangedListener(recipientWatcher);
mBccView.addTextChangedListener(recipientWatcher);
mSubjectView.addTextChangedListener(watcher);
mMessageContentView.addTextChangedListener(watcher);
mQuotedText.addTextChangedListener(watcher);
/* Yes, there really are poeple who ship versions of android without a contact picker */
if (mContacts.hasContactPicker()) {
mAddToFromContacts.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
doLaunchContactPicker(CONTACT_PICKER_TO);
}
});
mAddCcFromContacts.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
doLaunchContactPicker(CONTACT_PICKER_CC);
}
});
mAddBccFromContacts.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
doLaunchContactPicker(CONTACT_PICKER_BCC);
}
});
} else {
mAddToFromContacts.setVisibility(View.GONE);
mAddCcFromContacts.setVisibility(View.GONE);
mAddBccFromContacts.setVisibility(View.GONE);
}
/*
* We set this to invisible by default. Other methods will turn it back on if it's
* needed.
*/
showOrHideQuotedText(QuotedTextMode.NONE);
mQuotedTextShow.setOnClickListener(this);
mQuotedTextEdit.setOnClickListener(this);
mQuotedTextDelete.setOnClickListener(this);
mToView.setAdapter(mAddressAdapter);
mToView.setTokenizer(new Rfc822Tokenizer());
mToView.setValidator(mAddressValidator);
mCcView.setAdapter(mAddressAdapter);
mCcView.setTokenizer(new Rfc822Tokenizer());
mCcView.setValidator(mAddressValidator);
mBccView.setAdapter(mAddressAdapter);
mBccView.setTokenizer(new Rfc822Tokenizer());
mBccView.setValidator(mAddressValidator);
if (savedInstanceState != null) {
/*
* This data gets used in onCreate, so grab it here instead of onRestoreInstanceState
*/
mSourceMessageProcessed = savedInstanceState.getBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, false);
}
if (initFromIntent(intent)) {
mAction = Action.COMPOSE;
mDraftNeedsSaving = true;
} else {
String action = intent.getAction();
if (ACTION_COMPOSE.equals(action)) {
mAction = Action.COMPOSE;
} else if (ACTION_REPLY.equals(action)) {
mAction = Action.REPLY;
} else if (ACTION_REPLY_ALL.equals(action)) {
mAction = Action.REPLY_ALL;
} else if (ACTION_FORWARD.equals(action)) {
mAction = Action.FORWARD;
} else if (ACTION_EDIT_DRAFT.equals(action)) {
mAction = Action.EDIT_DRAFT;
} else {
// This shouldn't happen
Log.w(K9.LOG_TAG, "MessageCompose was started with an unsupported action");
mAction = Action.COMPOSE;
}
}
if (mIdentity == null) {
mIdentity = mAccount.getIdentity(0);
}
if (mAccount.isSignatureBeforeQuotedText()) {
mSignatureView = upperSignature;
lowerSignature.setVisibility(View.GONE);
} else {
mSignatureView = lowerSignature;
upperSignature.setVisibility(View.GONE);
}
mSignatureView.addTextChangedListener(sigwatcher);
if (!mIdentity.getSignatureUse()) {
mSignatureView.setVisibility(View.GONE);
}
mReadReceipt = mAccount.isMessageReadReceiptAlways();
mQuoteStyle = mAccount.getQuoteStyle();
updateFrom();
if (!mSourceMessageProcessed) {
updateSignature();
if (mAction == Action.REPLY || mAction == Action.REPLY_ALL ||
mAction == Action.FORWARD || mAction == Action.EDIT_DRAFT) {
/*
* If we need to load the message we add ourself as a message listener here
* so we can kick it off. Normally we add in onResume but we don't
* want to reload the message every time the activity is resumed.
* There is no harm in adding twice.
*/
MessagingController.getInstance(getApplication()).addListener(mListener);
final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid);
final String folderName = mMessageReference.folderName;
final String sourceMessageUid = mMessageReference.uid;
MessagingController.getInstance(getApplication()).loadMessageForView(account, folderName, sourceMessageUid, null);
}
if (mAction != Action.EDIT_DRAFT) {
addAddresses(mBccView, mAccount.getAlwaysBcc());
}
}
if (mAction == Action.REPLY || mAction == Action.REPLY_ALL) {
mMessageReference.flag = Flag.ANSWERED;
}
if (mAction == Action.REPLY || mAction == Action.REPLY_ALL ||
mAction == Action.EDIT_DRAFT) {
//change focus to message body.
mMessageContentView.requestFocus();
} else {
// Explicitly set focus to "To:" input field (see issue 2998)
mToView.requestFocus();
}
if (mAction == Action.FORWARD) {
mMessageReference.flag = Flag.FORWARDED;
}
mEncryptLayout = findViewById(R.id.layout_encrypt);
mCryptoSignatureCheckbox = (CheckBox)findViewById(R.id.cb_crypto_signature);
mCryptoSignatureUserId = (TextView)findViewById(R.id.userId);
mCryptoSignatureUserIdRest = (TextView)findViewById(R.id.userIdRest);
mEncryptCheckbox = (CheckBox)findViewById(R.id.cb_encrypt);
mEncryptCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
updateMessageFormat();
}
});
if (mSourceMessageBody != null) {
// mSourceMessageBody is set to something when replying to and forwarding decrypted
// messages, so the sender probably wants the message to be encrypted.
mEncryptCheckbox.setChecked(true);
}
initializeCrypto();
final CryptoProvider crypto = mAccount.getCryptoProvider();
if (crypto.isAvailable(this)) {
mEncryptLayout.setVisibility(View.VISIBLE);
mCryptoSignatureCheckbox.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
CheckBox checkBox = (CheckBox) v;
if (checkBox.isChecked()) {
mPreventDraftSaving = true;
if (!crypto.selectSecretKey(MessageCompose.this, mPgpData)) {
mPreventDraftSaving = false;
}
checkBox.setChecked(false);
} else {
mPgpData.setSignatureKeyId(0);
updateEncryptLayout();
}
}
});
if (mAccount.getCryptoAutoSignature()) {
long ids[] = crypto.getSecretKeyIdsFromEmail(this, mIdentity.getEmail());
if (ids != null && ids.length > 0) {
mPgpData.setSignatureKeyId(ids[0]);
mPgpData.setSignatureUserId(crypto.getUserId(this, ids[0]));
} else {
mPgpData.setSignatureKeyId(0);
mPgpData.setSignatureUserId(null);
}
}
updateEncryptLayout();
mAutoEncrypt = mAccount.isCryptoAutoEncrypt();
} else {
mEncryptLayout.setVisibility(View.GONE);
}
// Set font size of input controls
int fontSize = mFontSizes.getMessageComposeInput();
mFontSizes.setViewTextSize(mToView, fontSize);
mFontSizes.setViewTextSize(mCcView, fontSize);
mFontSizes.setViewTextSize(mBccView, fontSize);
mFontSizes.setViewTextSize(mSubjectView, fontSize);
mFontSizes.setViewTextSize(mMessageContentView, fontSize);
mFontSizes.setViewTextSize(mQuotedText, fontSize);
mFontSizes.setViewTextSize(mSignatureView, fontSize);
updateMessageFormat();
setTitle();
}
/**
* Handle external intents that trigger the message compose activity.
*
* <p>
* Supported external intents:
* <ul>
* <li>{@link Intent#ACTION_VIEW}</li>
* <li>{@link Intent#ACTION_SENDTO}</li>
* <li>{@link Intent#ACTION_SEND}</li>
* <li>{@link Intent#ACTION_SEND_MULTIPLE}</li>
* </ul>
* </p>
*
* @param intent
* The (external) intent that started the activity.
*
* @return {@code true}, if this activity was started by an external intent. {@code false},
* otherwise.
*/
private boolean initFromIntent(final Intent intent) {
boolean startedByExternalIntent = false;
final String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_SENDTO.equals(action)) {
startedByExternalIntent = true;
/*
* Someone has clicked a mailto: link. The address is in the URI.
*/
if (intent.getData() != null) {
Uri uri = intent.getData();
if ("mailto".equals(uri.getScheme())) {
initializeFromMailto(uri);
}
}
/*
* Note: According to the documenation ACTION_VIEW and ACTION_SENDTO don't accept
* EXTRA_* parameters.
* And previously we didn't process these EXTRAs. But it looks like nobody bothers to
* read the official documentation and just copies wrong sample code that happens to
* work with the AOSP Email application. And because even big players get this wrong,
* we're now finally giving in and read the EXTRAs for ACTION_SENDTO (below).
*/
}
if (Intent.ACTION_SEND.equals(action) || Intent.ACTION_SEND_MULTIPLE.equals(action) ||
Intent.ACTION_SENDTO.equals(action)) {
startedByExternalIntent = true;
/*
* Note: Here we allow a slight deviation from the documentated behavior.
* EXTRA_TEXT is used as message body (if available) regardless of the MIME
* type of the intent. In addition one or multiple attachments can be added
* using EXTRA_STREAM.
*/
CharSequence text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT);
// Only use EXTRA_TEXT if the body hasn't already been set by the mailto URI
if (text != null && mMessageContentView.getText().length() == 0) {
mMessageContentView.setCharacters(text);
}
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action)) {
Uri stream = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (stream != null) {
addAttachment(stream, type);
}
} else {
ArrayList<Parcelable> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
if (list != null) {
for (Parcelable parcelable : list) {
Uri stream = (Uri) parcelable;
if (stream != null) {
addAttachment(stream, type);
}
}
}
}
String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT);
// Only use EXTRA_SUBJECT if the subject hasn't already been set by the mailto URI
if (subject != null && mSubjectView.getText().length() == 0) {
mSubjectView.setText(subject);
}
String[] extraEmail = intent.getStringArrayExtra(Intent.EXTRA_EMAIL);
String[] extraCc = intent.getStringArrayExtra(Intent.EXTRA_CC);
String[] extraBcc = intent.getStringArrayExtra(Intent.EXTRA_BCC);
if (extraEmail != null) {
addRecipients(mToView, Arrays.asList(extraEmail));
}
boolean ccOrBcc = false;
if (extraCc != null) {
ccOrBcc |= addRecipients(mCcView, Arrays.asList(extraCc));
}
if (extraBcc != null) {
ccOrBcc |= addRecipients(mBccView, Arrays.asList(extraBcc));
}
if (ccOrBcc) {
// Display CC and BCC text fields if CC or BCC recipients were set by the intent.
onAddCcBcc();
}
}
return startedByExternalIntent;
}
private boolean addRecipients(TextView view, List<String> recipients) {
if (recipients == null || recipients.size() == 0) {
return false;
}
StringBuilder addressList = new StringBuilder();
// Read current contents of the TextView
String text = view.getText().toString();
addressList.append(text);
// Add comma if necessary
if (text.length() != 0 && !(text.endsWith(", ") || text.endsWith(","))) {
addressList.append(", ");
}
// Add recipients
for (String recipient : recipients) {
addressList.append(recipient);
addressList.append(", ");
}
view.setText(addressList);
return true;
}
private void initializeCrypto() {
if (mPgpData != null) {
return;
}
mPgpData = new PgpData();
}
/**
* Fill the encrypt layout with the latest data about signature key and encryption keys.
*/
public void updateEncryptLayout() {
if (!mPgpData.hasSignatureKey()) {
mCryptoSignatureCheckbox.setText(R.string.btn_crypto_sign);
mCryptoSignatureCheckbox.setChecked(false);
mCryptoSignatureUserId.setVisibility(View.INVISIBLE);
mCryptoSignatureUserIdRest.setVisibility(View.INVISIBLE);
} else {
// if a signature key is selected, then the checkbox itself has no text
mCryptoSignatureCheckbox.setText("");
mCryptoSignatureCheckbox.setChecked(true);
mCryptoSignatureUserId.setVisibility(View.VISIBLE);
mCryptoSignatureUserIdRest.setVisibility(View.VISIBLE);
mCryptoSignatureUserId.setText(R.string.unknown_crypto_signature_user_id);
mCryptoSignatureUserIdRest.setText("");
String userId = mPgpData.getSignatureUserId();
if (userId == null) {
userId = mAccount.getCryptoProvider().getUserId(this, mPgpData.getSignatureKeyId());
mPgpData.setSignatureUserId(userId);
}
if (userId != null) {
String chunks[] = mPgpData.getSignatureUserId().split(" <", 2);
mCryptoSignatureUserId.setText(chunks[0]);
if (chunks.length > 1) {
mCryptoSignatureUserIdRest.setText("<" + chunks[1]);
}
}
}
updateMessageFormat();
}
@Override
public void onResume() {
super.onResume();
mIgnoreOnPause = false;
MessagingController.getInstance(getApplication()).addListener(mListener);
}
@Override
public void onPause() {
super.onPause();
MessagingController.getInstance(getApplication()).removeListener(mListener);
// Save email as draft when activity is changed (go to home screen, call received) or screen locked
// don't do this if only changing orientations
if (!mIgnoreOnPause && (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) {
saveIfNeeded();
}
}
/**
* The framework handles most of the fields, but we need to handle stuff that we
* dynamically show and hide:
* Attachment list,
* Cc field,
* Bcc field,
* Quoted text,
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
ArrayList<Attachment> attachments = new ArrayList<Attachment>();
for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) {
View view = mAttachments.getChildAt(i);
Attachment attachment = (Attachment) view.getTag();
attachments.add(attachment);
}
outState.putInt(STATE_KEY_NUM_ATTACHMENTS_LOADING, mNumAttachmentsLoading);
outState.putString(STATE_KEY_WAITING_FOR_ATTACHMENTS, mWaitingForAttachments.name());
outState.putParcelableArrayList(STATE_KEY_ATTACHMENTS, attachments);
outState.putBoolean(STATE_KEY_CC_SHOWN, mCcWrapper.getVisibility() == View.VISIBLE);
outState.putBoolean(STATE_KEY_BCC_SHOWN, mBccWrapper.getVisibility() == View.VISIBLE);
outState.putSerializable(STATE_KEY_QUOTED_TEXT_MODE, mQuotedTextMode);
outState.putBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, mSourceMessageProcessed);
outState.putLong(STATE_KEY_DRAFT_ID, mDraftId);
outState.putSerializable(STATE_IDENTITY, mIdentity);
outState.putBoolean(STATE_IDENTITY_CHANGED, mIdentityChanged);
outState.putSerializable(STATE_PGP_DATA, mPgpData);
outState.putString(STATE_IN_REPLY_TO, mInReplyTo);
outState.putString(STATE_REFERENCES, mReferences);
outState.putSerializable(STATE_KEY_HTML_QUOTE, mQuotedHtmlContent);
outState.putBoolean(STATE_KEY_READ_RECEIPT, mReadReceipt);
outState.putBoolean(STATE_KEY_DRAFT_NEEDS_SAVING, mDraftNeedsSaving);
outState.putBoolean(STATE_KEY_FORCE_PLAIN_TEXT, mForcePlainText);
outState.putSerializable(STATE_KEY_QUOTED_TEXT_FORMAT, mQuotedTextFormat);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mAttachments.removeAllViews();
mMaxLoaderId = 0;
mNumAttachmentsLoading = savedInstanceState.getInt(STATE_KEY_NUM_ATTACHMENTS_LOADING);
mWaitingForAttachments = WaitingAction.NONE;
try {
String waitingFor = savedInstanceState.getString(STATE_KEY_WAITING_FOR_ATTACHMENTS);
mWaitingForAttachments = WaitingAction.valueOf(waitingFor);
} catch (Exception e) {
Log.w(K9.LOG_TAG, "Couldn't read value \" + STATE_KEY_WAITING_FOR_ATTACHMENTS +" +
"\" from saved instance state", e);
}
ArrayList<Attachment> attachments = savedInstanceState.getParcelableArrayList(STATE_KEY_ATTACHMENTS);
for (Attachment attachment : attachments) {
addAttachmentView(attachment);
if (attachment.loaderId > mMaxLoaderId) {
mMaxLoaderId = attachment.loaderId;
}
if (attachment.state == Attachment.LoadingState.URI_ONLY) {
initAttachmentInfoLoader(attachment);
} else if (attachment.state == Attachment.LoadingState.METADATA) {
initAttachmentContentLoader(attachment);
}
}
mReadReceipt = savedInstanceState
.getBoolean(STATE_KEY_READ_RECEIPT);
mCcWrapper.setVisibility(savedInstanceState.getBoolean(STATE_KEY_CC_SHOWN) ? View.VISIBLE
: View.GONE);
mBccWrapper.setVisibility(savedInstanceState
.getBoolean(STATE_KEY_BCC_SHOWN) ? View.VISIBLE : View.GONE);
// This method is called after the action bar menu has already been created and prepared.
// So compute the visibility of the "Add Cc/Bcc" menu item again.
computeAddCcBccVisibility();
showOrHideQuotedText(
(QuotedTextMode) savedInstanceState.getSerializable(STATE_KEY_QUOTED_TEXT_MODE));
mQuotedHtmlContent =
(InsertableHtmlContent) savedInstanceState.getSerializable(STATE_KEY_HTML_QUOTE);
if (mQuotedHtmlContent != null && mQuotedHtmlContent.getQuotedContent() != null) {
mQuotedHTML.setText(mQuotedHtmlContent.getQuotedContent());
}
mDraftId = savedInstanceState.getLong(STATE_KEY_DRAFT_ID);
mIdentity = (Identity)savedInstanceState.getSerializable(STATE_IDENTITY);
mIdentityChanged = savedInstanceState.getBoolean(STATE_IDENTITY_CHANGED);
mPgpData = (PgpData) savedInstanceState.getSerializable(STATE_PGP_DATA);
mInReplyTo = savedInstanceState.getString(STATE_IN_REPLY_TO);
mReferences = savedInstanceState.getString(STATE_REFERENCES);
mDraftNeedsSaving = savedInstanceState.getBoolean(STATE_KEY_DRAFT_NEEDS_SAVING);
mForcePlainText = savedInstanceState.getBoolean(STATE_KEY_FORCE_PLAIN_TEXT);
mQuotedTextFormat = (SimpleMessageFormat) savedInstanceState.getSerializable(
STATE_KEY_QUOTED_TEXT_FORMAT);
initializeCrypto();
updateFrom();
updateSignature();
updateEncryptLayout();
updateMessageFormat();
}
private void setTitle() {
switch (mAction) {
case REPLY: {
setTitle(R.string.compose_title_reply);
break;
}
case REPLY_ALL: {
setTitle(R.string.compose_title_reply_all);
break;
}
case FORWARD: {
setTitle(R.string.compose_title_forward);
break;
}
case COMPOSE:
default: {
setTitle(R.string.compose_title_compose);
break;
}
}
}
private void addAddresses(MultiAutoCompleteTextView view, String addresses) {
if (StringUtils.isNullOrEmpty(addresses)) {
return;
}
for (String address : addresses.split(",")) {
addAddress(view, new Address(address, ""));
}
}
private void addAddresses(MultiAutoCompleteTextView view, Address[] addresses) {
if (addresses == null) {
return;
}
for (Address address : addresses) {
addAddress(view, address);
}
}
private void addAddress(MultiAutoCompleteTextView view, Address address) {
view.append(address + ", ");
}
private Address[] getAddresses(MultiAutoCompleteTextView view) {
return Address.parseUnencoded(view.getText().toString().trim());
}
/*
* Returns an Address array of recipients this email will be sent to.
* @return Address array of recipients this email will be sent to.
*/
private Address[] getRecipientAddresses() {
String addresses = mToView.getText().toString() + mCcView.getText().toString()
+ mBccView.getText().toString();
return Address.parseUnencoded(addresses.trim());
}
/*
* Build the Body that will contain the text of the message. We'll decide where to
* include it later. Draft messages are treated somewhat differently in that signatures are not
* appended and HTML separators between composed text and quoted text are not added.
* @param isDraft If we should build a message that will be saved as a draft (as opposed to sent).
*/
private TextBody buildText(boolean isDraft) {
return buildText(isDraft, mMessageFormat);
}
/**
* Build the {@link Body} that will contain the text of the message.
*
* <p>
* Draft messages are treated somewhat differently in that signatures are not appended and HTML
* separators between composed text and quoted text are not added.
* </p>
*
* @param isDraft
* If {@code true} we build a message that will be saved as a draft (as opposed to
* sent).
* @param messageFormat
* Specifies what type of message to build ({@code text/plain} vs. {@code text/html}).
*
* @return {@link TextBody} instance that contains the entered text and possibly the quoted
* original message.
*/
private TextBody buildText(boolean isDraft, SimpleMessageFormat messageFormat) {
// The length of the formatted version of the user-supplied text/reply
int composedMessageLength;
// The offset of the user-supplied text/reply in the final text body
int composedMessageOffset;
/*
* Find out if we need to include the original message as quoted text.
*
* We include the quoted text in the body if the user didn't choose to hide it. We always
* include the quoted text when we're saving a draft. That's so the user is able to
* "un-hide" the quoted text if (s)he opens a saved draft.
*/
boolean includeQuotedText = (mQuotedTextMode.equals(QuotedTextMode.SHOW) || isDraft);
// Reply after quote makes no sense for HEADER style replies
boolean replyAfterQuote = (mQuoteStyle == QuoteStyle.HEADER) ?
false : mAccount.isReplyAfterQuote();
boolean signatureBeforeQuotedText = mAccount.isSignatureBeforeQuotedText();
// Get the user-supplied text
String text = mMessageContentView.getCharacters();
// Handle HTML separate from the rest of the text content
if (messageFormat == SimpleMessageFormat.HTML) {
// Do we have to modify an existing message to include our reply?
if (includeQuotedText && mQuotedHtmlContent != null) {
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "insertable: " + mQuotedHtmlContent.toDebugString());
}
if (!isDraft) {
// Append signature to the reply
if (replyAfterQuote || signatureBeforeQuotedText) {
text = appendSignature(text);
}
}
// Convert the text to HTML
text = HtmlConverter.textToHtmlFragment(text);
/*
* Set the insertion location based upon our reply after quote setting.
* Additionally, add some extra separators between the composed message and quoted
* message depending on the quote location. We only add the extra separators when
* we're sending, that way when we load a draft, we don't have to know the length
* of the separators to remove them before editing.
*/
if (replyAfterQuote) {
mQuotedHtmlContent.setInsertionLocation(
InsertableHtmlContent.InsertionLocation.AFTER_QUOTE);
if (!isDraft) {
text = "<br clear=\"all\">" + text;
}
} else {
mQuotedHtmlContent.setInsertionLocation(
InsertableHtmlContent.InsertionLocation.BEFORE_QUOTE);
if (!isDraft) {
text += "<br><br>";
}
}
if (!isDraft) {
// Place signature immediately after the quoted text
if (!(replyAfterQuote || signatureBeforeQuotedText)) {
mQuotedHtmlContent.insertIntoQuotedFooter(getSignatureHtml());
}
}
mQuotedHtmlContent.setUserContent(text);
// Save length of the body and its offset. This is used when thawing drafts.
composedMessageLength = text.length();
composedMessageOffset = mQuotedHtmlContent.getInsertionPoint();
text = mQuotedHtmlContent.toString();
} else {
// There is no text to quote so simply append the signature if available
if (!isDraft) {
text = appendSignature(text);
}
// Convert the text to HTML
text = HtmlConverter.textToHtmlFragment(text);
//TODO: Wrap this in proper HTML tags
composedMessageLength = text.length();
composedMessageOffset = 0;
}
} else {
// Capture composed message length before we start attaching quoted parts and signatures.
composedMessageLength = text.length();
composedMessageOffset = 0;
if (!isDraft) {
// Append signature to the text/reply
if (replyAfterQuote || signatureBeforeQuotedText) {
text = appendSignature(text);
}
}
String quotedText = mQuotedText.getCharacters();
if (includeQuotedText && quotedText.length() > 0) {
if (replyAfterQuote) {
composedMessageOffset = quotedText.length() + "\r\n".length();
text = quotedText + "\r\n" + text;
} else {
text += "\r\n\r\n" + quotedText.toString();
}
}
if (!isDraft) {
// Place signature immediately after the quoted text
if (!(replyAfterQuote || signatureBeforeQuotedText)) {
text = appendSignature(text);
}
}
}
TextBody body = new TextBody(text);
body.setComposedMessageLength(composedMessageLength);
body.setComposedMessageOffset(composedMessageOffset);
return body;
}
/**
* Build the final message to be sent (or saved). If there is another message quoted in this one, it will be baked
* into the final message here.
* @param isDraft Indicates if this message is a draft or not. Drafts do not have signatures
* appended and have some extra metadata baked into their header for use during thawing.
* @return Message to be sent.
* @throws MessagingException
*/
private MimeMessage createMessage(boolean isDraft) throws MessagingException {
MimeMessage message = new MimeMessage();
message.addSentDate(new Date());
Address from = new Address(mIdentity.getEmail(), mIdentity.getName());
message.setFrom(from);
message.setRecipients(RecipientType.TO, getAddresses(mToView));
message.setRecipients(RecipientType.CC, getAddresses(mCcView));
message.setRecipients(RecipientType.BCC, getAddresses(mBccView));
message.setSubject(mSubjectView.getText().toString());
if (mReadReceipt) {
message.setHeader("Disposition-Notification-To", from.toEncodedString());
message.setHeader("X-Confirm-Reading-To", from.toEncodedString());
message.setHeader("Return-Receipt-To", from.toEncodedString());
}
message.setHeader("User-Agent", getString(R.string.message_header_mua));
final String replyTo = mIdentity.getReplyTo();
if (replyTo != null) {
message.setReplyTo(new Address[] { new Address(replyTo) });
}
if (mInReplyTo != null) {
message.setInReplyTo(mInReplyTo);
}
if (mReferences != null) {
message.setReferences(mReferences);
}
// Build the body.
// TODO FIXME - body can be either an HTML or Text part, depending on whether we're in
// HTML mode or not. Should probably fix this so we don't mix up html and text parts.
TextBody body = null;
if (mPgpData.getEncryptedData() != null) {
String text = mPgpData.getEncryptedData();
body = new TextBody(text);
} else {
body = buildText(isDraft);
}
// text/plain part when mMessageFormat == MessageFormat.HTML
TextBody bodyPlain = null;
final boolean hasAttachments = mAttachments.getChildCount() > 0;
if (mMessageFormat == SimpleMessageFormat.HTML) {
// HTML message (with alternative text part)
// This is the compiled MIME part for an HTML message.
MimeMultipart composedMimeMessage = new MimeMultipart();
composedMimeMessage.setSubType("alternative"); // Let the receiver select either the text or the HTML part.
composedMimeMessage.addBodyPart(new MimeBodyPart(body, "text/html"));
bodyPlain = buildText(isDraft, SimpleMessageFormat.TEXT);
composedMimeMessage.addBodyPart(new MimeBodyPart(bodyPlain, "text/plain"));
if (hasAttachments) {
// If we're HTML and have attachments, we have a MimeMultipart container to hold the
// whole message (mp here), of which one part is a MimeMultipart container
// (composedMimeMessage) with the user's composed messages, and subsequent parts for
// the attachments.
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(new MimeBodyPart(composedMimeMessage));
addAttachmentsToMessage(mp);
message.setBody(mp);
} else {
// If no attachments, our multipart/alternative part is the only one we need.
message.setBody(composedMimeMessage);
}
} else if (mMessageFormat == SimpleMessageFormat.TEXT) {
// Text-only message.
if (hasAttachments) {
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(new MimeBodyPart(body, "text/plain"));
addAttachmentsToMessage(mp);
message.setBody(mp);
} else {
// No attachments to include, just stick the text body in the message and call it good.
message.setBody(body);
}
}
// If this is a draft, add metadata for thawing.
if (isDraft) {
// Add the identity to the message.
message.addHeader(K9.IDENTITY_HEADER, buildIdentityHeader(body, bodyPlain));
}
return message;
}
/**
* Add attachments as parts into a MimeMultipart container.
* @param mp MimeMultipart container in which to insert parts.
* @throws MessagingException
*/
private void addAttachmentsToMessage(final MimeMultipart mp) throws MessagingException {
Body body;
for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) {
Attachment attachment = (Attachment) mAttachments.getChildAt(i).getTag();
if (attachment.state != Attachment.LoadingState.COMPLETE) {
continue;
}
String contentType = attachment.contentType;
if (MimeUtil.isMessage(contentType)) {
body = new TempFileMessageBody(attachment.filename);
} else {
body = new TempFileBody(attachment.filename);
}
MimeBodyPart bp = new MimeBodyPart(body);
/*
* Correctly encode the filename here. Otherwise the whole
* header value (all parameters at once) will be encoded by
* MimeHeader.writeTo().
*/
bp.addHeader(MimeHeader.HEADER_CONTENT_TYPE, String.format("%s;\r\n name=\"%s\"",
contentType,
EncoderUtil.encodeIfNecessary(attachment.name,
EncoderUtil.Usage.WORD_ENTITY, 7)));
bp.setEncoding(MimeUtility.getEncodingforType(contentType));
/*
* TODO: Oh the joys of MIME...
*
* From RFC 2183 (The Content-Disposition Header Field):
* "Parameter values longer than 78 characters, or which
* contain non-ASCII characters, MUST be encoded as specified
* in [RFC 2184]."
*
* Example:
*
* Content-Type: application/x-stuff
* title*1*=us-ascii'en'This%20is%20even%20more%20
* title*2*=%2A%2A%2Afun%2A%2A%2A%20
* title*3="isn't it!"
*/
bp.addHeader(MimeHeader.HEADER_CONTENT_DISPOSITION, String.format(
"attachment;\r\n filename=\"%s\";\r\n size=%d",
attachment.name, attachment.size));
mp.addBodyPart(bp);
}
}
// FYI, there's nothing in the code that requires these variables to one letter. They're one
// letter simply to save space. This name sucks. It's too similar to Account.Identity.
private enum IdentityField {
LENGTH("l"),
OFFSET("o"),
FOOTER_OFFSET("fo"),
PLAIN_LENGTH("pl"),
PLAIN_OFFSET("po"),
MESSAGE_FORMAT("f"),
MESSAGE_READ_RECEIPT("r"),
SIGNATURE("s"),
NAME("n"),
EMAIL("e"),
// TODO - store a reference to the message being replied so we can mark it at the time of send.
ORIGINAL_MESSAGE("m"),
CURSOR_POSITION("p"), // Where in the message your cursor was when you saved.
QUOTED_TEXT_MODE("q"),
QUOTE_STYLE("qs");
private final String value;
IdentityField(String value) {
this.value = value;
}
public String value() {
return value;
}
/**
* Get the list of IdentityFields that should be integer values.
*
* <p>
* These values are sanity checked for integer-ness during decoding.
* </p>
*
* @return The list of integer {@link IdentityField}s.
*/
public static IdentityField[] getIntegerFields() {
return new IdentityField[] { LENGTH, OFFSET, FOOTER_OFFSET, PLAIN_LENGTH, PLAIN_OFFSET };
}
}
// Version identifier for "new style" identity. ! is an impossible value in base64 encoding, so we
// use that to determine which version we're in.
private static final String IDENTITY_VERSION_1 = "!";
/**
* Build the identity header string. This string contains metadata about a draft message to be
* used upon loading a draft for composition. This should be generated at the time of saving a
* draft.<br>
* <br>
* This is a URL-encoded key/value pair string. The list of possible values are in {@link IdentityField}.
* @param body {@link TextBody} to analyze for body length and offset.
* @param bodyPlain {@link TextBody} to analyze for body length and offset. May be null.
* @return Identity string.
*/
private String buildIdentityHeader(final TextBody body, final TextBody bodyPlain) {
Uri.Builder uri = new Uri.Builder();
if (body.getComposedMessageLength() != null && body.getComposedMessageOffset() != null) {
// See if the message body length is already in the TextBody.
uri.appendQueryParameter(IdentityField.LENGTH.value(), body.getComposedMessageLength().toString());
uri.appendQueryParameter(IdentityField.OFFSET.value(), body.getComposedMessageOffset().toString());
} else {
// If not, calculate it now.
uri.appendQueryParameter(IdentityField.LENGTH.value(), Integer.toString(body.getText().length()));
uri.appendQueryParameter(IdentityField.OFFSET.value(), Integer.toString(0));
}
if (mQuotedHtmlContent != null) {
uri.appendQueryParameter(IdentityField.FOOTER_OFFSET.value(),
Integer.toString(mQuotedHtmlContent.getFooterInsertionPoint()));
}
if (bodyPlain != null) {
if (bodyPlain.getComposedMessageLength() != null && bodyPlain.getComposedMessageOffset() != null) {
// See if the message body length is already in the TextBody.
uri.appendQueryParameter(IdentityField.PLAIN_LENGTH.value(), bodyPlain.getComposedMessageLength().toString());
uri.appendQueryParameter(IdentityField.PLAIN_OFFSET.value(), bodyPlain.getComposedMessageOffset().toString());
} else {
// If not, calculate it now.
uri.appendQueryParameter(IdentityField.PLAIN_LENGTH.value(), Integer.toString(body.getText().length()));
uri.appendQueryParameter(IdentityField.PLAIN_OFFSET.value(), Integer.toString(0));
}
}
// Save the quote style (useful for forwards).
uri.appendQueryParameter(IdentityField.QUOTE_STYLE.value(), mQuoteStyle.name());
// Save the message format for this offset.
uri.appendQueryParameter(IdentityField.MESSAGE_FORMAT.value(), mMessageFormat.name());
// If we're not using the standard identity of signature, append it on to the identity blob.
if (mIdentity.getSignatureUse() && mSignatureChanged) {
uri.appendQueryParameter(IdentityField.SIGNATURE.value(), mSignatureView.getCharacters());
}
if (mIdentityChanged) {
uri.appendQueryParameter(IdentityField.NAME.value(), mIdentity.getName());
uri.appendQueryParameter(IdentityField.EMAIL.value(), mIdentity.getEmail());
}
if (mMessageReference != null) {
uri.appendQueryParameter(IdentityField.ORIGINAL_MESSAGE.value(), mMessageReference.toIdentityString());
}
uri.appendQueryParameter(IdentityField.CURSOR_POSITION.value(), Integer.toString(mMessageContentView.getSelectionStart()));
uri.appendQueryParameter(IdentityField.QUOTED_TEXT_MODE.value(), mQuotedTextMode.name());
String k9identity = IDENTITY_VERSION_1 + uri.build().getEncodedQuery();
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Generated identity: " + k9identity);
}
return k9identity;
}
/**
* Parse an identity string. Handles both legacy and new (!) style identities.
*
* @param identityString
* The encoded identity string that was saved in a drafts header.
*
* @return A map containing the value for each {@link IdentityField} in the identity string.
*/
private Map<IdentityField, String> parseIdentityHeader(final String identityString) {
Map<IdentityField, String> identity = new HashMap<IdentityField, String>();
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Decoding identity: " + identityString);
if (identityString == null || identityString.length() < 1) {
return identity;
}
// Check to see if this is a "next gen" identity.
if (identityString.charAt(0) == IDENTITY_VERSION_1.charAt(0) && identityString.length() > 2) {
Uri.Builder builder = new Uri.Builder();
builder.encodedQuery(identityString.substring(1)); // Need to cut off the ! at the beginning.
Uri uri = builder.build();
for (IdentityField key : IdentityField.values()) {
String value = uri.getQueryParameter(key.value());
if (value != null) {
identity.put(key, value);
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Decoded identity: " + identity.toString());
// Sanity check our Integers so that recipients of this result don't have to.
for (IdentityField key : IdentityField.getIntegerFields()) {
if (identity.get(key) != null) {
try {
Integer.parseInt(identity.get(key));
} catch (NumberFormatException e) {
Log.e(K9.LOG_TAG, "Invalid " + key.name() + " field in identity: " + identity.get(key));
}
}
}
} else {
// Legacy identity
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got a saved legacy identity: " + identityString);
StringTokenizer tokens = new StringTokenizer(identityString, ":", false);
// First item is the body length. We use this to separate the composed reply from the quoted text.
if (tokens.hasMoreTokens()) {
String bodyLengthS = Utility.base64Decode(tokens.nextToken());
try {
identity.put(IdentityField.LENGTH, Integer.valueOf(bodyLengthS).toString());
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Unable to parse bodyLength '" + bodyLengthS + "'");
}
}
if (tokens.hasMoreTokens()) {
identity.put(IdentityField.SIGNATURE, Utility.base64Decode(tokens.nextToken()));
}
if (tokens.hasMoreTokens()) {
identity.put(IdentityField.NAME, Utility.base64Decode(tokens.nextToken()));
}
if (tokens.hasMoreTokens()) {
identity.put(IdentityField.EMAIL, Utility.base64Decode(tokens.nextToken()));
}
if (tokens.hasMoreTokens()) {
identity.put(IdentityField.QUOTED_TEXT_MODE, Utility.base64Decode(tokens.nextToken()));
}
}
return identity;
}
private String appendSignature(String originalText) {
String text = originalText;
if (mIdentity.getSignatureUse()) {
String signature = mSignatureView.getCharacters();
if (signature != null && !signature.contentEquals("")) {
text += "\r\n" + signature;
}
}
return text;
}
/**
* Get an HTML version of the signature in the #mSignatureView, if any.
* @return HTML version of signature.
*/
private String getSignatureHtml() {
String signature = "";
if (mIdentity.getSignatureUse()) {
signature = mSignatureView.getCharacters();
if(!StringUtils.isNullOrEmpty(signature)) {
signature = HtmlConverter.textToHtmlFragment("\r\n" + signature);
}
}
return signature;
}
private void sendMessage() {
new SendMessageTask().execute();
}
private void saveMessage() {
new SaveMessageTask().execute();
}
private void saveIfNeeded() {
if (!mDraftNeedsSaving || mPreventDraftSaving || mPgpData.hasEncryptionKeys() ||
mEncryptCheckbox.isChecked() || !mAccount.hasDraftsFolder()) {
return;
}
mDraftNeedsSaving = false;
saveMessage();
}
public void onEncryptionKeySelectionDone() {
if (mPgpData.hasEncryptionKeys()) {
onSend();
} else {
Toast.makeText(this, R.string.send_aborted, Toast.LENGTH_SHORT).show();
}
}
public void onEncryptDone() {
if (mPgpData.getEncryptedData() != null) {
onSend();
} else {
Toast.makeText(this, R.string.send_aborted, Toast.LENGTH_SHORT).show();
}
}
private void onSend() {
if (getAddresses(mToView).length == 0 && getAddresses(mCcView).length == 0 && getAddresses(mBccView).length == 0) {
mToView.setError(getString(R.string.message_compose_error_no_recipients));
Toast.makeText(this, getString(R.string.message_compose_error_no_recipients), Toast.LENGTH_LONG).show();
return;
}
if (mWaitingForAttachments != WaitingAction.NONE) {
return;
}
if (mNumAttachmentsLoading > 0) {
mWaitingForAttachments = WaitingAction.SEND;
showWaitingForAttachmentDialog();
} else {
performSend();
}
}
private void performSend() {
final CryptoProvider crypto = mAccount.getCryptoProvider();
if (mEncryptCheckbox.isChecked() && !mPgpData.hasEncryptionKeys()) {
// key selection before encryption
StringBuilder emails = new StringBuilder();
for (Address address : getRecipientAddresses()) {
if (emails.length() != 0) {
emails.append(',');
}
emails.append(address.getAddress());
if (!mContinueWithoutPublicKey &&
!crypto.hasPublicKeyForEmail(this, address.getAddress())) {
showDialog(DIALOG_CONTINUE_WITHOUT_PUBLIC_KEY);
return;
}
}
if (emails.length() != 0) {
emails.append(',');
}
emails.append(mIdentity.getEmail());
mPreventDraftSaving = true;
if (!crypto.selectEncryptionKeys(MessageCompose.this, emails.toString(), mPgpData)) {
mPreventDraftSaving = false;
}
return;
}
if (mPgpData.hasEncryptionKeys() || mPgpData.hasSignatureKey()) {
if (mPgpData.getEncryptedData() == null) {
String text = buildText(false).getText();
mPreventDraftSaving = true;
if (!crypto.encrypt(this, text, mPgpData)) {
mPreventDraftSaving = false;
}
return;
}
}
sendMessage();
if (mMessageReference != null && mMessageReference.flag != null) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Setting referenced message (" + mMessageReference.folderName + ", " + mMessageReference.uid + ") flag to " + mMessageReference.flag);
final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid);
final String folderName = mMessageReference.folderName;
final String sourceMessageUid = mMessageReference.uid;
MessagingController.getInstance(getApplication()).setFlag(account, folderName, sourceMessageUid, mMessageReference.flag, true);
}
mDraftNeedsSaving = false;
finish();
}
private void onDiscard() {
if (mDraftId != INVALID_DRAFT_ID) {
MessagingController.getInstance(getApplication()).deleteDraft(mAccount, mDraftId);
mDraftId = INVALID_DRAFT_ID;
}
mHandler.sendEmptyMessage(MSG_DISCARDED_DRAFT);
mDraftNeedsSaving = false;
finish();
}
private void onSave() {
if (mWaitingForAttachments != WaitingAction.NONE) {
return;
}
if (mNumAttachmentsLoading > 0) {
mWaitingForAttachments = WaitingAction.SAVE;
showWaitingForAttachmentDialog();
} else {
performSave();
}
}
private void performSave() {
saveIfNeeded();
finish();
}
private void onAddCcBcc() {
mCcWrapper.setVisibility(View.VISIBLE);
mBccWrapper.setVisibility(View.VISIBLE);
computeAddCcBccVisibility();
}
/**
* Hide the 'Add Cc/Bcc' menu item when both fields are visible.
*/
private void computeAddCcBccVisibility() {
if (mMenu != null && mCcWrapper.getVisibility() == View.VISIBLE &&
mBccWrapper.getVisibility() == View.VISIBLE) {
mMenu.findItem(R.id.add_cc_bcc).setVisible(false);
}
}
private void onReadReceipt() {
CharSequence txt;
if (mReadReceipt == false) {
txt = getString(R.string.read_receipt_enabled);
mReadReceipt = true;
} else {
txt = getString(R.string.read_receipt_disabled);
mReadReceipt = false;
}
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, txt, Toast.LENGTH_SHORT);
toast.show();
}
/**
* Kick off a picker for whatever kind of MIME types we'll accept and let Android take over.
*/
private void onAddAttachment() {
if (K9.isGalleryBuggy()) {
if (K9.useGalleryBugWorkaround()) {
Toast.makeText(MessageCompose.this,
getString(R.string.message_compose_use_workaround),
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MessageCompose.this,
getString(R.string.message_compose_buggy_gallery),
Toast.LENGTH_LONG).show();
}
}
onAddAttachment2("*/*");
}
/**
* Kick off a picker for the specified MIME type and let Android take over.
*
* @param mime_type
* The MIME type we want our attachment to have.
*/
private void onAddAttachment2(final String mime_type) {
if (mAccount.getCryptoProvider().isAvailable(this)) {
Toast.makeText(this, R.string.attachment_encryption_unsupported, Toast.LENGTH_LONG).show();
}
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType(mime_type);
mIgnoreOnPause = true;
startActivityForResult(Intent.createChooser(i, null), ACTIVITY_REQUEST_PICK_ATTACHMENT);
}
private void addAttachment(Uri uri) {
addAttachment(uri, null);
}
private void addAttachment(Uri uri, String contentType) {
Attachment attachment = new Attachment();
attachment.state = Attachment.LoadingState.URI_ONLY;
attachment.uri = uri;
attachment.contentType = contentType;
attachment.loaderId = ++mMaxLoaderId;
addAttachmentView(attachment);
initAttachmentInfoLoader(attachment);
}
private void initAttachmentInfoLoader(Attachment attachment) {
LoaderManager loaderManager = getSupportLoaderManager();
Bundle bundle = new Bundle();
bundle.putParcelable(LOADER_ARG_ATTACHMENT, attachment);
loaderManager.initLoader(attachment.loaderId, bundle, mAttachmentInfoLoaderCallback);
}
private void initAttachmentContentLoader(Attachment attachment) {
LoaderManager loaderManager = getSupportLoaderManager();
Bundle bundle = new Bundle();
bundle.putParcelable(LOADER_ARG_ATTACHMENT, attachment);
loaderManager.initLoader(attachment.loaderId, bundle, mAttachmentContentLoaderCallback);
}
private void addAttachmentView(Attachment attachment) {
boolean hasMetadata = (attachment.state != Attachment.LoadingState.URI_ONLY);
boolean isLoadingComplete = (attachment.state == Attachment.LoadingState.COMPLETE);
View view = getLayoutInflater().inflate(R.layout.message_compose_attachment, mAttachments, false);
TextView nameView = (TextView) view.findViewById(R.id.attachment_name);
View progressBar = view.findViewById(R.id.progressBar);
if (hasMetadata) {
nameView.setText(attachment.name);
} else {
nameView.setText(R.string.loading_attachment);
}
progressBar.setVisibility(isLoadingComplete ? View.GONE : View.VISIBLE);
ImageButton delete = (ImageButton) view.findViewById(R.id.attachment_delete);
delete.setOnClickListener(MessageCompose.this);
delete.setTag(view);
view.setTag(attachment);
mAttachments.addView(view);
}
private View getAttachmentView(int loaderId) {
for (int i = 0, childCount = mAttachments.getChildCount(); i < childCount; i++) {
View view = mAttachments.getChildAt(i);
Attachment tag = (Attachment) view.getTag();
if (tag != null && tag.loaderId == loaderId) {
return view;
}
}
return null;
}
private LoaderManager.LoaderCallbacks<Attachment> mAttachmentInfoLoaderCallback =
new LoaderManager.LoaderCallbacks<Attachment>() {
@Override
public Loader<Attachment> onCreateLoader(int id, Bundle args) {
onFetchAttachmentStarted();
Attachment attachment = args.getParcelable(LOADER_ARG_ATTACHMENT);
return new AttachmentInfoLoader(MessageCompose.this, attachment);
}
@Override
public void onLoadFinished(Loader<Attachment> loader, Attachment attachment) {
int loaderId = loader.getId();
View view = getAttachmentView(loaderId);
if (view != null) {
view.setTag(attachment);
TextView nameView = (TextView) view.findViewById(R.id.attachment_name);
nameView.setText(attachment.name);
attachment.loaderId = ++mMaxLoaderId;
initAttachmentContentLoader(attachment);
} else {
onFetchAttachmentFinished();
}
getSupportLoaderManager().destroyLoader(loaderId);
}
@Override
public void onLoaderReset(Loader<Attachment> loader) {
onFetchAttachmentFinished();
}
};
private LoaderManager.LoaderCallbacks<Attachment> mAttachmentContentLoaderCallback =
new LoaderManager.LoaderCallbacks<Attachment>() {
@Override
public Loader<Attachment> onCreateLoader(int id, Bundle args) {
Attachment attachment = args.getParcelable(LOADER_ARG_ATTACHMENT);
return new AttachmentContentLoader(MessageCompose.this, attachment);
}
@Override
public void onLoadFinished(Loader<Attachment> loader, Attachment attachment) {
int loaderId = loader.getId();
View view = getAttachmentView(loaderId);
if (view != null) {
if (attachment.state == Attachment.LoadingState.COMPLETE) {
view.setTag(attachment);
View progressBar = view.findViewById(R.id.progressBar);
progressBar.setVisibility(View.GONE);
} else {
mAttachments.removeView(view);
}
}
onFetchAttachmentFinished();
getSupportLoaderManager().destroyLoader(loaderId);
}
@Override
public void onLoaderReset(Loader<Attachment> loader) {
onFetchAttachmentFinished();
}
};
private void onFetchAttachmentStarted() {
mNumAttachmentsLoading += 1;
}
private void onFetchAttachmentFinished() {
// We're not allowed to perform fragment transactions when called from onLoadFinished().
// So we use the Handler to call performStalledAction().
mHandler.sendEmptyMessage(MSG_PERFORM_STALLED_ACTION);
}
private void performStalledAction() {
mNumAttachmentsLoading -= 1;
WaitingAction waitingFor = mWaitingForAttachments;
mWaitingForAttachments = WaitingAction.NONE;
if (waitingFor != WaitingAction.NONE) {
dismissWaitingForAttachmentDialog();
}
switch (waitingFor) {
case SEND: {
performSend();
break;
}
case SAVE: {
performSave();
break;
}
case NONE:
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if a CryptoSystem activity is returning, then mPreventDraftSaving was set to true
mPreventDraftSaving = false;
if (mAccount.getCryptoProvider().onActivityResult(this, requestCode, resultCode, data, mPgpData)) {
return;
}
if (resultCode != RESULT_OK)
return;
if (data == null) {
return;
}
switch (requestCode) {
case ACTIVITY_REQUEST_PICK_ATTACHMENT:
addAttachment(data.getData());
mDraftNeedsSaving = true;
break;
case CONTACT_PICKER_TO:
case CONTACT_PICKER_CC:
case CONTACT_PICKER_BCC:
ContactItem contact = mContacts.extractInfoFromContactPickerIntent(data);
if (contact == null) {
Toast.makeText(this, getString(R.string.error_contact_address_not_found), Toast.LENGTH_LONG).show();
return;
}
if (contact.emailAddresses.size() > 1) {
Intent i = new Intent(this, EmailAddressList.class);
i.putExtra(EmailAddressList.EXTRA_CONTACT_ITEM, contact);
if (requestCode == CONTACT_PICKER_TO) {
startActivityForResult(i, CONTACT_PICKER_TO2);
} else if (requestCode == CONTACT_PICKER_CC) {
startActivityForResult(i, CONTACT_PICKER_CC2);
} else if (requestCode == CONTACT_PICKER_BCC) {
startActivityForResult(i, CONTACT_PICKER_BCC2);
}
return;
}
if (K9.DEBUG) {
List<String> emails = contact.emailAddresses;
for (int i = 0; i < emails.size(); i++) {
Log.v(K9.LOG_TAG, "email[" + i + "]: " + emails.get(i));
}
}
String email = contact.emailAddresses.get(0);
if (requestCode == CONTACT_PICKER_TO) {
addAddress(mToView, new Address(email, ""));
} else if (requestCode == CONTACT_PICKER_CC) {
addAddress(mCcView, new Address(email, ""));
} else if (requestCode == CONTACT_PICKER_BCC) {
addAddress(mBccView, new Address(email, ""));
} else {
return;
}
break;
case CONTACT_PICKER_TO2:
case CONTACT_PICKER_CC2:
case CONTACT_PICKER_BCC2:
String emailAddr = data.getStringExtra(EmailAddressList.EXTRA_EMAIL_ADDRESS);
if (requestCode == CONTACT_PICKER_TO2) {
addAddress(mToView, new Address(emailAddr, ""));
} else if (requestCode == CONTACT_PICKER_CC2) {
addAddress(mCcView, new Address(emailAddr, ""));
} else if (requestCode == CONTACT_PICKER_BCC2) {
addAddress(mBccView, new Address(emailAddr, ""));
}
break;
}
}
public void doLaunchContactPicker(int resultId) {
mIgnoreOnPause = true;
startActivityForResult(mContacts.contactPickerIntent(), resultId);
}
private void onAccountChosen(Account account, Identity identity) {
if (!mAccount.equals(account)) {
if (K9.DEBUG) {
Log.v(K9.LOG_TAG, "Switching account from " + mAccount + " to " + account);
}
// on draft edit, make sure we don't keep previous message UID
if (mAction == Action.EDIT_DRAFT) {
mMessageReference = null;
}
// test whether there is something to save
if (mDraftNeedsSaving || (mDraftId != INVALID_DRAFT_ID)) {
final long previousDraftId = mDraftId;
final Account previousAccount = mAccount;
// make current message appear as new
mDraftId = INVALID_DRAFT_ID;
// actual account switch
mAccount = account;
if (K9.DEBUG) {
Log.v(K9.LOG_TAG, "Account switch, saving new draft in new account");
}
saveMessage();
if (previousDraftId != INVALID_DRAFT_ID) {
if (K9.DEBUG) {
Log.v(K9.LOG_TAG, "Account switch, deleting draft from previous account: "
+ previousDraftId);
}
MessagingController.getInstance(getApplication()).deleteDraft(previousAccount,
previousDraftId);
}
} else {
mAccount = account;
}
// Show CC/BCC text input field when switching to an account that always wants them
// displayed.
// Please note that we're not hiding the fields if the user switches back to an account
// that doesn't have this setting checked.
if (mAccount.isAlwaysShowCcBcc()) {
onAddCcBcc();
}
// not sure how to handle mFolder, mSourceMessage?
}
switchToIdentity(identity);
}
private void switchToIdentity(Identity identity) {
mIdentity = identity;
mIdentityChanged = true;
mDraftNeedsSaving = true;
updateFrom();
updateBcc();
updateSignature();
updateMessageFormat();
}
private void updateFrom() {
mChooseIdentityButton.setText(mIdentity.getEmail());
}
private void updateBcc() {
if (mIdentityChanged) {
mBccWrapper.setVisibility(View.VISIBLE);
}
mBccView.setText("");
addAddresses(mBccView, mAccount.getAlwaysBcc());
}
private void updateSignature() {
if (mIdentity.getSignatureUse()) {
mSignatureView.setCharacters(mIdentity.getSignature());
mSignatureView.setVisibility(View.VISIBLE);
} else {
mSignatureView.setVisibility(View.GONE);
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.attachment_delete:
/*
* The view is the delete button, and we have previously set the tag of
* the delete button to the view that owns it. We don't use parent because the
* view is very complex and could change in the future.
*/
mAttachments.removeView((View) view.getTag());
mDraftNeedsSaving = true;
break;
case R.id.quoted_text_show:
showOrHideQuotedText(QuotedTextMode.SHOW);
updateMessageFormat();
mDraftNeedsSaving = true;
break;
case R.id.quoted_text_delete:
showOrHideQuotedText(QuotedTextMode.HIDE);
updateMessageFormat();
mDraftNeedsSaving = true;
break;
case R.id.quoted_text_edit:
mForcePlainText = true;
if (mMessageReference != null) { // shouldn't happen...
// TODO - Should we check if mSourceMessageBody is already present and bypass the MessagingController call?
MessagingController.getInstance(getApplication()).addListener(mListener);
final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid);
final String folderName = mMessageReference.folderName;
final String sourceMessageUid = mMessageReference.uid;
MessagingController.getInstance(getApplication()).loadMessageForView(account, folderName, sourceMessageUid, null);
}
break;
case R.id.identity:
showDialog(DIALOG_CHOOSE_IDENTITY);
break;
}
}
/**
* Show or hide the quoted text.
*
* @param mode
* The value to set {@link #mQuotedTextMode} to.
*/
private void showOrHideQuotedText(QuotedTextMode mode) {
mQuotedTextMode = mode;
switch (mode) {
case NONE:
case HIDE: {
if (mode == QuotedTextMode.NONE) {
mQuotedTextShow.setVisibility(View.GONE);
} else {
mQuotedTextShow.setVisibility(View.VISIBLE);
}
mQuotedTextBar.setVisibility(View.GONE);
mQuotedText.setVisibility(View.GONE);
mQuotedHTML.setVisibility(View.GONE);
mQuotedTextEdit.setVisibility(View.GONE);
break;
}
case SHOW: {
mQuotedTextShow.setVisibility(View.GONE);
mQuotedTextBar.setVisibility(View.VISIBLE);
if (mQuotedTextFormat == SimpleMessageFormat.HTML) {
mQuotedText.setVisibility(View.GONE);
mQuotedHTML.setVisibility(View.VISIBLE);
mQuotedTextEdit.setVisibility(View.VISIBLE);
} else {
mQuotedText.setVisibility(View.VISIBLE);
mQuotedHTML.setVisibility(View.GONE);
mQuotedTextEdit.setVisibility(View.GONE);
}
break;
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.send:
mPgpData.setEncryptionKeys(null);
onSend();
break;
case R.id.save:
if (mEncryptCheckbox.isChecked()) {
showDialog(DIALOG_REFUSE_TO_SAVE_DRAFT_MARKED_ENCRYPTED);
} else {
onSave();
}
break;
case R.id.discard:
onDiscard();
break;
case R.id.add_cc_bcc:
onAddCcBcc();
break;
case R.id.add_attachment:
onAddAttachment();
break;
case R.id.add_attachment_image:
/*
* Show the menu items "Add attachment (Image)" and "Add attachment (Video)"
* if the work-around for the Gallery bug is enabled (see Issue 1186).
*/
menu.findItem(R.id.add_attachment_image).setVisible(K9.useGalleryBugWorkaround());
menu.findItem(R.id.add_attachment_video).setVisible(K9.useGalleryBugWorkaround());
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
computeAddCcBccVisibility();
return true;
}
@Override
public void onBackPressed() {
if (mDraftNeedsSaving) {
if (mEncryptCheckbox.isChecked()) {
showDialog(DIALOG_REFUSE_TO_SAVE_DRAFT_MARKED_ENCRYPTED);
} else if (!mAccount.hasDraftsFolder()) {
showDialog(DIALOG_CONFIRM_DISCARD_ON_BACK);
} else {
showDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE);
}
} else {
// Check if editing an existing draft.
if (mDraftId == INVALID_DRAFT_ID) {
onDiscard();
} else {
super.onBackPressed();
}
}
}
private void showWaitingForAttachmentDialog() {
String title;
switch (mWaitingForAttachments) {
case SEND: {
title = getString(R.string.fetching_attachment_dialog_title_send);
break;
}
case SAVE: {
title = getString(R.string.fetching_attachment_dialog_title_save);
break;
}
default: {
return;
}
}
ProgressDialogFragment fragment = ProgressDialogFragment.newInstance(title,
getString(R.string.fetching_attachment_dialog_message));
fragment.show(getSupportFragmentManager(), FRAGMENT_WAITING_FOR_ATTACHMENT);
}
public void onCancel(ProgressDialogFragment fragment) {
attachmentProgressDialogCancelled();
}
void attachmentProgressDialogCancelled() {
mWaitingForAttachments = WaitingAction.NONE;
}
private void dismissWaitingForAttachmentDialog() {
ProgressDialogFragment fragment = (ProgressDialogFragment)
getSupportFragmentManager().findFragmentByTag(FRAGMENT_WAITING_FOR_ATTACHMENT);
if (fragment != null) {
fragment.dismiss();
}
}
@Override
public Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE:
return new AlertDialog.Builder(this)
.setTitle(R.string.save_or_discard_draft_message_dlg_title)
.setMessage(R.string.save_or_discard_draft_message_instructions_fmt)
.setPositiveButton(R.string.save_draft_action, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dismissDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE);
onSave();
}
})
.setNegativeButton(R.string.discard_action, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dismissDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE);
onDiscard();
}
})
.create();
case DIALOG_REFUSE_TO_SAVE_DRAFT_MARKED_ENCRYPTED:
return new AlertDialog.Builder(this)
.setTitle(R.string.refuse_to_save_draft_marked_encrypted_dlg_title)
.setMessage(R.string.refuse_to_save_draft_marked_encrypted_instructions_fmt)
.setNeutralButton(R.string.okay_action, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dismissDialog(DIALOG_REFUSE_TO_SAVE_DRAFT_MARKED_ENCRYPTED);
}
})
.create();
case DIALOG_CONTINUE_WITHOUT_PUBLIC_KEY:
return new AlertDialog.Builder(this)
.setTitle(R.string.continue_without_public_key_dlg_title)
.setMessage(R.string.continue_without_public_key_instructions_fmt)
.setPositiveButton(R.string.continue_action, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dismissDialog(DIALOG_CONTINUE_WITHOUT_PUBLIC_KEY);
mContinueWithoutPublicKey = true;
onSend();
}
})
.setNegativeButton(R.string.back_action, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dismissDialog(DIALOG_CONTINUE_WITHOUT_PUBLIC_KEY);
mContinueWithoutPublicKey = false;
}
})
.create();
case DIALOG_CONFIRM_DISCARD_ON_BACK:
return new AlertDialog.Builder(this)
.setTitle(R.string.confirm_discard_draft_message_title)
.setMessage(R.string.confirm_discard_draft_message)
.setPositiveButton(R.string.cancel_action, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dismissDialog(DIALOG_CONFIRM_DISCARD_ON_BACK);
}
})
.setNegativeButton(R.string.discard_action, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dismissDialog(DIALOG_CONFIRM_DISCARD_ON_BACK);
Toast.makeText(MessageCompose.this,
getString(R.string.message_discarded_toast),
Toast.LENGTH_LONG).show();
onDiscard();
}
})
.create();
case DIALOG_CHOOSE_IDENTITY:
Context context = new ContextThemeWrapper(this,
(K9.getK9Theme() == K9.Theme.LIGHT) ?
R.style.Theme_K9_Dialog_Light :
R.style.Theme_K9_Dialog_Dark);
Builder builder = new AlertDialog.Builder(context);
builder.setTitle(R.string.send_as);
final IdentityAdapter adapter = new IdentityAdapter(context);
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
IdentityContainer container = (IdentityContainer) adapter.getItem(which);
onAccountChosen(container.account, container.identity);
}
});
return builder.create();
}
return super.onCreateDialog(id);
}
/**
* Add all attachments of an existing message as if they were added by hand.
*
* @param part
* The message part to check for being an attachment. This method will recurse if it's
* a multipart part.
* @param depth
* The recursion depth. Currently unused.
*
* @return {@code true} if all attachments were able to be attached, {@code false} otherwise.
*
* @throws MessagingException
* In case of an error
*/
private boolean loadAttachments(Part part, int depth) throws MessagingException {
if (part.getBody() instanceof Multipart) {
Multipart mp = (Multipart) part.getBody();
boolean ret = true;
for (int i = 0, count = mp.getCount(); i < count; i++) {
if (!loadAttachments(mp.getBodyPart(i), depth + 1)) {
ret = false;
}
}
return ret;
}
String contentType = MimeUtility.unfoldAndDecode(part.getContentType());
String name = MimeUtility.getHeaderParameter(contentType, "name");
if (name != null) {
Body body = part.getBody();
if (body != null && body instanceof LocalAttachmentBody) {
final Uri uri = ((LocalAttachmentBody) body).getContentUri();
mHandler.post(new Runnable() {
@Override
public void run() {
addAttachment(uri);
}
});
} else {
return false;
}
}
return true;
}
/**
* Pull out the parts of the now loaded source message and apply them to the new message
* depending on the type of message being composed.
*
* @param message
* The source message used to populate the various text fields.
*/
private void processSourceMessage(Message message) {
try {
switch (mAction) {
case REPLY:
case REPLY_ALL: {
processMessageToReplyTo(message);
break;
}
case FORWARD: {
processMessageToForward(message);
break;
}
case EDIT_DRAFT: {
processDraftMessage(message);
break;
}
default: {
Log.w(K9.LOG_TAG, "processSourceMessage() called with unsupported action");
break;
}
}
} catch (MessagingException me) {
/**
* Let the user continue composing their message even if we have a problem processing
* the source message. Log it as an error, though.
*/
Log.e(K9.LOG_TAG, "Error while processing source message: ", me);
} finally {
mSourceMessageProcessed = true;
mDraftNeedsSaving = false;
}
updateMessageFormat();
}
private void processMessageToReplyTo(Message message) throws MessagingException {
if (message.getSubject() != null) {
final String subject = PREFIX.matcher(message.getSubject()).replaceFirst("");
if (!subject.toLowerCase(Locale.US).startsWith("re:")) {
mSubjectView.setText("Re: " + subject);
} else {
mSubjectView.setText(subject);
}
} else {
mSubjectView.setText("");
}
/*
* If a reply-to was included with the message use that, otherwise use the from
* or sender address.
*/
Address[] replyToAddresses;
if (message.getReplyTo().length > 0) {
replyToAddresses = message.getReplyTo();
} else {
replyToAddresses = message.getFrom();
}
// if we're replying to a message we sent, we probably meant
// to reply to the recipient of that message
if (mAccount.isAnIdentity(replyToAddresses)) {
replyToAddresses = message.getRecipients(RecipientType.TO);
}
addAddresses(mToView, replyToAddresses);
if (message.getMessageId() != null && message.getMessageId().length() > 0) {
mInReplyTo = message.getMessageId();
if (message.getReferences() != null && message.getReferences().length > 0) {
StringBuilder buffy = new StringBuilder();
for (int i = 0; i < message.getReferences().length; i++)
buffy.append(message.getReferences()[i]);
mReferences = buffy.toString() + " " + mInReplyTo;
} else {
mReferences = mInReplyTo;
}
} else {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "could not get Message-ID.");
}
// Quote the message and setup the UI.
populateUIWithQuotedMessage(mAccount.isDefaultQuotedTextShown());
if (mAction == Action.REPLY || mAction == Action.REPLY_ALL) {
Identity useIdentity = null;
for (Address address : message.getRecipients(RecipientType.TO)) {
Identity identity = mAccount.findIdentity(address);
if (identity != null) {
useIdentity = identity;
break;
}
}
if (useIdentity == null) {
if (message.getRecipients(RecipientType.CC).length > 0) {
for (Address address : message.getRecipients(RecipientType.CC)) {
Identity identity = mAccount.findIdentity(address);
if (identity != null) {
useIdentity = identity;
break;
}
}
}
}
if (useIdentity != null) {
Identity defaultIdentity = mAccount.getIdentity(0);
if (useIdentity != defaultIdentity) {
switchToIdentity(useIdentity);
}
}
}
if (mAction == Action.REPLY_ALL) {
if (message.getReplyTo().length > 0) {
for (Address address : message.getFrom()) {
if (!mAccount.isAnIdentity(address)) {
addAddress(mToView, address);
}
}
}
for (Address address : message.getRecipients(RecipientType.TO)) {
if (!mAccount.isAnIdentity(address) && !Utility.arrayContains(replyToAddresses, address)) {
addAddress(mToView, address);
}
}
if (message.getRecipients(RecipientType.CC).length > 0) {
for (Address address : message.getRecipients(RecipientType.CC)) {
if (!mAccount.isAnIdentity(address) && !Utility.arrayContains(replyToAddresses, address)) {
addAddress(mCcView, address);
}
}
mCcWrapper.setVisibility(View.VISIBLE);
}
}
}
private void processMessageToForward(Message message) throws MessagingException {
String subject = message.getSubject();
if (subject != null && !subject.toLowerCase(Locale.US).startsWith("fwd:")) {
mSubjectView.setText("Fwd: " + subject);
} else {
mSubjectView.setText(subject);
}
mQuoteStyle = QuoteStyle.HEADER;
// "Be Like Thunderbird" - on forwarded messages, set the message ID
// of the forwarded message in the references and the reply to. TB
// only includes ID of the message being forwarded in the reference,
// even if there are multiple references.
if (!StringUtils.isNullOrEmpty(message.getMessageId())) {
mInReplyTo = message.getMessageId();
mReferences = mInReplyTo;
} else {
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "could not get Message-ID.");
}
}
// Quote the message and setup the UI.
populateUIWithQuotedMessage(true);
if (!mSourceMessageProcessed) {
if (!loadAttachments(message, 0)) {
mHandler.sendEmptyMessage(MSG_SKIPPED_ATTACHMENTS);
}
}
}
private void processDraftMessage(Message message) throws MessagingException {
String showQuotedTextMode = "NONE";
mDraftId = MessagingController.getInstance(getApplication()).getId(message);
mSubjectView.setText(message.getSubject());
addAddresses(mToView, message.getRecipients(RecipientType.TO));
if (message.getRecipients(RecipientType.CC).length > 0) {
addAddresses(mCcView, message.getRecipients(RecipientType.CC));
mCcWrapper.setVisibility(View.VISIBLE);
}
Address[] bccRecipients = message.getRecipients(RecipientType.BCC);
if (bccRecipients.length > 0) {
addAddresses(mBccView, bccRecipients);
String bccAddress = mAccount.getAlwaysBcc();
if (bccRecipients.length == 1 && bccAddress != null && bccAddress.equals(bccRecipients[0].toString())) {
// If the auto-bcc is the only entry in the BCC list, don't show the Bcc fields.
mBccWrapper.setVisibility(View.GONE);
} else {
mBccWrapper.setVisibility(View.VISIBLE);
}
}
// Read In-Reply-To header from draft
final String[] inReplyTo = message.getHeader("In-Reply-To");
if ((inReplyTo != null) && (inReplyTo.length >= 1)) {
mInReplyTo = inReplyTo[0];
}
// Read References header from draft
final String[] references = message.getHeader("References");
if ((references != null) && (references.length >= 1)) {
mReferences = references[0];
}
if (!mSourceMessageProcessed) {
loadAttachments(message, 0);
}
// Decode the identity header when loading a draft.
// See buildIdentityHeader(TextBody) for a detailed description of the composition of this blob.
Map<IdentityField, String> k9identity = new HashMap<IdentityField, String>();
if (message.getHeader(K9.IDENTITY_HEADER) != null && message.getHeader(K9.IDENTITY_HEADER).length > 0 && message.getHeader(K9.IDENTITY_HEADER)[0] != null) {
k9identity = parseIdentityHeader(message.getHeader(K9.IDENTITY_HEADER)[0]);
}
Identity newIdentity = new Identity();
if (k9identity.containsKey(IdentityField.SIGNATURE)) {
newIdentity.setSignatureUse(true);
newIdentity.setSignature(k9identity.get(IdentityField.SIGNATURE));
mSignatureChanged = true;
} else {
newIdentity.setSignatureUse(message.getFolder().getAccount().getSignatureUse());
newIdentity.setSignature(mIdentity.getSignature());
}
if (k9identity.containsKey(IdentityField.NAME)) {
newIdentity.setName(k9identity.get(IdentityField.NAME));
mIdentityChanged = true;
} else {
newIdentity.setName(mIdentity.getName());
}
if (k9identity.containsKey(IdentityField.EMAIL)) {
newIdentity.setEmail(k9identity.get(IdentityField.EMAIL));
mIdentityChanged = true;
} else {
newIdentity.setEmail(mIdentity.getEmail());
}
if (k9identity.containsKey(IdentityField.ORIGINAL_MESSAGE)) {
mMessageReference = null;
try {
String originalMessage = k9identity.get(IdentityField.ORIGINAL_MESSAGE);
MessageReference messageReference = new MessageReference(originalMessage);
// Check if this is a valid account in our database
Preferences prefs = Preferences.getPreferences(getApplicationContext());
Account account = prefs.getAccount(messageReference.accountUuid);
if (account != null) {
mMessageReference = messageReference;
}
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Could not decode message reference in identity.", e);
}
}
int cursorPosition = 0;
if (k9identity.containsKey(IdentityField.CURSOR_POSITION)) {
try {
cursorPosition = Integer.valueOf(k9identity.get(IdentityField.CURSOR_POSITION)).intValue();
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Could not parse cursor position for MessageCompose; continuing.", e);
}
}
if (k9identity.containsKey(IdentityField.QUOTED_TEXT_MODE)) {
showQuotedTextMode = k9identity.get(IdentityField.QUOTED_TEXT_MODE);
}
mIdentity = newIdentity;
updateSignature();
updateFrom();
Integer bodyLength = k9identity.get(IdentityField.LENGTH) != null
? Integer.valueOf(k9identity.get(IdentityField.LENGTH))
: 0;
Integer bodyOffset = k9identity.get(IdentityField.OFFSET) != null
? Integer.valueOf(k9identity.get(IdentityField.OFFSET))
: 0;
Integer bodyFooterOffset = k9identity.get(IdentityField.FOOTER_OFFSET) != null
? Integer.valueOf(k9identity.get(IdentityField.FOOTER_OFFSET))
: null;
Integer bodyPlainLength = k9identity.get(IdentityField.PLAIN_LENGTH) != null
? Integer.valueOf(k9identity.get(IdentityField.PLAIN_LENGTH))
: null;
Integer bodyPlainOffset = k9identity.get(IdentityField.PLAIN_OFFSET) != null
? Integer.valueOf(k9identity.get(IdentityField.PLAIN_OFFSET))
: null;
mQuoteStyle = k9identity.get(IdentityField.QUOTE_STYLE) != null
? QuoteStyle.valueOf(k9identity.get(IdentityField.QUOTE_STYLE))
: mAccount.getQuoteStyle();
QuotedTextMode quotedMode;
try {
quotedMode = QuotedTextMode.valueOf(showQuotedTextMode);
} catch (Exception e) {
quotedMode = QuotedTextMode.NONE;
}
// Always respect the user's current composition format preference, even if the
// draft was saved in a different format.
// TODO - The current implementation doesn't allow a user in HTML mode to edit a draft that wasn't saved with K9mail.
String messageFormatString = k9identity.get(IdentityField.MESSAGE_FORMAT);
MessageFormat messageFormat = null;
if (messageFormatString != null) {
try {
messageFormat = MessageFormat.valueOf(messageFormatString);
} catch (Exception e) { /* do nothing */ }
}
if (messageFormat == null) {
// drafts created before the advent of HTML composition. In those cases,
// we'll display the whole message (including the quoted part) in the
// composition window. If that's the case, try and convert it to text to
// match the behavior in text mode.
mMessageContentView.setCharacters(getBodyTextFromMessage(message, SimpleMessageFormat.TEXT));
mForcePlainText = true;
showOrHideQuotedText(quotedMode);
return;
}
if (messageFormat == MessageFormat.HTML) {
Part part = MimeUtility.findFirstPartByMimeType(message, "text/html");
if (part != null) { // Shouldn't happen if we were the one who saved it.
mQuotedTextFormat = SimpleMessageFormat.HTML;
String text = MimeUtility.getTextFromPart(part);
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Loading message with offset " + bodyOffset + ", length " + bodyLength + ". Text length is " + text.length() + ".");
}
if (bodyOffset + bodyLength > text.length()) {
// The draft was edited outside of K-9 Mail?
Log.d(K9.LOG_TAG, "The identity field from the draft contains an invalid LENGTH/OFFSET");
bodyOffset = 0;
bodyLength = 0;
}
// Grab our reply text.
String bodyText = text.substring(bodyOffset, bodyOffset + bodyLength);
mMessageContentView.setCharacters(HtmlConverter.htmlToText(bodyText));
// Regenerate the quoted html without our user content in it.
StringBuilder quotedHTML = new StringBuilder();
quotedHTML.append(text.substring(0, bodyOffset)); // stuff before the reply
quotedHTML.append(text.substring(bodyOffset + bodyLength));
if (quotedHTML.length() > 0) {
mQuotedHtmlContent = new InsertableHtmlContent();
mQuotedHtmlContent.setQuotedContent(quotedHTML);
// We don't know if bodyOffset refers to the header or to the footer
mQuotedHtmlContent.setHeaderInsertionPoint(bodyOffset);
if (bodyFooterOffset != null) {
mQuotedHtmlContent.setFooterInsertionPoint(bodyFooterOffset);
} else {
mQuotedHtmlContent.setFooterInsertionPoint(bodyOffset);
}
mQuotedHTML.setText(mQuotedHtmlContent.getQuotedContent());
}
}
if (bodyPlainOffset != null && bodyPlainLength != null) {
processSourceMessageText(message, bodyPlainOffset, bodyPlainLength, false);
}
} else if (messageFormat == MessageFormat.TEXT) {
mQuotedTextFormat = SimpleMessageFormat.TEXT;
processSourceMessageText(message, bodyOffset, bodyLength, true);
} else {
Log.e(K9.LOG_TAG, "Unhandled message format.");
}
// Set the cursor position if we have it.
try {
mMessageContentView.setSelection(cursorPosition);
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Could not set cursor position in MessageCompose; ignoring.", e);
}
showOrHideQuotedText(quotedMode);
}
/**
* Pull out the parts of the now loaded source message and apply them to the new message
* depending on the type of message being composed.
* @param message Source message
* @param bodyOffset Insertion point for reply.
* @param bodyLength Length of reply.
* @param viewMessageContent Update mMessageContentView or not.
* @throws MessagingException
*/
private void processSourceMessageText(Message message, Integer bodyOffset, Integer bodyLength,
boolean viewMessageContent) throws MessagingException {
Part textPart = MimeUtility.findFirstPartByMimeType(message, "text/plain");
if (textPart != null) {
String text = MimeUtility.getTextFromPart(textPart);
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "Loading message with offset " + bodyOffset + ", length " + bodyLength + ". Text length is " + text.length() + ".");
}
// If we had a body length (and it was valid), separate the composition from the quoted text
// and put them in their respective places in the UI.
if (bodyLength > 0) {
try {
String bodyText = text.substring(bodyOffset, bodyOffset + bodyLength);
// Regenerate the quoted text without our user content in it nor added newlines.
StringBuilder quotedText = new StringBuilder();
if (bodyOffset == 0 && text.substring(bodyLength, bodyLength + 4).equals("\r\n\r\n")) {
// top-posting: ignore two newlines at start of quote
quotedText.append(text.substring(bodyLength + 4));
} else if (bodyOffset + bodyLength == text.length() &&
text.substring(bodyOffset - 2, bodyOffset).equals("\r\n")) {
// bottom-posting: ignore newline at end of quote
quotedText.append(text.substring(0, bodyOffset - 2));
} else {
quotedText.append(text.substring(0, bodyOffset)); // stuff before the reply
quotedText.append(text.substring(bodyOffset + bodyLength));
}
if (viewMessageContent) {
mMessageContentView.setCharacters(bodyText);
}
mQuotedText.setCharacters(quotedText);
} catch (IndexOutOfBoundsException e) {
// Invalid bodyOffset or bodyLength. The draft was edited outside of K-9 Mail?
Log.d(K9.LOG_TAG, "The identity field from the draft contains an invalid bodyOffset/bodyLength");
if (viewMessageContent) {
mMessageContentView.setCharacters(text);
}
}
} else {
if (viewMessageContent) {
mMessageContentView.setCharacters(text);
}
}
}
}
// Regexes to check for signature.
private static final Pattern DASH_SIGNATURE_PLAIN = Pattern.compile("\r\n-- \r\n.*", Pattern.DOTALL);
private static final Pattern DASH_SIGNATURE_HTML = Pattern.compile("(<br( /)?>|\r?\n)-- <br( /)?>", Pattern.CASE_INSENSITIVE);
private static final Pattern BLOCKQUOTE_START = Pattern.compile("<blockquote", Pattern.CASE_INSENSITIVE);
private static final Pattern BLOCKQUOTE_END = Pattern.compile("</blockquote>", Pattern.CASE_INSENSITIVE);
/**
* Build and populate the UI with the quoted message.
*
* @param showQuotedText
* {@code true} if the quoted text should be shown, {@code false} otherwise.
*
* @throws MessagingException
*/
private void populateUIWithQuotedMessage(boolean showQuotedText) throws MessagingException {
MessageFormat origMessageFormat = mAccount.getMessageFormat();
if (mForcePlainText || origMessageFormat == MessageFormat.TEXT) {
// Use plain text for the quoted message
mQuotedTextFormat = SimpleMessageFormat.TEXT;
} else if (origMessageFormat == MessageFormat.AUTO) {
// Figure out which message format to use for the quoted text by looking if the source
// message contains a text/html part. If it does, we use that.
mQuotedTextFormat =
(MimeUtility.findFirstPartByMimeType(mSourceMessage, "text/html") == null) ?
SimpleMessageFormat.TEXT : SimpleMessageFormat.HTML;
} else {
mQuotedTextFormat = SimpleMessageFormat.HTML;
}
// TODO -- I am assuming that mSourceMessageBody will always be a text part. Is this a safe assumption?
// Handle the original message in the reply
// If we already have mSourceMessageBody, use that. It's pre-populated if we've got crypto going on.
String content = (mSourceMessageBody != null) ?
mSourceMessageBody :
getBodyTextFromMessage(mSourceMessage, mQuotedTextFormat);
if (mQuotedTextFormat == SimpleMessageFormat.HTML) {
// Strip signature.
// closing tags such as </div>, </span>, </table>, </pre> will be cut off.
if (mAccount.isStripSignature() &&
(mAction == Action.REPLY || mAction == Action.REPLY_ALL)) {
Matcher dashSignatureHtml = DASH_SIGNATURE_HTML.matcher(content);
if (dashSignatureHtml.find()) {
Matcher blockquoteStart = BLOCKQUOTE_START.matcher(content);
Matcher blockquoteEnd = BLOCKQUOTE_END.matcher(content);
List<Integer> start = new ArrayList<Integer>();
List<Integer> end = new ArrayList<Integer>();
while(blockquoteStart.find()) {
start.add(blockquoteStart.start());
}
while(blockquoteEnd.find()) {
end.add(blockquoteEnd.start());
}
if (start.size() != end.size()) {
Log.d(K9.LOG_TAG, "There are " + start.size() + " <blockquote> tags, but " +
end.size() + " </blockquote> tags. Refusing to strip.");
} else if (start.size() > 0) {
// Ignore quoted signatures in blockquotes.
dashSignatureHtml.region(0, start.get(0));
if (dashSignatureHtml.find()) {
// before first <blockquote>.
content = content.substring(0, dashSignatureHtml.start());
} else {
for (int i = 0; i < start.size() - 1; i++) {
// within blockquotes.
if (end.get(i) < start.get(i+1)) {
dashSignatureHtml.region(end.get(i), start.get(i+1));
if (dashSignatureHtml.find()) {
content = content.substring(0, dashSignatureHtml.start());
break;
}
}
}
if (end.get(end.size() - 1) < content.length()) {
// after last </blockquote>.
dashSignatureHtml.region(end.get(end.size() - 1), content.length());
if (dashSignatureHtml.find()) {
content = content.substring(0, dashSignatureHtml.start());
}
}
}
} else {
// No blockquotes found.
content = content.substring(0, dashSignatureHtml.start());
}
}
// Fix the stripping off of closing tags if a signature was stripped,
// as well as clean up the HTML of the quoted message.
HtmlCleaner cleaner = new HtmlCleaner();
CleanerProperties properties = cleaner.getProperties();
properties.setNamespacesAware(false);
properties.setAdvancedXmlEscape(false);
properties.setOmitXmlDeclaration(true);
properties.setOmitDoctypeDeclaration(false);
properties.setTranslateSpecialEntities(false);
properties.setRecognizeUnicodeChars(false);
TagNode node = cleaner.clean(content);
SimpleHtmlSerializer htmlSerialized = new SimpleHtmlSerializer(properties);
try {
content = htmlSerialized.getAsString(node, "UTF8");
} catch (java.io.IOException ioe) {
// Can't imagine this happening.
Log.e(K9.LOG_TAG, "Problem cleaning quoted message.", ioe);
}
}
// Add the HTML reply header to the top of the content.
mQuotedHtmlContent = quoteOriginalHtmlMessage(mSourceMessage, content, mQuoteStyle);
// Load the message with the reply header.
mQuotedHTML.setText(mQuotedHtmlContent.getQuotedContent());
// TODO: Also strip the signature from the text/plain part
mQuotedText.setCharacters(quoteOriginalTextMessage(mSourceMessage,
getBodyTextFromMessage(mSourceMessage, SimpleMessageFormat.TEXT), mQuoteStyle));
} else if (mQuotedTextFormat == SimpleMessageFormat.TEXT) {
if (mAccount.isStripSignature() &&
(mAction == Action.REPLY || mAction == Action.REPLY_ALL)) {
if (DASH_SIGNATURE_PLAIN.matcher(content).find()) {
content = DASH_SIGNATURE_PLAIN.matcher(content).replaceFirst("\r\n");
}
}
mQuotedText.setCharacters(quoteOriginalTextMessage(mSourceMessage, content, mQuoteStyle));
}
if (showQuotedText) {
showOrHideQuotedText(QuotedTextMode.SHOW);
} else {
showOrHideQuotedText(QuotedTextMode.HIDE);
}
}
/**
* Fetch the body text from a message in the desired message format. This method handles
* conversions between formats (html to text and vice versa) if necessary.
* @param message Message to analyze for body part.
* @param format Desired format.
* @return Text in desired format.
* @throws MessagingException
*/
private String getBodyTextFromMessage(final Message message, final SimpleMessageFormat format)
throws MessagingException {
Part part;
if (format == SimpleMessageFormat.HTML) {
// HTML takes precedence, then text.
part = MimeUtility.findFirstPartByMimeType(message, "text/html");
if (part != null) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "getBodyTextFromMessage: HTML requested, HTML found.");
return MimeUtility.getTextFromPart(part);
}
part = MimeUtility.findFirstPartByMimeType(message, "text/plain");
if (part != null) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "getBodyTextFromMessage: HTML requested, text found.");
return HtmlConverter.textToHtml(MimeUtility.getTextFromPart(part));
}
} else if (format == SimpleMessageFormat.TEXT) {
// Text takes precedence, then html.
part = MimeUtility.findFirstPartByMimeType(message, "text/plain");
if (part != null) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "getBodyTextFromMessage: Text requested, text found.");
return MimeUtility.getTextFromPart(part);
}
part = MimeUtility.findFirstPartByMimeType(message, "text/html");
if (part != null) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "getBodyTextFromMessage: Text requested, HTML found.");
return HtmlConverter.htmlToText(MimeUtility.getTextFromPart(part));
}
}
// If we had nothing interesting, return an empty string.
return "";
}
// Regular expressions to look for various HTML tags. This is no HTML::Parser, but hopefully it's good enough for
// our purposes.
private static final Pattern FIND_INSERTION_POINT_HTML = Pattern.compile("(?si:.*?(<html(?:>|\\s+[^>]*>)).*)");
private static final Pattern FIND_INSERTION_POINT_HEAD = Pattern.compile("(?si:.*?(<head(?:>|\\s+[^>]*>)).*)");
private static final Pattern FIND_INSERTION_POINT_BODY = Pattern.compile("(?si:.*?(<body(?:>|\\s+[^>]*>)).*)");
private static final Pattern FIND_INSERTION_POINT_HTML_END = Pattern.compile("(?si:.*(</html>).*?)");
private static final Pattern FIND_INSERTION_POINT_BODY_END = Pattern.compile("(?si:.*(</body>).*?)");
// The first group in a Matcher contains the first capture group. We capture the tag found in the above REs so that
// we can locate the *end* of that tag.
private static final int FIND_INSERTION_POINT_FIRST_GROUP = 1;
// HTML bits to insert as appropriate
// TODO is it safe to assume utf-8 here?
private static final String FIND_INSERTION_POINT_HTML_CONTENT = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\r\n<html>";
private static final String FIND_INSERTION_POINT_HTML_END_CONTENT = "</html>";
private static final String FIND_INSERTION_POINT_HEAD_CONTENT = "<head><meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"></head>";
// Index of the start of the beginning of a String.
private static final int FIND_INSERTION_POINT_START_OF_STRING = 0;
/**
* <p>Find the start and end positions of the HTML in the string. This should be the very top
* and bottom of the displayable message. It returns a {@link InsertableHtmlContent}, which
* contains both the insertion points and potentially modified HTML. The modified HTML should be
* used in place of the HTML in the original message.</p>
*
* <p>This method loosely mimics the HTML forward/reply behavior of BlackBerry OS 4.5/BIS 2.5, which in turn mimics
* Outlook 2003 (as best I can tell).</p>
*
* @param content Content to examine for HTML insertion points
* @return Insertion points and HTML to use for insertion.
*/
private InsertableHtmlContent findInsertionPoints(final String content) {
InsertableHtmlContent insertable = new InsertableHtmlContent();
// If there is no content, don't bother doing any of the regex dancing.
if (content == null || content.equals("")) {
return insertable;
}
// Search for opening tags.
boolean hasHtmlTag = false;
boolean hasHeadTag = false;
boolean hasBodyTag = false;
// First see if we have an opening HTML tag. If we don't find one, we'll add one later.
Matcher htmlMatcher = FIND_INSERTION_POINT_HTML.matcher(content);
if (htmlMatcher.matches()) {
hasHtmlTag = true;
}
// Look for a HEAD tag. If we're missing a BODY tag, we'll use the close of the HEAD to start our content.
Matcher headMatcher = FIND_INSERTION_POINT_HEAD.matcher(content);
if (headMatcher.matches()) {
hasHeadTag = true;
}
// Look for a BODY tag. This is the ideal place for us to start our content.
Matcher bodyMatcher = FIND_INSERTION_POINT_BODY.matcher(content);
if (bodyMatcher.matches()) {
hasBodyTag = true;
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Open: hasHtmlTag:" + hasHtmlTag + " hasHeadTag:" + hasHeadTag + " hasBodyTag:" + hasBodyTag);
// Given our inspections, let's figure out where to start our content.
// This is the ideal case -- there's a BODY tag and we insert ourselves just after it.
if (hasBodyTag) {
insertable.setQuotedContent(new StringBuilder(content));
insertable.setHeaderInsertionPoint(bodyMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP));
} else if (hasHeadTag) {
// Now search for a HEAD tag. We can insert after there.
// If BlackBerry sees a HEAD tag, it inserts right after that, so long as there is no BODY tag. It doesn't
// try to add BODY, either. Right or wrong, it seems to work fine.
insertable.setQuotedContent(new StringBuilder(content));
insertable.setHeaderInsertionPoint(headMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP));
} else if (hasHtmlTag) {
// Lastly, check for an HTML tag.
// In this case, it will add a HEAD, but no BODY.
StringBuilder newContent = new StringBuilder(content);
// Insert the HEAD content just after the HTML tag.
newContent.insert(htmlMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP), FIND_INSERTION_POINT_HEAD_CONTENT);
insertable.setQuotedContent(newContent);
// The new insertion point is the end of the HTML tag, plus the length of the HEAD content.
insertable.setHeaderInsertionPoint(htmlMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP) + FIND_INSERTION_POINT_HEAD_CONTENT.length());
} else {
// If we have none of the above, we probably have a fragment of HTML. Yahoo! and Gmail both do this.
// Again, we add a HEAD, but not BODY.
StringBuilder newContent = new StringBuilder(content);
// Add the HTML and HEAD tags.
newContent.insert(FIND_INSERTION_POINT_START_OF_STRING, FIND_INSERTION_POINT_HEAD_CONTENT);
newContent.insert(FIND_INSERTION_POINT_START_OF_STRING, FIND_INSERTION_POINT_HTML_CONTENT);
// Append the </HTML> tag.
newContent.append(FIND_INSERTION_POINT_HTML_END_CONTENT);
insertable.setQuotedContent(newContent);
insertable.setHeaderInsertionPoint(FIND_INSERTION_POINT_HTML_CONTENT.length() + FIND_INSERTION_POINT_HEAD_CONTENT.length());
}
// Search for closing tags. We have to do this after we deal with opening tags since it may
// have modified the message.
boolean hasHtmlEndTag = false;
boolean hasBodyEndTag = false;
// First see if we have an opening HTML tag. If we don't find one, we'll add one later.
Matcher htmlEndMatcher = FIND_INSERTION_POINT_HTML_END.matcher(insertable.getQuotedContent());
if (htmlEndMatcher.matches()) {
hasHtmlEndTag = true;
}
// Look for a BODY tag. This is the ideal place for us to place our footer.
Matcher bodyEndMatcher = FIND_INSERTION_POINT_BODY_END.matcher(insertable.getQuotedContent());
if (bodyEndMatcher.matches()) {
hasBodyEndTag = true;
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Close: hasHtmlEndTag:" + hasHtmlEndTag + " hasBodyEndTag:" + hasBodyEndTag);
// Now figure out where to put our footer.
// This is the ideal case -- there's a BODY tag and we insert ourselves just before it.
if (hasBodyEndTag) {
insertable.setFooterInsertionPoint(bodyEndMatcher.start(FIND_INSERTION_POINT_FIRST_GROUP));
} else if (hasHtmlEndTag) {
// Check for an HTML tag. Add ourselves just before it.
insertable.setFooterInsertionPoint(htmlEndMatcher.start(FIND_INSERTION_POINT_FIRST_GROUP));
} else {
// If we have none of the above, we probably have a fragment of HTML.
// Set our footer insertion point as the end of the string.
insertable.setFooterInsertionPoint(insertable.getQuotedContent().length());
}
return insertable;
}
class Listener extends MessagingListener {
@Override
public void loadMessageForViewStarted(Account account, String folder, String uid) {
if ((mMessageReference == null) || !mMessageReference.uid.equals(uid)) {
return;
}
mHandler.sendEmptyMessage(MSG_PROGRESS_ON);
}
@Override
public void loadMessageForViewFinished(Account account, String folder, String uid, Message message) {
if ((mMessageReference == null) || !mMessageReference.uid.equals(uid)) {
return;
}
mHandler.sendEmptyMessage(MSG_PROGRESS_OFF);
}
@Override
public void loadMessageForViewBodyAvailable(Account account, String folder, String uid, final Message message) {
if ((mMessageReference == null) || !mMessageReference.uid.equals(uid)) {
return;
}
mSourceMessage = message;
runOnUiThread(new Runnable() {
@Override
public void run() {
// We check to see if we've previously processed the source message since this
// could be called when switching from HTML to text replies. If that happens, we
// only want to update the UI with quoted text (which picks the appropriate
// part).
if (mSourceProcessed) {
try {
populateUIWithQuotedMessage(true);
} catch (MessagingException e) {
// Hm, if we couldn't populate the UI after source reprocessing, let's just delete it?
showOrHideQuotedText(QuotedTextMode.HIDE);
Log.e(K9.LOG_TAG, "Could not re-process source message; deleting quoted text to be safe.", e);
}
updateMessageFormat();
} else {
processSourceMessage(message);
mSourceProcessed = true;
}
}
});
}
@Override
public void loadMessageForViewFailed(Account account, String folder, String uid, Throwable t) {
if ((mMessageReference == null) || !mMessageReference.uid.equals(uid)) {
return;
}
mHandler.sendEmptyMessage(MSG_PROGRESS_OFF);
// TODO show network error
}
@Override
public void messageUidChanged(Account account, String folder, String oldUid, String newUid) {
// Track UID changes of the source message
if (mMessageReference != null) {
final Account sourceAccount = Preferences.getPreferences(MessageCompose.this).getAccount(mMessageReference.accountUuid);
final String sourceFolder = mMessageReference.folderName;
final String sourceMessageUid = mMessageReference.uid;
if (account.equals(sourceAccount) && (folder.equals(sourceFolder))) {
if (oldUid.equals(sourceMessageUid)) {
mMessageReference.uid = newUid;
}
if ((mSourceMessage != null) && (oldUid.equals(mSourceMessage.getUid()))) {
mSourceMessage.setUid(newUid);
}
}
}
}
}
/**
* When we are launched with an intent that includes a mailto: URI, we can actually
* gather quite a few of our message fields from it.
*
* @param mailtoUri
* The mailto: URI we use to initialize the message fields.
*/
private void initializeFromMailto(Uri mailtoUri) {
String schemaSpecific = mailtoUri.getSchemeSpecificPart();
int end = schemaSpecific.indexOf('?');
if (end == -1) {
end = schemaSpecific.length();
}
// Extract the recipient's email address from the mailto URI if there's one.
String recipient = Uri.decode(schemaSpecific.substring(0, end));
/*
* mailto URIs are not hierarchical. So calling getQueryParameters()
* will throw an UnsupportedOperationException. We avoid this by
* creating a new hierarchical dummy Uri object with the query
* parameters of the original URI.
*/
CaseInsensitiveParamWrapper uri = new CaseInsensitiveParamWrapper(
Uri.parse("foo://bar?" + mailtoUri.getEncodedQuery()));
// Read additional recipients from the "to" parameter.
List<String> to = uri.getQueryParameters("to");
if (recipient.length() != 0) {
to = new ArrayList<String>(to);
to.add(0, recipient);
}
addRecipients(mToView, to);
// Read carbon copy recipients from the "cc" parameter.
boolean ccOrBcc = addRecipients(mCcView, uri.getQueryParameters("cc"));
// Read blind carbon copy recipients from the "bcc" parameter.
ccOrBcc |= addRecipients(mBccView, uri.getQueryParameters("bcc"));
if (ccOrBcc) {
// Display CC and BCC text fields if CC or BCC recipients were set by the intent.
onAddCcBcc();
}
// Read subject from the "subject" parameter.
List<String> subject = uri.getQueryParameters("subject");
if (!subject.isEmpty()) {
mSubjectView.setText(subject.get(0));
}
// Read message body from the "body" parameter.
List<String> body = uri.getQueryParameters("body");
if (!body.isEmpty()) {
mMessageContentView.setCharacters(body.get(0));
}
}
private static class CaseInsensitiveParamWrapper {
private final Uri uri;
private Set<String> mParamNames;
public CaseInsensitiveParamWrapper(Uri uri) {
this.uri = uri;
}
public List<String> getQueryParameters(String key) {
final List<String> params = new ArrayList<String>();
for (String paramName : getQueryParameterNames()) {
if (paramName.equalsIgnoreCase(key)) {
params.addAll(uri.getQueryParameters(paramName));
}
}
return params;
}
@TargetApi(11)
private Set<String> getQueryParameterNames() {
if (Build.VERSION.SDK_INT >= 11) {
return uri.getQueryParameterNames();
}
return getQueryParameterNamesPreSdk11();
}
private Set<String> getQueryParameterNamesPreSdk11() {
if (mParamNames == null) {
String query = uri.getQuery();
Set<String> paramNames = new HashSet<String>();
Collections.addAll(paramNames, query.split("(=[^&]*(&|$))|&"));
mParamNames = paramNames;
}
return mParamNames;
}
}
private class SendMessageTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
/*
* Create the message from all the data the user has entered.
*/
MimeMessage message;
try {
message = createMessage(false); // isDraft = true
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Failed to create new message for send or save.", me);
throw new RuntimeException("Failed to create a new message for send or save.", me);
}
try {
mContacts.markAsContacted(message.getRecipients(RecipientType.TO));
mContacts.markAsContacted(message.getRecipients(RecipientType.CC));
mContacts.markAsContacted(message.getRecipients(RecipientType.BCC));
} catch (Exception e) {
Log.e(K9.LOG_TAG, "Failed to mark contact as contacted.", e);
}
MessagingController.getInstance(getApplication()).sendMessage(mAccount, message, null);
long draftId = mDraftId;
if (draftId != INVALID_DRAFT_ID) {
mDraftId = INVALID_DRAFT_ID;
MessagingController.getInstance(getApplication()).deleteDraft(mAccount, draftId);
}
return null;
}
}
private class SaveMessageTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
/*
* Create the message from all the data the user has entered.
*/
MimeMessage message;
try {
message = createMessage(true); // isDraft = true
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Failed to create new message for send or save.", me);
throw new RuntimeException("Failed to create a new message for send or save.", me);
}
/*
* Save a draft
*/
if (mAction == Action.EDIT_DRAFT) {
/*
* We're saving a previously saved draft, so update the new message's uid
* to the old message's uid.
*/
if (mMessageReference != null) {
message.setUid(mMessageReference.uid);
}
}
final MessagingController messagingController = MessagingController.getInstance(getApplication());
Message draftMessage = messagingController.saveDraft(mAccount, message, mDraftId);
mDraftId = messagingController.getId(draftMessage);
mHandler.sendEmptyMessage(MSG_SAVED_DRAFT);
return null;
}
}
private static final int REPLY_WRAP_LINE_WIDTH = 72;
private static final int QUOTE_BUFFER_LENGTH = 512; // amount of extra buffer to allocate to accommodate quoting headers or prefixes
/**
* Add quoting markup to a text message.
* @param originalMessage Metadata for message being quoted.
* @param messageBody Text of the message to be quoted.
* @param quoteStyle Style of quoting.
* @return Quoted text.
* @throws MessagingException
*/
private String quoteOriginalTextMessage(final Message originalMessage, final String messageBody, final QuoteStyle quoteStyle) throws MessagingException {
String body = messageBody == null ? "" : messageBody;
if (quoteStyle == QuoteStyle.PREFIX) {
StringBuilder quotedText = new StringBuilder(body.length() + QUOTE_BUFFER_LENGTH);
quotedText.append(String.format(
getString(R.string.message_compose_reply_header_fmt) + "\r\n",
Address.toString(originalMessage.getFrom()))
);
final String prefix = mAccount.getQuotePrefix();
final String wrappedText = Utility.wrap(body, REPLY_WRAP_LINE_WIDTH - prefix.length());
// "$" and "\" in the quote prefix have to be escaped for
// the replaceAll() invocation.
final String escapedPrefix = prefix.replaceAll("(\\\\|\\$)", "\\\\$1");
quotedText.append(wrappedText.replaceAll("(?m)^", escapedPrefix));
return quotedText.toString().replaceAll("\\\r", "");
} else if (quoteStyle == QuoteStyle.HEADER) {
StringBuilder quotedText = new StringBuilder(body.length() + QUOTE_BUFFER_LENGTH);
quotedText.append("\r\n");
quotedText.append(getString(R.string.message_compose_quote_header_separator)).append("\r\n");
if (originalMessage.getFrom() != null && Address.toString(originalMessage.getFrom()).length() != 0) {
quotedText.append(getString(R.string.message_compose_quote_header_from)).append(" ").append(Address.toString(originalMessage.getFrom())).append("\r\n");
}
if (originalMessage.getSentDate() != null) {
quotedText.append(getString(R.string.message_compose_quote_header_send_date)).append(" ").append(originalMessage.getSentDate()).append("\r\n");
}
if (originalMessage.getRecipients(RecipientType.TO) != null && originalMessage.getRecipients(RecipientType.TO).length != 0) {
quotedText.append(getString(R.string.message_compose_quote_header_to)).append(" ").append(Address.toString(originalMessage.getRecipients(RecipientType.TO))).append("\r\n");
}
if (originalMessage.getRecipients(RecipientType.CC) != null && originalMessage.getRecipients(RecipientType.CC).length != 0) {
quotedText.append(getString(R.string.message_compose_quote_header_cc)).append(" ").append(Address.toString(originalMessage.getRecipients(RecipientType.CC))).append("\r\n");
}
if (originalMessage.getSubject() != null) {
quotedText.append(getString(R.string.message_compose_quote_header_subject)).append(" ").append(originalMessage.getSubject()).append("\r\n");
}
quotedText.append("\r\n");
quotedText.append(body);
return quotedText.toString();
} else {
// Shouldn't ever happen.
return body;
}
}
/**
* Add quoting markup to a HTML message.
* @param originalMessage Metadata for message being quoted.
* @param messageBody Text of the message to be quoted.
* @param quoteStyle Style of quoting.
* @return Modified insertable message.
* @throws MessagingException
*/
private InsertableHtmlContent quoteOriginalHtmlMessage(final Message originalMessage, final String messageBody, final QuoteStyle quoteStyle) throws MessagingException {
InsertableHtmlContent insertable = findInsertionPoints(messageBody);
if (quoteStyle == QuoteStyle.PREFIX) {
StringBuilder header = new StringBuilder(QUOTE_BUFFER_LENGTH);
header.append("<div class=\"gmail_quote\">");
header.append(HtmlConverter.textToHtmlFragment(String.format(
getString(R.string.message_compose_reply_header_fmt),
Address.toString(originalMessage.getFrom()))
));
header.append("<blockquote class=\"gmail_quote\" " +
"style=\"margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;\">\r\n");
String footer = "</blockquote></div>";
insertable.insertIntoQuotedHeader(header.toString());
insertable.insertIntoQuotedFooter(footer);
} else if (quoteStyle == QuoteStyle.HEADER) {
StringBuilder header = new StringBuilder();
header.append("<div style='font-size:10.0pt;font-family:\"Tahoma\",\"sans-serif\";padding:3.0pt 0in 0in 0in'>\r\n");
header.append("<hr style='border:none;border-top:solid #E1E1E1 1.0pt'>\r\n"); // This gets converted into a horizontal line during html to text conversion.
if (mSourceMessage.getFrom() != null && Address.toString(mSourceMessage.getFrom()).length() != 0) {
header.append("<b>").append(getString(R.string.message_compose_quote_header_from)).append("</b> ")
.append(HtmlConverter.textToHtmlFragment(Address.toString(mSourceMessage.getFrom())))
.append("<br>\r\n");
}
if (mSourceMessage.getSentDate() != null) {
header.append("<b>").append(getString(R.string.message_compose_quote_header_send_date)).append("</b> ")
.append(mSourceMessage.getSentDate())
.append("<br>\r\n");
}
if (mSourceMessage.getRecipients(RecipientType.TO) != null && mSourceMessage.getRecipients(RecipientType.TO).length != 0) {
header.append("<b>").append(getString(R.string.message_compose_quote_header_to)).append("</b> ")
.append(HtmlConverter.textToHtmlFragment(Address.toString(mSourceMessage.getRecipients(RecipientType.TO))))
.append("<br>\r\n");
}
if (mSourceMessage.getRecipients(RecipientType.CC) != null && mSourceMessage.getRecipients(RecipientType.CC).length != 0) {
header.append("<b>").append(getString(R.string.message_compose_quote_header_cc)).append("</b> ")
.append(HtmlConverter.textToHtmlFragment(Address.toString(mSourceMessage.getRecipients(RecipientType.CC))))
.append("<br>\r\n");
}
if (mSourceMessage.getSubject() != null) {
header.append("<b>").append(getString(R.string.message_compose_quote_header_subject)).append("</b> ")
.append(HtmlConverter.textToHtmlFragment(mSourceMessage.getSubject()))
.append("<br>\r\n");
}
header.append("</div>\r\n");
header.append("<br>\r\n");
insertable.insertIntoQuotedHeader(header.toString());
}
return insertable;
}
/**
* Used to store an {@link Identity} instance together with the {@link Account} it belongs to.
*
* @see IdentityAdapter
*/
static class IdentityContainer {
public final Identity identity;
public final Account account;
IdentityContainer(Identity identity, Account account) {
this.identity = identity;
this.account = account;
}
}
/**
* Adapter for the <em>Choose identity</em> list view.
*
* <p>
* Account names are displayed as section headers, identities as selectable list items.
* </p>
*/
static class IdentityAdapter extends BaseAdapter {
private LayoutInflater mLayoutInflater;
private List<Object> mItems;
public IdentityAdapter(Context context) {
mLayoutInflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
List<Object> items = new ArrayList<Object>();
Preferences prefs = Preferences.getPreferences(context.getApplicationContext());
Account[] accounts = prefs.getAvailableAccounts().toArray(EMPTY_ACCOUNT_ARRAY);
for (Account account : accounts) {
items.add(account);
List<Identity> identities = account.getIdentities();
for (Identity identity : identities) {
items.add(new IdentityContainer(identity, account));
}
}
mItems = items;
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int position) {
return (mItems.get(position) instanceof Account) ? 0 : 1;
}
@Override
public boolean isEnabled(int position) {
return (mItems.get(position) instanceof IdentityContainer);
}
@Override
public Object getItem(int position) {
return mItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Object item = mItems.get(position);
View view = null;
if (item instanceof Account) {
if (convertView != null && convertView.getTag() instanceof AccountHolder) {
view = convertView;
} else {
view = mLayoutInflater.inflate(R.layout.choose_account_item, parent, false);
AccountHolder holder = new AccountHolder();
holder.name = (TextView) view.findViewById(R.id.name);
holder.chip = view.findViewById(R.id.chip);
view.setTag(holder);
}
Account account = (Account) item;
AccountHolder holder = (AccountHolder) view.getTag();
holder.name.setText(account.getDescription());
holder.chip.setBackgroundColor(account.getChipColor());
} else if (item instanceof IdentityContainer) {
if (convertView != null && convertView.getTag() instanceof IdentityHolder) {
view = convertView;
} else {
view = mLayoutInflater.inflate(R.layout.choose_identity_item, parent, false);
IdentityHolder holder = new IdentityHolder();
holder.name = (TextView) view.findViewById(R.id.name);
holder.description = (TextView) view.findViewById(R.id.description);
view.setTag(holder);
}
IdentityContainer identityContainer = (IdentityContainer) item;
Identity identity = identityContainer.identity;
IdentityHolder holder = (IdentityHolder) view.getTag();
holder.name.setText(identity.getDescription());
holder.description.setText(getIdentityDescription(identity));
}
return view;
}
static class AccountHolder {
public TextView name;
public View chip;
}
static class IdentityHolder {
public TextView name;
public TextView description;
}
}
private static String getIdentityDescription(Identity identity) {
return String.format("%s <%s>", identity.getName(), identity.getEmail());
}
private void setMessageFormat(SimpleMessageFormat format) {
// This method will later be used to enable/disable the rich text editing mode.
mMessageFormat = format;
}
private void updateMessageFormat() {
MessageFormat origMessageFormat = mAccount.getMessageFormat();
SimpleMessageFormat messageFormat;
if (origMessageFormat == MessageFormat.TEXT) {
// The user wants to send text/plain messages. We don't override that choice under
// any circumstances.
messageFormat = SimpleMessageFormat.TEXT;
} else if (mForcePlainText && includeQuotedText()) {
// Right now we send a text/plain-only message when the quoted text was edited, no
// matter what the user selected for the message format.
messageFormat = SimpleMessageFormat.TEXT;
} else if (mEncryptCheckbox.isChecked() || mCryptoSignatureCheckbox.isChecked()) {
// Right now we only support PGP inline which doesn't play well with HTML. So force
// plain text in those cases.
messageFormat = SimpleMessageFormat.TEXT;
} else if (origMessageFormat == MessageFormat.AUTO) {
if (mAction == Action.COMPOSE || mQuotedTextFormat == SimpleMessageFormat.TEXT ||
!includeQuotedText()) {
// If the message format is set to "AUTO" we use text/plain whenever possible. That
// is, when composing new messages and replying to or forwarding text/plain
// messages.
messageFormat = SimpleMessageFormat.TEXT;
} else {
messageFormat = SimpleMessageFormat.HTML;
}
} else {
// In all other cases use HTML
messageFormat = SimpleMessageFormat.HTML;
}
setMessageFormat(messageFormat);
}
private boolean includeQuotedText() {
return (mQuotedTextMode == QuotedTextMode.SHOW);
}
/**
* An {@link EditText} extension with methods that convert line endings from
* {@code \r\n} to {@code \n} and back again when setting and getting text.
*
*/
private static class EolConvertingEditText extends EditText {
public EolConvertingEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* Return the text the EolConvertingEditText is displaying.
*
* @return A string with any line endings converted to {@code \r\n}.
*/
public String getCharacters() {
return getText().toString().replace("\n", "\r\n");
}
/**
* Sets the string value of the EolConvertingEditText. Any line endings
* in the string will be converted to {@code \n}.
*
* @param text
*/
public void setCharacters(CharSequence text) {
setText(text.toString().replace("\r\n", "\n"));
}
}
}
|
package it.backbox.gui;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSpinner;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.RowSorter;
import javax.swing.ScrollPaneConstants;
import javax.swing.SortOrder;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import javax.swing.tree.TreePath;
import it.backbox.bean.Chunk;
import it.backbox.bean.Folder;
import it.backbox.exception.BackBoxException;
import it.backbox.exception.RestException;
import it.backbox.gui.model.FileBrowserTableModel;
import it.backbox.gui.model.FileBrowserTableRowSorter;
import it.backbox.gui.model.FileBrowserTreeCellRenderer;
import it.backbox.gui.model.FileBrowserTreeModel;
import it.backbox.gui.model.FileBrowserTreeNode;
import it.backbox.gui.model.FileBrowserTreeNode.TreeNodeType;
import it.backbox.gui.model.FileBrowserTreeSelectionListener;
import it.backbox.gui.model.PreviewTableCellRenderer;
import it.backbox.gui.model.PreviewTableModel;
import it.backbox.gui.utility.BackBoxHelper;
import it.backbox.gui.utility.GuiUtility;
import it.backbox.gui.utility.ThreadActionListener;
import it.backbox.progress.ProgressListener;
import it.backbox.progress.ProgressManager;
import it.backbox.transaction.DeleteDBTask;
import it.backbox.transaction.DeleteRemoteTask;
import it.backbox.transaction.Task;
import it.backbox.transaction.Transaction;
import it.backbox.transaction.TransactionManager.CompleteTransactionListener;
import it.backbox.utility.Utility;
import net.miginfocom.swing.MigLayout;
public class BackBoxGui {
private static final Logger _log = Logger.getLogger("it.backbox");
private JFrame frmBackBox;
private JTable table;
private JTree tree;
private PasswordDialog pwdDialog;
private ConfigurationDialog configurationDialog;
private PreferencesDialog preferencesDialog;
private JLabel lblStatus;
private NewConfDialog newConfDialog;
private JTable tablePreview;
private JButton btnConnect;
private JLabel lblEtaValue;
private JButton btnBackupAll;
private JButton btnRestoreAll;
private LoadingDialog loadingDialog;
private JButton btnClear;
private JButton btnStart;
private JButton btnStop;
private DetailsDialog detailsDialog;
private JMenuItem mntmUploadDb;
private JMenuItem mntmDownloadDb;
private JSpinner spnCurrentUploadSpeed;
private JMenuItem mntmNewConfiguration;
private JMenuItem mntmConfiguration;
private JLabel lblFreeSpaceValue;
private JMenuItem mntmCheck;
private JMenu mntmBackup;
private JMenu mntmRestore;
private JMenuItem mntmBuildDatabase;
private JProgressBar progressBar;
protected BackBoxHelper helper;
private ProgressManager pm;
private boolean connected = false;
private boolean running = false;
private boolean pending = false;
private boolean pendingDone = false;
/**
* Launch the application.
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
BackBoxGui window = new BackBoxGui();
window.frmBackBox.setVisible(true);
if (window.helper.confExists()) {
window.pwdDialog.setLocationRelativeTo(window.frmBackBox);
window.pwdDialog.load(GuiConstant.LOGIN_MODE);
window.pwdDialog.setVisible(true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void connect() {
GuiUtility.checkEDT(false);
connected = true;
final int uploadSpeed = helper.getConfiguration().getDefaultUploadSpeed();
pm.setSpeed(ProgressManager.UPLOAD_ID, uploadSpeed);
pm.setSpeed(ProgressManager.DOWNLOAD_ID, helper.getConfiguration().getDefaultDownloadSpeed());
helper.tm.addListener(new CompleteTransactionListener() {
@Override
public void transactionCompleted(Transaction tt) {
updateTableResult(tt);
}
});
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
spnCurrentUploadSpeed.setValue(uploadSpeed / 1024);
updateFileBrowser();
updateMenu();
updateStatus();
}
});
}
public void disconnect(final boolean clear) {
GuiUtility.checkEDT(false);
try {
if (helper.tm != null) {
if (running) {
helper.tm.stopTransactions();
pendingDone = true;
}
helper.tm.clear();
}
if (connected)
helper.logout();
connected = false;
running = false;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (clear) {
FileBrowserTableModel model = (FileBrowserTableModel) table.getModel();
while(model.getRowCount() > 0)
model.removeRow(0);
clearPreviewTable();
mntmBackup.removeAll();
mntmBackup.setEnabled(false);
mntmRestore.removeAll();
mntmRestore.setEnabled(false);
}
updateStatus();
}
});
} catch (Exception e) {
GuiUtility.handleException(frmBackBox, "Error in logout", e);
}
}
public void updateMenu() {
GuiUtility.checkEDT(true);
mntmBackup.removeAll();
mntmBackup.setEnabled(false);
mntmRestore.removeAll();
mntmRestore.setEnabled(false);
final List<Folder> folders = helper.getConfiguration().getBackupFolders();
for (final Folder f : folders) {
JMenuItem mntmFolderB = new JMenuItem(f.getAlias());
mntmFolderB.addActionListener(new ThreadActionListener() {
private List<Transaction> tt = null;
@Override
protected boolean preaction(ActionEvent event) {
if (running) {
JOptionPane.showMessageDialog(frmBackBox, "Transactions running", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
if (!connected) {
JOptionPane.showMessageDialog(frmBackBox, "Not connected", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
@Override
protected void action(ActionEvent event) {
helper.tm.clear();
try {
tt = helper.backup(f, false);
} catch (final Exception e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
loadingDialog.hideLoading();
GuiUtility.handleException(frmBackBox, "Error building backup transactions", e);
}
});
}
}
@Override
protected void postaction(ActionEvent event) {
clearPreviewTable();
updatePreviewTable(tt);
if ((tt == null) || tt.isEmpty()) {
loadingDialog.hideLoading();
JOptionPane.showMessageDialog(frmBackBox, "No files to backup", "Info", JOptionPane.INFORMATION_MESSAGE);
} else {
pending = true;
pendingDone = false;
}
updateStatus();
}
});
JMenuItem mntmFolderR = new JMenuItem(f.getAlias());
mntmFolderR.addActionListener(new ThreadActionListener() {
private List<Transaction> tt = null;
@Override
protected boolean preaction(ActionEvent event) {
if (running) {
JOptionPane.showMessageDialog(frmBackBox, "Transactions running", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
if (!connected) {
JOptionPane.showMessageDialog(frmBackBox, "Not connected", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
@Override
protected void action(ActionEvent event) {
final JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = fc.showOpenDialog(frmBackBox);
if (returnVal == JFileChooser.APPROVE_OPTION) {
helper.tm.clear();
try {
tt = helper.restore(fc.getSelectedFile().getCanonicalPath(), f, false);
} catch (final Exception e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
loadingDialog.hideLoading();
GuiUtility.handleException(frmBackBox, "Error building restore transactions", e);
}
});
}
}
}
@Override
protected void postaction(ActionEvent event) {
clearPreviewTable();
updatePreviewTable(tt);
if ((tt == null) || tt.isEmpty()) {
loadingDialog.hideLoading();
JOptionPane.showMessageDialog(frmBackBox, "No files to restore", "Info", JOptionPane.INFORMATION_MESSAGE);
} else {
pending = true;
pendingDone = false;
}
updateStatus();
}
});
mntmBackup.add(mntmFolderB);
mntmRestore.add(mntmFolderR);
}
mntmBackup.setEnabled(true);
mntmRestore.setEnabled(true);
}
private void updateFileBrowser() {
GuiUtility.checkEDT(true);
final List<Folder> folders = helper.getConfiguration().getBackupFolders();
final FileBrowserTreeModel model = (FileBrowserTreeModel) tree.getModel();
final FileBrowserTreeNode root = (FileBrowserTreeNode) model.getRoot();
root.removeAllChildren();
for (Folder f : folders)
model.insertNodeInto(new FileBrowserTreeNode(f.getAlias(), TreeNodeType.FOLDER), root);
model.reload(root);
}
private void updatePreviewTable(List<Transaction> transactions) {
GuiUtility.checkEDT(true);
final DefaultTableModel model = (DefaultTableModel) tablePreview.getModel();
if (transactions != null)
for (Transaction tt : transactions)
for (final Task t : tt.getTasks())
model.addRow(new Object[] {t.getDescription(), GuiUtility.getTaskSize(t), GuiUtility.getTaskType(t), "", tt, t});
pending = ((transactions != null) && !transactions.isEmpty());
}
private void clearPreviewTable() {
GuiUtility.checkEDT(true);
DefaultTableModel model = (DefaultTableModel) tablePreview.getModel();
while (model.getRowCount() > 0)
model.removeRow(0);
}
private void updateTableResult(Transaction transaction) {
GuiUtility.checkEDT(true);
if (transaction == null)
return;
DefaultTableModel model = (DefaultTableModel) tablePreview.getModel();
for (Task task : transaction.getTasks()) {
for (int i = 0; i < model.getRowCount(); i++) {
Task tm = (Task) model.getValueAt(i, PreviewTableModel.TASK_COLUMN_INDEX);
if (tm.getId().equals(task.getId())) {
short resultCode = transaction.getResultCode();
model.setValueAt(transaction, i, PreviewTableModel.TRANSACTION_COLUMN_INDEX);
model.setValueAt(task, i, PreviewTableModel.TASK_COLUMN_INDEX);
if (resultCode < 0)
model.setValueAt(GuiConstant.RESULT_ERROR, i, PreviewTableModel.RESULT_COLUMN_INDEX);
else if (resultCode == Transaction.Result.OK)
model.setValueAt(GuiConstant.RESULT_SUCCESS, i, PreviewTableModel.RESULT_COLUMN_INDEX);
break;
}
}
}
}
private void updateStatus() {
GuiUtility.checkEDT(true);
if (running)
lblStatus.setText("Running...");
else if (pending && !pendingDone)
lblStatus.setText("Operations pending");
else if (connected)
lblStatus.setText("Connected");
else
lblStatus.setText("Not connected");
btnConnect.setEnabled(!connected);
btnBackupAll.setEnabled(connected && !running);
btnRestoreAll.setEnabled(connected && !running);
btnStart.setEnabled(connected && !running && pending && !pendingDone);
btnStop.setEnabled(connected && running);
btnClear.setEnabled(connected && !running && pending);
mntmUploadDb.setEnabled(!running);
mntmDownloadDb.setEnabled(!running);
mntmNewConfiguration.setEnabled(!running);
mntmConfiguration.setEnabled(connected && !running);
mntmCheck.setEnabled(connected && !running);
mntmBackup.setEnabled(connected && !running);
mntmRestore.setEnabled(connected && !running);
mntmBuildDatabase.setEnabled(!connected);
if (connected && !running && !pending)
try {
lblFreeSpaceValue.setText(Utility.humanReadableByteCount(helper.getFreeSpace(), false));
} catch (IOException | RestException | BackBoxException e) {
lblFreeSpaceValue.setText("Error");
_log.log(Level.WARNING, "Error retrieving free space", e);
}
else if (!connected)
lblFreeSpaceValue.setText("");
}
/**
* Create the application.
*/
public BackBoxGui() {
initializeFrame();
helper = BackBoxHelper.getInstance();
pm = ProgressManager.getInstance();
try {
helper.loadConfiguration();
} catch (IOException e) {
GuiUtility.handleException(frmBackBox, "Error loading configuration file, using default configuration...", e);
}
initializeMenu();
Component up = initializeFileBrowser();
Component down = initializeOp();
JSplitPane splitPane = new JSplitPane(
JSplitPane.VERTICAL_SPLIT, up, down);
Dimension preferredSize = up.getPreferredSize();
Dimension halfSize = new Dimension((int) preferredSize.getWidth(), frmBackBox.getHeight() / 2);
up.setMinimumSize(halfSize);
frmBackBox.getContentPane().add(splitPane, BorderLayout.CENTER);
updateStatus();
pwdDialog = new PasswordDialog(this, frmBackBox);
newConfDialog = new NewConfDialog(this, frmBackBox);
loadingDialog = new LoadingDialog(frmBackBox);
detailsDialog = new DetailsDialog(frmBackBox);
preferencesDialog = new PreferencesDialog(frmBackBox);
configurationDialog = new ConfigurationDialog(this, frmBackBox);
}
private final Thread exitThread = new Thread() {
public void run() {
try {
if (connected && helper.getConfiguration().isAutoUploadConf())
helper.uploadConf(false);
disconnect(false);
System.exit(0);
} catch (Exception e) {
GuiUtility.handleException(frmBackBox, "Error in logout", e);
}
loadingDialog.hideLoading();
}
};
/**
* Initialize the contents of the frame.
*/
private void initializeFrame() {
GuiUtility.checkEDT(true);
frmBackBox = new JFrame();
frmBackBox.setLocationRelativeTo(null);
frmBackBox.setSize(750, 700);
frmBackBox.setTitle("BackBox");
frmBackBox.setBounds(100, 100, 732, 692);
frmBackBox.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frmBackBox.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
loadingDialog.showLoading();
exitThread.start();
}
});
}
private Component initializeOp() {
GuiUtility.checkEDT(true);
JPanel pnlOp = new JPanel();
pnlOp.setLayout(new MigLayout("", "[90px:n:90px][90px:n:90px][90px:n:90px][40px:40px][35px][201.00,grow][100px:100px:100px][35.00:35.00:35.00][90px:90px:90px]", "[20px][282.00,grow,fill][]"));
btnBackupAll = new JButton("Backup All");
btnBackupAll.setMnemonic('B');
btnBackupAll.setEnabled(connected);
btnBackupAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (running) {
JOptionPane.showMessageDialog(frmBackBox, "Transactions running", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (connected) {
helper.tm.clear();
loadingDialog.showLoading();
Thread worker = new Thread() {
public void run() {
List<Transaction> tt = null;
try {
tt = helper.backupAll();
} catch (Exception e) {
loadingDialog.hideLoading();
GuiUtility.handleException(frmBackBox, "Error building backup transactions", e);
} finally {
clearPreviewTable();
updatePreviewTable(tt);
if ((tt == null) || tt.isEmpty()) {
loadingDialog.hideLoading();
JOptionPane.showMessageDialog(frmBackBox, "No files to backup", "Info", JOptionPane.INFORMATION_MESSAGE);
} else {
pending = true;
pendingDone = false;
}
updateStatus();
}
loadingDialog.hideLoading();
}
};
worker.start();
} else
JOptionPane.showMessageDialog(frmBackBox, "Not connected", "Error", JOptionPane.ERROR_MESSAGE);
}
});
btnConnect = new JButton("Connect");
btnConnect.setMnemonic('c');
btnConnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (helper.confExists()) {
pwdDialog.setLocationRelativeTo(frmBackBox);
pwdDialog.load(GuiConstant.LOGIN_MODE);
pwdDialog.setVisible(true);
} else
JOptionPane.showMessageDialog(frmBackBox, "Configuration not found", "Error", JOptionPane.ERROR_MESSAGE);
}
});
pnlOp.add(btnConnect, "cell 0 0,grow");
pnlOp.add(btnBackupAll, "cell 1 0,grow");
btnRestoreAll = new JButton("Restore All");
btnRestoreAll.setMnemonic('R');
btnRestoreAll.setEnabled(connected);
btnRestoreAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (running) {
JOptionPane.showMessageDialog(frmBackBox, "Transactions running", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (connected) {
final JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = fc.showOpenDialog(frmBackBox);
if (returnVal == JFileChooser.APPROVE_OPTION) {
helper.tm.clear();
loadingDialog.showLoading();
Thread worker = new Thread() {
public void run() {
List<Transaction> tt = null;
try {
tt = helper.restoreAll(fc.getSelectedFile().getCanonicalPath());
} catch (Exception e) {
loadingDialog.hideLoading();
GuiUtility.handleException(frmBackBox, "Error building restore transactions", e);
} finally {
clearPreviewTable();
updatePreviewTable(tt);
if ((tt == null) || tt.isEmpty()) {
loadingDialog.hideLoading();
JOptionPane.showMessageDialog(frmBackBox, "No files to restore", "Info", JOptionPane.INFORMATION_MESSAGE);
} else {
pending = true;
pendingDone = false;
}
updateStatus();
}
loadingDialog.hideLoading();
}
};
worker.start();
}
} else
JOptionPane.showMessageDialog(frmBackBox, "Not connected", "Error", JOptionPane.ERROR_MESSAGE);
}
});
pnlOp.add(btnRestoreAll, "cell 2 0,grow");
JLabel lblFreeSpace = new JLabel("Free Space:");
pnlOp.add(lblFreeSpace, "cell 5 0,alignx right,growy");
lblFreeSpaceValue = new JLabel("");
pnlOp.add(lblFreeSpaceValue, "cell 6 0,alignx left,growy");
lblStatus = new JLabel("");
pnlOp.add(lblStatus, "cell 7 0 2 1,alignx right");
JScrollPane scrollPanePreview = new JScrollPane();
pnlOp.add(scrollPanePreview, "cell 0 1 9 1,grow");
tablePreview = new JTable();
tablePreview.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
tablePreview.setModel(new PreviewTableModel());
TableColumnModel columnModel = tablePreview.getColumnModel();
columnModel.getColumn(0).setPreferredWidth(300);
columnModel.getColumn(0).setMinWidth(300);
columnModel.getColumn(1).setPreferredWidth(100);
columnModel.getColumn(1).setMinWidth(50);
columnModel.getColumn(2).setPreferredWidth(100);
columnModel.getColumn(2).setMaxWidth(100);
columnModel.getColumn(3).setPreferredWidth(100);
columnModel.getColumn(3).setMaxWidth(100);
columnModel.removeColumn(columnModel.getColumn(4));
columnModel.removeColumn(columnModel.getColumn(4));
tablePreview.setRowSorter(new FileBrowserTableRowSorter(tablePreview.getModel()));
tablePreview.setDefaultRenderer(String.class, new PreviewTableCellRenderer());
tablePreview.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2)
showDetails();
}
});
tablePreview.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DELETE)
deleteTransactions();
}
});
scrollPanePreview.setViewportView(tablePreview);
scrollPanePreview.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPanePreview.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPanePreview.setViewportBorder(null);
final JPopupMenu popupPreviewMenu = new JPopupMenu();
GuiUtility.addPopup(tablePreview, popupPreviewMenu);
JMenuItem mntmDetails = new JMenuItem("Details");
mntmDetails.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
showDetails();
}
});
JMenuItem mntmDelete = new JMenuItem("Delete");
mntmDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
deleteTransactions();
}
});
popupPreviewMenu.add(mntmDetails);
popupPreviewMenu.add(mntmDelete);
spnCurrentUploadSpeed = new JSpinner();
spnCurrentUploadSpeed.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
pm.setSpeed(ProgressManager.UPLOAD_ID, ((int) spnCurrentUploadSpeed.getValue()) * 1024);
pm.setSpeed(ProgressManager.DOWNLOAD_ID, ((int) spnCurrentUploadSpeed.getValue()) * 1024);
}
});
btnStart = new JButton("Start");
btnStop = new JButton("Stop");
btnClear = new JButton("Clear");
btnClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
pending = false;
pendingDone = false;
helper.tm.clear();
clearPreviewTable();
updateStatus();
}
});
btnClear.setEnabled(false);
pnlOp.add(btnClear, "cell 2 2,grow");
pnlOp.add(spnCurrentUploadSpeed, "cell 3 2,growx");
JLabel lblKbs = new JLabel("KB\\s");
pnlOp.add(lblKbs, "cell 4 2");
progressBar = new JProgressBar();
progressBar.setStringPainted(true);
pnlOp.add(progressBar, "cell 5 2 2 1,grow");
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
loadingDialog.showLoading();
Thread worker = new Thread() {
public void run() {
try {
helper.tm.stopTransactions();
} catch (Exception e1) {
loadingDialog.hideLoading();
GuiUtility.handleException(frmBackBox, "Error stopping transactions", e1);
} finally {
running = false;
pendingDone = true;
updateStatus();
}
loadingDialog.hideLoading();
}
};
worker.start();
}
});
btnStop.setEnabled(false);
pnlOp.add(btnStop, "cell 1 2,grow");
btnStart.setEnabled(false);
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ProgressListener listener = new ProgressListener() {
long partial = 0;
long subpartial = 0;
long speedSubpartial = 0;
long lastTimestamp = 0;
long averagespeed = 0;
long speeds[] = new long[10];
int i = 0;
@Override
public void update(String id, long bytes) {
subpartial += bytes;
if (pm.getSpeed(id) == 0) {
long timestamp = new Date().getTime();
speedSubpartial += bytes;
long elapsed = timestamp - lastTimestamp;
if (elapsed > 1500) {
long speed = (speedSubpartial * 1000) / elapsed;
speeds[i++] = speed;
lastTimestamp = timestamp;
speedSubpartial = 0;
if (i >= 5) {
i = 0;
averagespeed = 0;
for (long a : speeds)
averagespeed += a;
averagespeed /= speeds.length;
}
}
} else
averagespeed = pm.getSpeed(id);
if (averagespeed > 0) {
partial += subpartial;
subpartial = 0;
long b = helper.tm.getAllTasksWeight() - partial;
lblEtaValue.setText(GuiUtility.getETAString(b, averagespeed));
}
helper.tm.weightCompleted(bytes);
}
};
pm.setListener(ProgressManager.UPLOAD_ID, listener);
pm.setListener(ProgressManager.DOWNLOAD_ID, listener);
helper.tm.runTransactions();
helper.tm.shutdown();
running = true;
updateStatus();
Thread t = new Thread("ProgressBar") {
public void run() {
progressBar.setValue(0);
while (helper.tm.isRunning()) {
if (_log.isLoggable(Level.FINE))
_log.fine("TaskCompleted/AllTask: " + helper.tm.getCompletedTasksWeight() + '/' + helper.tm.getAllTasksWeight());
if (helper.tm.getAllTasksWeight() > 0) {
long perc = (helper.tm.getCompletedTasksWeight() * 100) / helper.tm.getAllTasksWeight();
if (_log.isLoggable(Level.FINE))
_log.fine("Perc: " + perc + "% - " + "Progress: " + progressBar.getValue() + '%');
if ((perc > progressBar.getValue()) && (perc <= 99))
progressBar.setValue((int)perc);
}
try { Thread.sleep(1000); } catch (InterruptedException e) {}
}
running = false;
pendingDone = true;
progressBar.setValue(100);
updateFileBrowser();
List<Transaction> result = helper.tm.getResult();
if (result != null) {
boolean error = false;
for (Transaction t : result) {
updateTableResult(t);
if (t.getResultCode() < 0)
error = true;
}
if (error)
JOptionPane.showMessageDialog(frmBackBox, "Operation completed with errors", "BackBox", JOptionPane.ERROR_MESSAGE);
else
JOptionPane.showMessageDialog(frmBackBox, "Operation completed", "BackBox", JOptionPane.INFORMATION_MESSAGE);
} else
JOptionPane.showMessageDialog(frmBackBox, "Transactions still in progress", "Error", JOptionPane.ERROR_MESSAGE);
updateStatus();
}
};
t.start();
}
});
pnlOp.add(btnStart, "cell 0 2,grow");
JLabel lblEta = new JLabel("ETA:");
pnlOp.add(lblEta, "cell 7 2,alignx right");
lblEtaValue = new JLabel("");
pnlOp.add(lblEtaValue, "cell 8 2");
return pnlOp;
}
private Component initializeFileBrowser() {
GuiUtility.checkEDT(true);
table = new JTable();
table.setShowGrid(false);
table.setFillsViewportHeight(true);
table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
table.setModel(new FileBrowserTableModel());
TableColumnModel columnModel = table.getColumnModel();
columnModel.getColumn(0).setMinWidth(20);
columnModel.getColumn(0).setMaxWidth(20);
columnModel.getColumn(0).setResizable(false);
columnModel.getColumn(1).setPreferredWidth(200);
columnModel.getColumn(1).setMinWidth(200);
columnModel.getColumn(2).setPreferredWidth(50);
columnModel.getColumn(2).setMinWidth(50);
columnModel.getColumn(3).setPreferredWidth(100);
columnModel.getColumn(3).setMinWidth(100);
columnModel.getColumn(4).setPreferredWidth(100);
columnModel.getColumn(4).setMinWidth(100);
table.removeColumn(columnModel.getColumn(5));
table.removeColumn(columnModel.getColumn(5));
FileBrowserTableRowSorter sorter = new FileBrowserTableRowSorter(table.getModel());
table.setRowSorter(sorter);
List<RowSorter.SortKey> sortKeys = new ArrayList<RowSorter.SortKey>();
sortKeys.add(new RowSorter.SortKey(1, SortOrder.ASCENDING));
sorter.setSortKeys(sortKeys);
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int row = table.rowAtPoint(e.getPoint());
row = table.convertRowIndexToModel(row);
FileBrowserTableModel tableModel = (FileBrowserTableModel) table.getModel();
FileBrowserTreeNode node = tableModel.getNode(row);
if (node.getType() == TreeNodeType.FOLDER) {
TreePath path = new TreePath(node.getPath());
tree.setSelectionPath(path);
tree.scrollPathToVisible(path);
} else if (node.getType() == TreeNodeType.PREV_FOLDER) {
node = (FileBrowserTreeNode) node.getParent();
TreePath path = new TreePath(node.getPath());
tree.setSelectionPath(path);
tree.scrollPathToVisible(path);
} else if (node.getType() == TreeNodeType.FILE) {
addDownload();
}
}
}
});
JScrollPane scpTable = new JScrollPane(table);
scpTable.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scpTable.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scpTable.setViewportBorder(null);
tree = new JTree(new FileBrowserTreeModel(new FileBrowserTreeNode(TreeNodeType.FOLDER)));
tree.setRootVisible(false);
tree.setShowsRootHandles(true);
tree.addTreeSelectionListener(new FileBrowserTreeSelectionListener(frmBackBox, helper, table));
tree.setCellRenderer(new FileBrowserTreeCellRenderer());
JScrollPane treeScroll = new JScrollPane(tree);
Dimension preferredSize = treeScroll.getPreferredSize();
Dimension widePreferred = new Dimension(200, (int) preferredSize.getHeight());
treeScroll.setPreferredSize(widePreferred);
JSplitPane splitPane = new JSplitPane(
JSplitPane.HORIZONTAL_SPLIT,
treeScroll,
scpTable);
final JPopupMenu popupMenu = new JPopupMenu();
GuiUtility.addPopup(table, popupMenu);
JMenuItem mntmDownload = new JMenuItem("Download");
mntmDownload.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addDownload();
}
});
JMenuItem mntmDelete = new JMenuItem("Delete");
mntmDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (running) {
JOptionPane.showMessageDialog(frmBackBox, "Transactions running", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
loadingDialog.showLoading();
Thread worker = new Thread() {
public void run() {
List<Transaction> tt = new ArrayList<Transaction>();
try {
List<it.backbox.bean.File> fs = getSelectedFiles();
for (it.backbox.bean.File f : fs)
tt.add(helper.delete(f.getFolderAlias(), f.getFilename(), f.getHash(), false));
} catch (Exception e1) {
loadingDialog.hideLoading();
GuiUtility.handleException(frmBackBox, "Error building download transactions", e1);
} finally {
updatePreviewTable(tt);
pending = ((tt != null) && !tt.isEmpty());
pendingDone = false;
updateStatus();
}
loadingDialog.hideLoading();
}
};
worker.start();
}
});
popupMenu.add(mntmDownload);
popupMenu.add(mntmDelete);
return splitPane;
}
private void initializeMenu() {
GuiUtility.checkEDT(true);
JMenuBar menuBar = new JMenuBar();
frmBackBox.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
mnFile.setMnemonic('F');
menuBar.add(mnFile);
mntmNewConfiguration = new JMenuItem("New configuration...");
mntmNewConfiguration.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!running) {
if (helper.confExists()) {
int s = JOptionPane.showConfirmDialog(frmBackBox, "Are you sure? This will overwrite current configuration.", "New configuration", JOptionPane.YES_NO_OPTION);
if (s != JOptionPane.OK_OPTION)
return;
}
newConfDialog.setLocationRelativeTo(frmBackBox);
newConfDialog.setVisible(true);
} else
JOptionPane.showMessageDialog(frmBackBox, "Transactions running", "Error", JOptionPane.ERROR_MESSAGE);
}
});
mntmNewConfiguration.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));
mnFile.add(mntmNewConfiguration);
mntmBuildDatabase = new JMenuItem("Build database...");
mnFile.add(mntmBuildDatabase);
mntmBuildDatabase.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (running) {
JOptionPane.showMessageDialog(frmBackBox, "Transactions running", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
int s = JOptionPane.showConfirmDialog(frmBackBox, "Are you sure? This will overwrite local database.", "Build database", JOptionPane.YES_NO_OPTION);
if (s != JOptionPane.OK_OPTION)
return;
pwdDialog.setLocationRelativeTo(frmBackBox);
pwdDialog.load(GuiConstant.BUILDDB_MODE);
pwdDialog.setVisible(true);
}
});
JSeparator separator = new JSeparator();
mnFile.add(separator);
mntmBackup = new JMenu("Backup");
mntmBackup.setEnabled(false);
mnFile.add(mntmBackup);
mntmRestore = new JMenu("Restore");
mntmRestore.setEnabled(false);
mnFile.add(mntmRestore);
JSeparator separator2 = new JSeparator();
mnFile.add(separator2);
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
loadingDialog.showLoading();
exitThread.start();
}
});
mntmUploadDb = new JMenuItem("Upload configuration");
mntmUploadDb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (running) {
JOptionPane.showMessageDialog(frmBackBox, "Transactions running", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
loadingDialog.showLoading();
Thread worker = new Thread() {
public void run() {
try {
helper.uploadConf(true);
disconnect(true);
JOptionPane.showMessageDialog(frmBackBox, "Configuration uploaded successfully", "Upload configuration", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e1) {
loadingDialog.hideLoading();
GuiUtility.handleException(frmBackBox, "Error uploading configuration", e1);
}
loadingDialog.hideLoading();
}
};
worker.start();
}
});
mntmUploadDb.setEnabled(connected);
mnFile.add(mntmUploadDb);
mntmDownloadDb = new JMenuItem("Download configuration");
mntmDownloadDb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (running) {
JOptionPane.showMessageDialog(frmBackBox, "Transactions running", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
int s = JOptionPane.showConfirmDialog(frmBackBox, "Are you sure? This will overwrite local configuration.", "Download configuration", JOptionPane.YES_NO_OPTION);
if (s != JOptionPane.OK_OPTION)
return;
loadingDialog.showLoading();
Thread worker = new Thread() {
public void run() {
try {
helper.downloadConf();
disconnect(true);
JOptionPane.showMessageDialog(frmBackBox, "Configuration downloaded successfully", "Download configuration", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e1) {
loadingDialog.hideLoading();
GuiUtility.handleException(frmBackBox, "Error downloading configuration", e1);
}
loadingDialog.hideLoading();
}
};
worker.start();
}
});
mntmDownloadDb.setEnabled(connected);
mnFile.add(mntmDownloadDb);
JSeparator separator3 = new JSeparator();
mnFile.add(separator3);
mntmExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.ALT_MASK));
mnFile.add(mntmExit);
JMenu mnEdit = new JMenu("Edit");
menuBar.add(mnEdit);
mntmConfiguration = new JMenuItem("Configuration...");
mntmConfiguration.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (running) {
JOptionPane.showMessageDialog(frmBackBox, "Transactions running", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (connected) {
try {
configurationDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
configurationDialog.setLocationRelativeTo(frmBackBox);
configurationDialog.load(helper.getConfiguration().getBackupFolders());
configurationDialog.setVisible(true);
} catch (Exception e1) {
GuiUtility.handleException(frmBackBox, "Error loading configuration", e1);
}
} else
JOptionPane.showMessageDialog(frmBackBox, "Not connected", "Error", JOptionPane.ERROR_MESSAGE);
}
});
mntmCheck = new JMenuItem("Check database");
mntmCheck.setEnabled(false);
mntmCheck.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (running) {
JOptionPane.showMessageDialog(frmBackBox, "Transactions running", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (!connected) {
JOptionPane.showMessageDialog(frmBackBox, "Not connected", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
loadingDialog.showLoading();
progressBar.setValue(0);
SwingWorker<Void, Integer> worker = new SwingWorker<Void, Integer>() {
List<Transaction> tt = new ArrayList<>();
@Override
protected Void doInBackground() throws Exception {
int size = 0;
List<it.backbox.bean.File> files = helper.dbm.getAllFiles();
Map<String, Chunk> allChunks = new HashMap<>();
for (it.backbox.bean.File f : files) {
for (Chunk c : f.getChunks()) {
size++;
allChunks.put(c.getBoxid(), c);
}
}
progressBar.setMaximum(size * 2);
for (it.backbox.bean.File f : files) {
if (!helper.existsRemotely(f)) {
Transaction t = new Transaction(f.getHash());
DeleteDBTask dt = new DeleteDBTask(f);
dt.setDescription(f.getFolderAlias() + "\\" + f.getFilename());
t.addTask(dt);
tt.add(t);
helper.tm.addTransaction(t);
}
publish(f.getChunks().size());
}
List<Folder> folders = helper.getConfiguration().getBackupFolders();
for (Folder f : folders) {
Map<String, List<Chunk>> remoteInfo = helper.bm.getFolderChunks(f.getId());
for (List<Chunk> cc : remoteInfo.values()) {
for (Chunk c : cc) {
if (!allChunks.containsKey(c.getBoxid())) {
Transaction t = new Transaction(c.getChunkhash());
DeleteRemoteTask dt = new DeleteRemoteTask(c);
dt.setDescription(f.getAlias() + "\\" + c.getChunkname());
t.addTask(dt);
tt.add(t);
helper.tm.addTransaction(t);
}
publish(1);
}
}
}
return null;
}
@Override
protected void process(List<Integer> ints) {
for (Integer i : ints)
progressBar.setValue(progressBar.getValue() + i);
}
@Override
protected void done() {
pending = false;
pendingDone = true;
progressBar.setValue(100);
clearPreviewTable();
updatePreviewTable(tt);
if ((tt == null) || tt.isEmpty()) {
loadingDialog.hideLoading();
JOptionPane.showMessageDialog(frmBackBox, "That's all right!", "Info", JOptionPane.INFORMATION_MESSAGE);
} else {
pending = true;
pendingDone = false;
}
updateStatus();
loadingDialog.hideLoading();
}
};
worker.execute();
}
});
mnEdit.add(mntmCheck);
mnEdit.add(mntmConfiguration);
JMenuItem mntmPreferences = new JMenuItem("Preferences...");
mntmPreferences.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
preferencesDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
preferencesDialog.setLocationRelativeTo(frmBackBox);
preferencesDialog.load(helper.getConfiguration().getDefaultUploadSpeed(),
helper.getConfiguration().getDefaultDownloadSpeed(),
helper.getConfiguration().getProxyConfiguration(),
!running,
helper.getConfiguration().isAutoUploadConf());
preferencesDialog.setVisible(true);
} catch (Exception e1) {
GuiUtility.handleException(frmBackBox, "Error loading configuration", e1);
}
}
});
JSeparator separator_2 = new JSeparator();
mnEdit.add(separator_2);
mnEdit.add(mntmPreferences);
}
private void showDetails() {
GuiUtility.checkEDT(true);
loadingDialog.showLoading();
Thread worker = new Thread() {
public void run() {
detailsDialog.load(tablePreview);
detailsDialog.setLocationRelativeTo(frmBackBox);
detailsDialog.setVisible(true);
loadingDialog.hideLoading();
}
};
worker.start();
}
private void listAllFiles(FileBrowserTreeNode node, List<it.backbox.bean.File> list) {
GuiUtility.checkEDT(false);
Enumeration<FileBrowserTreeNode> e = node.children();
while (e.hasMoreElements()) {
FileBrowserTreeNode cnode = e.nextElement();
if (cnode.getType() == TreeNodeType.PREV_FOLDER)
return;
Object obj = cnode.getUserObject();
if (obj instanceof String)
listAllFiles(cnode, list);
else if (obj instanceof it.backbox.bean.File) {
list.add((it.backbox.bean.File) obj);
if (_log.isLoggable(Level.FINE)) {
FileBrowserTreeNode c = (FileBrowserTreeNode) cnode.getParent();
StringBuilder sb = new StringBuilder("Selected files: \n");
while (!c.isRoot()) {
sb.insert(0, c.getUserObject() + "->");
c = (FileBrowserTreeNode) c.getParent();
}
_log.fine(sb.toString());
}
}
}
}
private List<it.backbox.bean.File> getSelectedFiles() {
GuiUtility.checkEDT(false);
int[] selectedRows = table.getSelectedRows();
FileBrowserTableModel model = (FileBrowserTableModel) table.getModel();
List<it.backbox.bean.File> res = new ArrayList<>();
for (int i : selectedRows) {
int row = table.convertRowIndexToModel(i);
FileBrowserTreeNode node = model.getNode(row);
if (node.getType() == TreeNodeType.FOLDER) {
List<it.backbox.bean.File> list = new ArrayList<>();
listAllFiles(node, list);
res.addAll(list);
} else if (node.getType() == TreeNodeType.FILE)
res.add((it.backbox.bean.File) node.getUserObject());
}
return res;
}
private void addDownload() {
if (running) {
JOptionPane.showMessageDialog(frmBackBox, "Transactions running", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
final JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fc.showSaveDialog(frmBackBox) == JFileChooser.APPROVE_OPTION) {
loadingDialog.showLoading();
Thread worker = new Thread() {
public void run() {
final List<Transaction> tt = new ArrayList<Transaction>();
try {
List<it.backbox.bean.File> fs = getSelectedFiles();
for (it.backbox.bean.File f : fs)
tt.add(helper.downloadFile(f.getFolderAlias(), f.getFilename(), f.getHash(), fc.getSelectedFile().getCanonicalPath(), false));
} catch (final Exception e1) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
loadingDialog.hideLoading();
GuiUtility.handleException(frmBackBox, "Error building download transactions", e1);
}
});
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
updatePreviewTable(tt);
pending = ((tt != null) && !tt.isEmpty());
pendingDone = false;
updateStatus();
loadingDialog.hideLoading();
}
});
}
};
worker.start();
}
}
private void deleteTransactions() {
int[] ss = tablePreview.getSelectedRows();
PreviewTableModel model = (PreviewTableModel) tablePreview.getModel();
List<Transaction> tToDel = new ArrayList<>();
for (int s : ss) {
s = tablePreview.convertRowIndexToModel(s);
tToDel.add((Transaction) model.getValueAt(s, PreviewTableModel.TRANSACTION_COLUMN_INDEX));
}
for (Transaction tt : tToDel) {
if (!helper.tm.removeTransaction(tt))
continue;
for (Task t : tt.getTasks()) {
for (int i = 0; i < model.getRowCount(); i++) {
Task tm = (Task) model.getValueAt(i, PreviewTableModel.TASK_COLUMN_INDEX);
if (tm.getId().equals(t.getId()))
model.removeRow(i);
}
}
}
}
}
|
package io.branch.referral;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.util.SparseArray;
import android.view.ActionMode;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/**
* <p>
* The core object required when using Branch SDK. You should declare an object of this type at
* the class-level of each Activity or Fragment that you wish to use Branch functionality within.
* </p>
*
* <p>
* Normal instantiation of this object would look like this:
* </p>
*
* <pre style="background:#fff;padding:10px;border:2px solid silver;">
* Branch.getInstance(this.getApplicationContext()) // from an Activity
*
* Branch.getInstance(getActivity().getApplicationContext()) // from a Fragment
* </pre>
*
*/
public class Branch {
private static final String TAG = "BranchSDK";
/**
* Hard-coded {@link String} that denotes a {@link BranchLinkData#tags}; applies to links that
* are shared with others directly as a user action, via social media for instance.
*/
public static final String FEATURE_TAG_SHARE = "share";
/**
* Hard-coded {@link String} that denotes a 'referral' tag; applies to links that are associated
* with a referral program, incentivized or not.
*/
public static final String FEATURE_TAG_REFERRAL = "referral";
/**
* Hard-coded {@link String} that denotes a 'referral' tag; applies to links that are sent as
* referral actions by users of an app using an 'invite contacts' feature for instance.
*/
public static final String FEATURE_TAG_INVITE = "invite";
/**
* Hard-coded {@link String} that denotes a link that is part of a commercial 'deal' or offer.
*/
public static final String FEATURE_TAG_DEAL = "deal";
/**
* Hard-coded {@link String} that denotes a link tagged as a gift action within a service or
* product.
*/
public static final String FEATURE_TAG_GIFT = "gift";
/**
* The code to be passed as part of a deal or gift; retrieved from the Branch object as a
* tag upon initialisation. Of {@link String} format.
*/
public static final String REDEEM_CODE = "$redeem_code";
/**
* <p>Default value of referral bucket; referral buckets contain credits that are used when users
* are referred to your apps. These can be viewed in the Branch dashboard under Referrals.</p>
*/
public static final String REFERRAL_BUCKET_DEFAULT = "default";
/**
* <p>Hard-coded value for referral code type. Referral codes will always result on "credit" actions.
* Even if they are of 0 value.</p>
*/
public static final String REFERRAL_CODE_TYPE = "credit";
/**
* Branch SDK version for the current release of the Branch SDK.
*/
public static final int REFERRAL_CREATION_SOURCE_SDK = 2;
/**
* Key value for referral code as a parameter.
*/
public static final String REFERRAL_CODE = "referral_code";
/**
* The redirect URL provided when the link is handled by a desktop client.
*/
public static final String REDIRECT_DESKTOP_URL = "$desktop_url";
/**
* The redirect URL provided when the link is handled by an Android device.
*/
public static final String REDIRECT_ANDROID_URL = "$android_url";
/**
* The redirect URL provided when the link is handled by an iOS device.
*/
public static final String REDIRECT_IOS_URL = "$ios_url";
/**
* The redirect URL provided when the link is handled by a large form-factor iOS device such as
* an iPad.
*/
public static final String REDIRECT_IPAD_URL = "$ipad_url";
/**
* The redirect URL provided when the link is handled by an Amazon Fire device.
*/
public static final String REDIRECT_FIRE_URL = "$fire_url";
/**
* The redirect URL provided when the link is handled by a Blackberry device.
*/
public static final String REDIRECT_BLACKBERRY_URL = "$blackberry_url";
/**
* The redirect URL provided when the link is handled by a Windows Phone device.
*/
public static final String REDIRECT_WINDOWS_PHONE_URL = "$windows_phone_url";
public static final String OG_TITLE = "$og_title";
public static final String OG_DESC = "$og_description";
public static final String OG_IMAGE_URL = "$og_image_url";
public static final String OG_VIDEO = "$og_video";
public static final String OG_URL = "$og_url";
/**
* Unique identifier for the app in use.
*/
public static final String OG_APP_ID = "$og_app_id";
/**
* {@link String} value denoting the deep link path to override Branch's default one. By
* default, Branch will use yourapp://open?link_click_id=12345. If you specify this key/value,
* Branch will use yourapp://'$deeplink_path'?link_click_id=12345
*/
public static final String DEEPLINK_PATH = "$deeplink_path";
/**
* {@link String} value indicating whether the link should always initiate a deep link action.
* By default, unless overridden on the dashboard, Branch will only open the app if they are
* 100% sure the app is installed. This setting will cause the link to always open the app.
* Possible values are "true" or "false"
*/
public static final String ALWAYS_DEEPLINK = "$always_deeplink";
/**
* An {@link Integer} value indicating the user to reward for applying a referral code. In this
* case, the user applying the referral code receives credit.
*/
public static final int REFERRAL_CODE_LOCATION_REFERREE = 0;
/**
* An {@link Integer} value indicating the user to reward for applying a referral code. In this
* case, the user who created the referral code receives credit.
*/
public static final int REFERRAL_CODE_LOCATION_REFERRING_USER = 2;
/**
* An {@link Integer} value indicating the user to reward for applying a referral code. In this
* case, both the creator and applicant receive credit
*/
public static final int REFERRAL_CODE_LOCATION_BOTH = 3;
/**
* An {@link Integer} value indicating the calculation type of the referral code. In this case,
* the referral code can be applied continually.
*/
public static final int REFERRAL_CODE_AWARD_UNLIMITED = 1;
/**
* An {@link Integer} value indicating the calculation type of the referral code. In this case,
* a user can only apply a specific referral code once.
*/
public static final int REFERRAL_CODE_AWARD_UNIQUE = 0;
/**
* An {@link Integer} value indicating the link type. In this case, the link can be used an
* unlimited number of times.
*/
public static final int LINK_TYPE_UNLIMITED_USE = 0;
/**
* An {@link Integer} value indicating the link type. In this case, the link can be used only
* once. After initial use, subsequent attempts will not validate.
*/
public static final int LINK_TYPE_ONE_TIME_USE = 1;
private static final int SESSION_KEEPALIVE = 2000;
/**
* <p>An {@link Integer} value defining the timeout period in milliseconds to wait during a
* looping task before triggering an actual connection close during a session close action.</p>
*/
private static final int PREVENT_CLOSE_TIMEOUT = 500;
/**
* <p>A {@link Branch} object that is instantiated on init and holds the singleton instance of
* the class during application runtime.</p>
*/
private static Branch branchReferral_;
private BranchRemoteInterface kRemoteInterface_;
private PrefHelper prefHelper_;
private SystemObserver systemObserver_;
private Context context_;
final Object lock;
private Timer closeTimer;
private Timer rotateCloseTimer;
private boolean keepAlive_;
private Semaphore serverSema_;
private ServerRequestQueue requestQueue_;
private int networkCount_;
private boolean hasNetwork_;
private SparseArray<String> debugListenerInitHistory_;
private OnTouchListener debugOnTouchListener_;
private Handler debugHandler_;
private boolean debugStarted_;
private Map<BranchLinkData, String> linkCache_;
private ScheduledFuture<?> appListingSchedule_;
/* BranchActivityLifeCycleObserver instance. Should be initialised on creating Instance with Application object. */
private BranchActivityLifeCycleObserver activityLifeCycleObserver_;
/* Set to true when application is instantiating {@BranchApp} by extending or adding manifest entry. */
private static boolean isAutoSessionMode_ = false;
/* Set to true when {@link Activity} life cycle callbacks are registered. */
private static boolean isActivityLifeCycleCallbackRegistered_ = false;
/* Enumeration for defining session initialisation state. */
private enum SESSION_STATE {INITIALISED, INITIALISING, UNINITIALISED}
/* Holds the current Session state. Default is set to UNINITIALISED. */
private SESSION_STATE initState_ = SESSION_STATE.UNINITIALISED;
/**
* <p>The main constructor of the Branch class is private because the class uses the Singleton
* pattern.</p>
*
* <p>Use {@link #getInstance(Context) getInstance} method when instantiating.</p>
*
* @param context A {@link Context} from which this call was made.
*/
private Branch(Context context) {
prefHelper_ = PrefHelper.getInstance(context);
kRemoteInterface_ = new BranchRemoteInterface(context);
systemObserver_ = new SystemObserver(context);
requestQueue_ = ServerRequestQueue.getInstance(context);
serverSema_ = new Semaphore(1);
closeTimer = new Timer();
rotateCloseTimer = new Timer();
lock = new Object();
keepAlive_ = false;
networkCount_ = 0;
hasNetwork_ = true;
debugListenerInitHistory_ = new SparseArray<String>();
debugOnTouchListener_ = retrieveOnTouchListener();
debugHandler_ = new Handler();
debugStarted_ = false;
linkCache_ = new HashMap<BranchLinkData, String>();
}
/**
* <p>Singleton method to return the pre-initialised object of the type {@link Branch}.
* Make sure your app is instantiating {@link BranchApp} before calling this method.</p>
*
* @return An initialised singleton {@link Branch} object
*
* @throws BranchException Exception<br>
* 1) If your {@link Application} is not instance of {@link BranchApp}.<br>
* 2) If the minimum API level is below 14.
*/
public static Branch getInstance() throws BranchException {
/* Check if BranchApp is instantiated. */
if (branchReferral_ == null ) {
throw BranchException.getInstantiationException();
}
else if(isAutoSessionMode_ == true){
/* Check if Activity life cycle callbacks are set if in auto session mode. */
if (isActivityLifeCycleCallbackRegistered_ == false) {
throw BranchException.getAPILevelException();
}
}
return branchReferral_;
}
public static Branch getInstance(Context context, String branchKey) {
if (branchReferral_ == null) {
branchReferral_ = Branch.initInstance(context);
}
branchReferral_.context_ = context.getApplicationContext();
if (branchKey.startsWith("key_")) {
branchReferral_.prefHelper_.setBranchKey(branchKey);
} else {
branchReferral_.prefHelper_.setAppKey(branchKey);
}
return branchReferral_;
}
private static Branch getBranchInstance(Context context, boolean isLive) {
if (branchReferral_ == null) {
branchReferral_ = Branch.initInstance(context);
String branchKey = branchReferral_.prefHelper_.readBranchKey(isLive);
if (branchKey == null || branchKey.equalsIgnoreCase(PrefHelper.NO_STRING_VALUE)) {
Log.i("BranchSDK", "Branch Warning: Please enter your branch_key in your project's Manifest file!");
branchReferral_.prefHelper_.setBranchKey(PrefHelper.NO_STRING_VALUE);
} else {
branchReferral_.prefHelper_.setBranchKey(branchKey);
}
}
branchReferral_.context_ = context;
/* If {@link Application} is instantiated register for activity life cycle events. */
if (context instanceof BranchApp) {
isAutoSessionMode_ = true;
branchReferral_.setActivityLifeCycleObserver((Application) context);
}
return branchReferral_;
}
/**
* <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton
* object of the type {@link Branch}.</p>
*
* <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p>
*
* @param context A {@link Context} from which this call was made.
*
* @return An initialised {@link Branch} object, either fetched from a pre-initialised
* instance within the singleton class, or a newly instantiated object where
* one was not already requested during the current app lifecycle.
*/
public static Branch getInstance(Context context) {
return getBranchInstance(context, true);
}
/**
* <p>If you configured the your Strings file according to the guide, you'll be able to use
* the test version of your app by just calling this static method before calling initSession.</p>
*
* @param context A {@link Context} from which this call was made.
*
* @return An initialised {@link Branch} object.
*/
public static Branch getTestInstance(Context context) {
return getBranchInstance(context, false);
}
/**
* <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton
* object of the type {@link Branch}.</p>
*
* <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p>
*
* @param context A {@link Context} from which this call was made.
*
* @return An initialised {@link Branch} object, either fetched from a pre-initialised
* instance within the singleton class, or a newly instantiated object where
* one was not already requested during the current app lifecycle.
*/
public static Branch getAutoInstance(Context context) {
isAutoSessionMode_ = true;
getBranchInstance(context, true);
branchReferral_.setActivityLifeCycleObserver((Application)context);
return branchReferral_;
}
/**
* <p>If you configured the your Strings file according to the guide, you'll be able to use
* the test version of your app by just calling this static method before calling initSession.</p>
*
* @param context A {@link Context} from which this call was made.
*
* @return An initialised {@link Branch} object.
*/
public static Branch getAutoTestInstance(Context context) {
isAutoSessionMode_ = true;
getBranchInstance(context, false);
branchReferral_.setActivityLifeCycleObserver((Application)context);
return branchReferral_;
}
/**
* <p>Initialises an instance of the Branch object.</p>
*
* @param context A {@link Context} from which this call was made.
*
* @return An initialised {@link Branch} object.
*/
private static Branch initInstance(Context context) {
return new Branch(context.getApplicationContext());
}
/**
* <p>Manually sets the {@link Boolean} value, that indicates that the Branch API connection has
* been initialised, to false - forcing re-initialisation.</p>
*/
public void resetUserSession() {
initState_ = SESSION_STATE.UNINITIALISED;
}
/**
* <p>Sets the number of times to re-attempt a timed-out request to the Branch API, before
* considering the request to have failed entirely. Default 5.</p>
*
* @param retryCount An {@link Integer} specifying the number of times to retry before giving
* up and declaring defeat.
*/
public void setRetryCount(int retryCount) {
if (prefHelper_ != null && retryCount > 0) {
prefHelper_.setRetryCount(retryCount);
}
}
/**
* <p>Sets the amount of time in milliseconds to wait before re-attempting a timed-out request
* to the Branch API. Default 3000 ms.</p>
*
* @param retryInterval An {@link Integer} value specifying the number of milliseconds to
* wait before re-attempting a timed-out request.
*/
public void setRetryInterval(int retryInterval) {
if (prefHelper_ != null && retryInterval > 0) {
prefHelper_.setRetryInterval(retryInterval);
}
}
/**
* <p>Sets the duration in milliseconds that the system should wait for a response before considering
* any Branch API call to have timed out. Default 3000 ms.</p>
*
* <p>Increase this to perform better in low network speed situations, but at the expense of
* responsiveness to error situation.</p>
*
* @param timeout An {@link Integer} value specifying the number of milliseconds to wait before
* considering the request to have timed out.
*/
public void setNetworkTimeout(int timeout) {
if (prefHelper_ != null && timeout > 0) {
prefHelper_.setTimeout(timeout);
}
}
/**
* <p>Sets the library to function in debug mode, enabling logging of all requests.</p>
* <p>If you want to flag debug, call this <b>before</b> initUserSession</p>
*/
public void setDebug() {
prefHelper_.setExternDebug();
}
/**
* <p>Calls the {@link PrefHelper#disableExternAppListing()} on the local instance to prevent
* a list of installed apps from being returned to the Branch API.</p>
*/
public void disableAppList() {
prefHelper_.disableExternAppListing();
}
/**
* <p>Calls the {@link PrefHelper#disableTouchDebugging()} ()} on the local instance to prevent
* touch debugging feature.</p>
*/
public void disableTouchDebugging() {
prefHelper_.disableTouchDebugging();
}
/**
* <p>If there's further Branch API call happening within the two seconds, we then don't close
* the session; otherwise, we close the session after two seconds.</p>
*
* <p>Call this method if you don't want this smart session feature and would rather manage
* the session yourself.</p>
*
* <p><b>Note:</b> smart session - we keep session alive for two seconds</p>
*/
public void disableSmartSession() {
prefHelper_.disableSmartSession();
}
/**
* <p>Initialises a session with the Branch API, assigning a {@link BranchReferralInitListener}
* to perform an action upon successful initialisation.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called following
* successful (or unsuccessful) initialisation of the session with the Branch API.
*
* @return A {@link Boolean} value, indicating <i>false</i> if initialisation is
* unsuccessful.
*/
public boolean initSession(BranchReferralInitListener callback) {
initSession(callback, (Activity) null);
return false;
}
/**
* <p>Initialises a session with the Branch API, passing the {@link Activity} and assigning a
* {@link BranchReferralInitListener} to perform an action upon successful initialisation.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
*
* @param activity The calling {@link Activity} for context.
*
* @return A {@link Boolean} value, indicating <i>false</i> if initialisation is
* unsuccessful.
*/
public boolean initSession(BranchReferralInitListener callback, Activity activity) {
if (systemObserver_.getUpdateState(false) == 0 && !hasUser()) {
prefHelper_.setIsReferrable();
} else {
prefHelper_.clearIsReferrable();
}
initUserSessionInternal(callback, activity);
return false;
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
*
* @param data A {@link Uri} variable containing the details of the source link that
* led to this initialisation action.
*
* @return A {@link Boolean} value that will return <i>false</i> if the supplied
* <i>data</i> parameter cannot be handled successfully - i.e. is not of a
* valid URI format.
*/
public boolean initSession(BranchReferralInitListener callback, Uri data) {
return initSession(callback, data, null);
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
*
* @param data A {@link Uri} variable containing the details of the source link that
* led to this initialisation action.
*
* @param activity The calling {@link Activity} for context.
*
* @return A {@link Boolean} value that will return <i>false</i> if the supplied
* <i>data</i> parameter cannot be handled successfully - i.e. is not of a
* valid URI format.
*/
public boolean initSession(BranchReferralInitListener callback, Uri data, Activity activity) {
boolean uriHandled = readAndStripParam(data, activity);
initSession(callback, activity);
return uriHandled;
}
/**
* <p>Initialises a session with the Branch API, without a callback or {@link Activity}.</p>
*
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession() {
return initSession((Activity) null);
}
/**
* <p>Initialises a session with the Branch API, without a callback or {@link Activity}.</p>
*
* @param activity The calling {@link Activity} for context.
*
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(Activity activity) {
return initSession(null, activity);
}
/**
* <p>Initialises a session with the Branch API, with associated data from the supplied
* {@link Uri}.</p>
*
* @param data A {@link Uri} variable containing the details of the source link that
* led to this
* initialisation action.
*
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSessionWithData(Uri data) {
return initSessionWithData(data, null);
}
/**
* <p>Initialises a session with the Branch API, with associated data from the supplied
* {@link Uri}.</p>
*
* @param data A {@link Uri} variable containing the details of the source link that led to this
* initialisation action.
*
* @param activity The calling {@link Activity} for context.
*
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSessionWithData(Uri data, Activity activity) {
boolean uriHandled = readAndStripParam(data, activity);
initSession(null, activity);
return uriHandled;
}
/**
* <p>Initialises a session with the Branch API, specifying whether the initialisation can count
* as a referrable action.</p>
*
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
*
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(boolean isReferrable) {
return initSession(null, isReferrable, (Activity)null);
}
/**
* <p>Initialises a session with the Branch API, specifying whether the initialisation can count
* as a referrable action, and supplying the calling {@link Activity} for context.</p>
*
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
*
* @param activity The calling {@link Activity} for context.
*
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(boolean isReferrable, Activity activity) {
return initSession(null, isReferrable, activity);
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
*
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
*
* @param data A {@link Uri} variable containing the details of the source link that
* led to this initialisation action.
*
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, Uri data) {
return initSession(callback, isReferrable, data, null);
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
*
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
*
* @param data A {@link Uri} variable containing the details of the source link that
* led to this initialisation action.
*
* @param activity The calling {@link Activity} for context.
*
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, Uri data, Activity activity) {
boolean uriHandled = readAndStripParam(data, activity);
initSession(callback, isReferrable, activity);
return uriHandled;
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
*
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
*
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(BranchReferralInitListener callback, boolean isReferrable) {
return initSession(callback, isReferrable, (Activity)null);
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, Activity activity) {
if (isReferrable) {
this.prefHelper_.setIsReferrable();
} else {
this.prefHelper_.clearIsReferrable();
}
initUserSessionInternal(callback, activity);
return false;
}
private void initUserSessionInternal(BranchReferralInitListener callback, Activity activity) {
//If already initialised
if (hasUser() && hasSession() && initState_ == SESSION_STATE.INITIALISED) {
if (callback != null)
callback.onInitFinished(new JSONObject(), null);
clearCloseTimer();
keepAlive();
}
//If uninitialised or initialising
else {
//If initialising ,then set new callbacks.
if (initState_ == SESSION_STATE.INITIALISING) {
requestQueue_.setInstallOrOpenCallback(callback);
}
//if Uninitialised move request to the front if there is an existing request or create a new request.
else {
initState_ = SESSION_STATE.INITIALISING;
initializeSession(callback);
}
}
if (prefHelper_.getTouchDebugging()) {
if (activity != null && debugListenerInitHistory_.get(System.identityHashCode(activity)) == null) {
debugListenerInitHistory_.put(System.identityHashCode(activity), "init");
View view = activity.getWindow().getDecorView().findViewById(android.R.id.content);
if (view != null) {
view.setOnTouchListener(debugOnTouchListener_);
}
}
}
}
/**
* <p>Set the current activity window for the debug touch events. Only for internal usage.</p>
*
* @param activity The current activity.
*/
private void setTouchDebugInternal(Activity activity){
if (activity != null && debugListenerInitHistory_.get(System.identityHashCode(activity)) == null) {
debugListenerInitHistory_.put(System.identityHashCode(activity), "init");
activity.getWindow().setCallback(new BranchWindowCallback(activity.getWindow().getCallback()));
}
}
private void clearTouchDebugInternal(Activity activity) {
if (activity.getWindow().getCallback() instanceof BranchWindowCallback) {
Window.Callback originalCallback =
((BranchWindowCallback) activity.getWindow().getCallback()).callback_;
activity.getWindow().setCallback(originalCallback);
debugListenerInitHistory_.remove(System.identityHashCode(activity));
}
}
private OnTouchListener retrieveOnTouchListener() {
if (debugOnTouchListener_ == null) {
debugOnTouchListener_ = new OnTouchListener() {
class KeepDebugConnectionTask extends TimerTask {
public void run() {
if (!prefHelper_.keepDebugConnection()) {
debugHandler_.post(_longPressed);
}
}
}
Runnable _longPressed = new Runnable() {
private boolean started = false;
private Timer timer;
public void run() {
debugHandler_.removeCallbacks(_longPressed);
if (!started) {
Log.i("Branch Debug","======= Start Debug Session =======");
prefHelper_.setDebug();
timer = new Timer();
timer.scheduleAtFixedRate(new KeepDebugConnectionTask(), new Date(), 20000);
} else {
Log.i("Branch Debug","======= End Debug Session =======");
prefHelper_.clearDebug();
timer.cancel();
timer = null;
}
this.started = !this.started;
}
};
@Override
public boolean onTouch(View v, MotionEvent ev) {
int pointerCount = ev.getPointerCount();
final int actionPerformed = ev.getAction();
switch (actionPerformed & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
if (systemObserver_.isSimulator()) {
debugHandler_.postDelayed(_longPressed, PrefHelper.DEBUG_TRIGGER_PRESS_TIME);
}
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_CANCEL:
debugHandler_.removeCallbacks(_longPressed);
break;
case MotionEvent.ACTION_UP:
v.performClick();
debugHandler_.removeCallbacks(_longPressed);
break;
case MotionEvent.ACTION_POINTER_DOWN:
if (pointerCount == PrefHelper.DEBUG_TRIGGER_NUM_FINGERS) {
debugHandler_.postDelayed(_longPressed, PrefHelper.DEBUG_TRIGGER_PRESS_TIME);
}
break;
}
return true;
}
};
}
return debugOnTouchListener_;
}
/**
* <p>Closes the current session, dependent on the state of the
* {@link PrefHelper#getSmartSession()} {@link Boolean} value. If <i>true</i>, take no action.
* If false, close the sesion via the {@link #executeClose()} method.</p>
* <p>Note that if smartSession is enabled, closeSession cannot be called within
* a 2 second time span of another Branch action. This has to do with the method that
* Branch uses to keep a session alive during Activity transitions</p>
*/
public void closeSession() {
if (isAutoSessionMode_) {
/*
* Ignore any session close request from user if session is managed
* automatically.This is handle situation of closeSession() in
* closed by developer by error while running in auto session mode.
*/
return;
}
if (prefHelper_.getSmartSession()) {
if (keepAlive_) {
return;
}
// else, real close
synchronized(lock) {
clearCloseTimer();
rotateCloseTimer.schedule(new TimerTask() {
@Override
public void run() {
executeClose();
}
}, PREVENT_CLOSE_TIMEOUT);
}
} else {
executeClose();
}
if (prefHelper_.getExternAppListing()) {
if (appListingSchedule_ == null) {
scheduleListOfApps();
}
}
}
/*
* <p>Closes the current session. Should be called by on getting the last actvity onStop() event.
* </p>
*/
private void closeSessionInternal(){
executeClose();
if (prefHelper_.getExternAppListing()) {
if (appListingSchedule_ == null) {
scheduleListOfApps();
}
}
}
/**
* <p>Perform the state-safe actions required to terminate any open session, and report the
* closed application event to the Branch API.</p>
*/
private void executeClose() {
if (initState_ != SESSION_STATE.UNINITIALISED) {
if (!hasNetwork_) {
// if there's no network connectivity, purge the old install/open
ServerRequest req = requestQueue_.peek();
if (req != null && (req instanceof ServerRequestRegisterInstall) || (req instanceof ServerRequestRegisterOpen)) {
requestQueue_.dequeue();
}
} else {
if (!requestQueue_.containsClose()) {
ServerRequest req = new ServerRequestRegisterClose(context_);
handleNewRequest(req);
}
}
initState_ = SESSION_STATE.UNINITIALISED;
}
}
private boolean readAndStripParam(Uri data, Activity activity) {
if (data != null && data.isHierarchical()) {
if (data.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey()) != null) {
prefHelper_.setLinkClickIdentifier(data.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey()));
String paramString = "link_click_id=" + data.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey());
String uriString = activity.getIntent().getDataString();
if (data.getQuery().length() == paramString.length()) {
paramString = "\\?" + paramString;
} else if ((uriString.length()-paramString.length()) == uriString.indexOf(paramString)) {
paramString = "&" + paramString;
} else {
paramString = paramString + "&";
}
Uri newData = Uri.parse(uriString.replaceFirst(paramString, ""));
activity.getIntent().setData(newData);
return true;
}
}
return false;
}
/**
* <p>Identifies the current user to the Branch API by supplying a unique identifier as a
* {@link String} value. No callback.</p>
*
* @param userId A {@link String} value containing the unique identifier of the user.
*/
public void setIdentity(String userId) {
setIdentity(userId, null);
}
/**
* <p>Identifies the current user to the Branch API by supplying a unique identifier as a
* {@link String} value, with a callback specified to perform a defined action upon successful
* response to request.</p>
*
* @param userId A {@link String} value containing the unique identifier of the user.
* @param callback A {@link BranchReferralInitListener} callback instance that will return
* the data associated with the user id being assigned, if available.
*/
public void setIdentity(String userId, BranchReferralInitListener callback) {
ServerRequest req = new ServerRequestIdentifyUserRequest(context_, callback, userId);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
} else {
if (((ServerRequestIdentifyUserRequest) req).isExistingID()) {
((ServerRequestIdentifyUserRequest) req).handleUserExist(branchReferral_);
}
}
}
/**
* Indicates whether or not this user has a custom identity specified for them. Note that this is independent of installs.
* If you call setIdentity, this device will have that identity associated with this user until logout is called.
* This includes persisting through uninstalls, as we track device id.
*
* @return A {@link Boolean} value that will return <i>true</i> only if user already has an identity.
*
*/
public boolean isUserIdentified() {
return !prefHelper_.getIdentity().equals(PrefHelper.NO_STRING_VALUE);
}
/**
* <p>This method should be called if you know that a different person is about to use the app. For example,
* if you allow users to log out and let their friend use the app, you should call this to notify Branch
* to create a new user for this device. This will clear the first and latest params, as a new session is created.</p>
*/
public void logout() {
ServerRequest req = new ServerRequestLogout(context_);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>Fire-and-forget retrieval of action count for the current session. Without a callback.</p>
*/
public void loadActionCounts() {
loadActionCounts(null);
}
/**
* <p>Gets the total action count, with a callback to perform a predefined
* action following successful report of state change. You'll then need to
* call getUniqueActions or getTotalActions in the callback to update the
* totals in your UX.</p>
*
* @param callback A {@link BranchReferralStateChangedListener} callback instance that will
* trigger actions defined therein upon a referral state change.
*/
public void loadActionCounts(BranchReferralStateChangedListener callback) {
ServerRequest req = new ServerRequestGetReferralCount(context_, callback);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>Fire-and-forget retrieval of rewards for the current session. Without a callback.</p>
*/
public void loadRewards() {
loadRewards(null);
}
/**
* <p>Retrieves rewards for the current session, with a callback to perform a predefined
* action following successful report of state change. You'll then need to call getCredits
* in the callback to update the credit totals in your UX.</p>
*
* @param callback A {@link BranchReferralStateChangedListener} callback instance that will
* trigger actions defined therein upon a referral state change.
*/
public void loadRewards(BranchReferralStateChangedListener callback) {
ServerRequest req = new ServerRequestGetRewards(context_, callback);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>Retrieve the number of credits available for the "default" bucket.</p>
*
* @return An {@link Integer} value of the number credits available in the "default" bucket.
*/
public int getCredits() {
return prefHelper_.getCreditCount();
}
/**
* Returns an {@link Integer} of the number of credits available for use within the supplied
* bucket name.
*
* @param bucket A {@link String} value indicating the name of the bucket to get credits for.
*
* @return An {@link Integer} value of the number credits available in the specified
* bucket.
*/
public int getCreditsForBucket(String bucket) {
return prefHelper_.getCreditCount(bucket);
}
/**
* <p>Gets the total number of times that the specified action has been carried out.</p>
*
* @param action A {@link String} value containing the name of the action to count.
*
* @return An {@link Integer} value of the total number of times that an action has
* been executed.
*/
public int getTotalCountsForAction(String action) {
return prefHelper_.getActionTotalCount(action);
}
/**
* <p>Gets the number of unique times that the specified action has been carried out.</p>
*
* @param action A {@link String} value containing the name of the action to count.
*
* @return An {@link Integer} value of the number of unique times that the
* specified action has been carried out.
*/
public int getUniqueCountsForAction(String action) {
return prefHelper_.getActionUniqueCount(action);
}
/**
* <p>Redeems the specified number of credits from the "default" bucket, if there are sufficient
* credits within it. If the number to redeem exceeds the number available in the bucket, all of
* the available credits will be redeemed instead.</p>
*
* @param count A {@link Integer} specifying the number of credits to attempt to redeem from
* the bucket.
*/
public void redeemRewards(int count) {
redeemRewards(Defines.Jsonkey.DefaultBucket.getKey(), count, null);
}
/**
* <p>Redeems the specified number of credits from the "default" bucket, if there are sufficient
* credits within it. If the number to redeem exceeds the number available in the bucket, all of
* the available credits will be redeemed instead.</p>
*
* @param count A {@link Integer} specifying the number of credits to attempt to redeem from
* the bucket.
*
* @param callback A {@link BranchReferralStateChangedListener} callback instance that will
* trigger actions defined therein upon a executing redeem rewards.
*/
public void redeemRewards(int count, BranchReferralStateChangedListener callback) {
redeemRewards(Defines.Jsonkey.DefaultBucket.getKey(), count, callback);
}
/**
* <p>Redeems the specified number of credits from the named bucket, if there are sufficient
* credits within it. If the number to redeem exceeds the number available in the bucket, all of
* the available credits will be redeemed instead.</p>
*
* @param bucket A {@link String} value containing the name of the referral bucket to attempt
* to redeem credits from.
*
* @param count A {@link Integer} specifying the number of credits to attempt to redeem from
* the specified bucket.
*/
public void redeemRewards(final String bucket, final int count) {
redeemRewards(bucket, count, null);
}
/**
* <p>Redeems the specified number of credits from the named bucket, if there are sufficient
* credits within it. If the number to redeem exceeds the number available in the bucket, all of
* the available credits will be redeemed instead.</p>
*
* @param bucket A {@link String} value containing the name of the referral bucket to attempt
* to redeem credits from.
* @param count A {@link Integer} specifying the number of credits to attempt to redeem from
* the specified bucket.
* @param callback A {@link BranchReferralStateChangedListener} callback instance that will
* trigger actions defined therein upon a executing redeem rewards.
*/
public void redeemRewards(final String bucket, final int count, BranchReferralStateChangedListener callback) {
ServerRequestRedeemRewards req = new ServerRequestRedeemRewards(context_, bucket, count, callback);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>Gets the credit history of the specified bucket and triggers a callback to handle the
* response.</p>
*
* @param callback A {@link BranchListResponseListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*/
public void getCreditHistory(BranchListResponseListener callback) {
getCreditHistory(null, null, 100, CreditHistoryOrder.kMostRecentFirst, callback);
}
/**
* <p>Gets the credit history of the specified bucket and triggers a callback to handle the
* response.</p>
*
* @param bucket A {@link String} value containing the name of the referral bucket that the
* code will belong to.
*
* @param callback A {@link BranchListResponseListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*/
public void getCreditHistory(final String bucket, BranchListResponseListener callback) {
getCreditHistory(bucket, null, 100, CreditHistoryOrder.kMostRecentFirst, callback);
}
/**
* <p>Gets the credit history of the specified bucket and triggers a callback to handle the
* response.</p>
*
* @param afterId A {@link String} value containing the ID of the history record to begin after.
* This allows for a partial history to be retrieved, rather than the entire
* credit history of the bucket.
*
* @param length A {@link Integer} value containing the number of credit history records to
* return.
*
* @param order A {@link CreditHistoryOrder} object indicating which order the results should
* be returned in.
*
* <p>Valid choices:</p>
*
* <ul>
* <li>{@link CreditHistoryOrder#kMostRecentFirst}</li>
* <li>{@link CreditHistoryOrder#kLeastRecentFirst}</li>
* </ul>
*
* @param callback A {@link BranchListResponseListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*/
public void getCreditHistory(final String afterId, final int length, final CreditHistoryOrder order, BranchListResponseListener callback) {
getCreditHistory(null, afterId, length, order, callback);
}
/**
* <p>Gets the credit history of the specified bucket and triggers a callback to handle the
* response.</p>
*
* @param bucket A {@link String} value containing the name of the referral bucket that the
* code will belong to.
* @param afterId A {@link String} value containing the ID of the history record to begin after.
* This allows for a partial history to be retrieved, rather than the entire
* credit history of the bucket.
* @param length A {@link Integer} value containing the number of credit history records to
* return.
* @param order A {@link CreditHistoryOrder} object indicating which order the results should
* be returned in.
* <p/>
* <p>Valid choices:</p>
* <p/>
* <ul>
* <li>{@link CreditHistoryOrder#kMostRecentFirst}</li>
* <li>{@link CreditHistoryOrder#kLeastRecentFirst}</li>
* </ul>
* @param callback A {@link BranchListResponseListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*/
public void getCreditHistory(final String bucket, final String afterId, final int length, final CreditHistoryOrder order, BranchListResponseListener callback) {
ServerRequest req = new ServerRequestGetRewardHistory(context_, bucket, afterId, length, order, callback);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>A void call to indicate that the user has performed a specific action and for that to be
* reported to the Branch API, with additional app-defined meta data to go along with that action.</p>
*
* @param action A {@link String} value to be passed as an action that the user has carried
* out. For example "registered" or "logged in".
* @param metadata A {@link JSONObject} containing app-defined meta-data to be attached to a
* user action that has just been completed.
*/
public void userCompletedAction(final String action, JSONObject metadata) {
if (metadata != null)
metadata = filterOutBadCharacters(metadata);
ServerRequest req = new ServerRequestActionCompleted(context_, action, metadata);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>A void call to indicate that the user has performed a specific action and for that to be
* reported to the Branch API.</p>
*
* @param action A {@link String} value to be passed as an action that the user has carried
* out. For example "registered" or "logged in".
*/
public void userCompletedAction(final String action) {
userCompletedAction(action, null);
}
/**
* <p>Returns the parameters associated with the link that referred the user. This is only set once,
* the first time the user is referred by a link. Think of this as the user referral parameters.
* It is also only set if isReferrable is equal to true, which by default is only true
* on a fresh install (not upgrade or reinstall). This will change on setIdentity (if the
* user already exists from a previous device) and logout.</p>
*
* @return A {@link JSONObject} containing the install-time parameters as configured
* locally.
*/
public JSONObject getFirstReferringParams() {
String storedParam = prefHelper_.getInstallParams();
return convertParamsStringToDictionary(storedParam);
}
/**
* <p>Returns the parameters associated with the link that referred the session. If a user
* clicks a link, and then opens the app, initSession will return the paramters of the link
* and then set them in as the latest parameters to be retrieved by this method. By default,
* sessions persist for the duration of time that the app is in focus. For example, if you
* minimize the app, these parameters will be cleared when closeSession is called.</p>
*
* @return A {@link JSONObject} containing the latest referring parameters as
* configured locally.
*/
public JSONObject getLatestReferringParams() {
String storedParam = prefHelper_.getSessionParams();
return convertParamsStringToDictionary(storedParam);
}
/**
* <p>Configures and requests a short URL to be generated by the Branch servers, via a synchronous
* call; with a duration specified within which an app session should be matched to the link.</p>
*
* @return A {@link String} containing the resulting short URL.
*/
public String getShortUrlSync() {
return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, stringifyParams(null), null, false);
}
/**
* <p>Configures and requests a short URL to be generated by the Branch servers, via a synchronous
* call; with a duration specified within which an app session should be matched to the link.</p>
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @return A {@link String} containing the resulting short URL.
*/
public String getShortUrlSync(JSONObject params) {
return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, stringifyParams(filterOutBadCharacters(params)), null, false);
}
/**
* <p>Configures and requests a referral URL to be generated by the Branch servers, via a synchronous
* call; with a duration specified within which an app session should be matched to the link.</p>
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @return A {@link String} containing the resulting referral URL.
*/
public String getReferralUrlSync(String channel, JSONObject params) {
return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(filterOutBadCharacters(params)), null, false);
}
/**
* <p>Configures and requests a referral URL to be generated by the Branch servers, via a synchronous
* call; with a duration specified within which an app session should be matched to the link.</p>
*
* @param tags An iterable {@link Collection} of {@link String} tags associated with a deep
* link.
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @return A {@link String} containing the resulting referral URL.
*/
public String getReferralUrlSync(Collection<String> tags, String channel, JSONObject params) {
return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(filterOutBadCharacters(params)), null, false);
}
/**
* <p>Configures and requests a content URL (defined as feature = sharing) to be generated by the Branch servers, via a synchronous
* call</p>
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @return A {@link String} containing the resulting content URL.
*/
public String getContentUrlSync(String channel, JSONObject params) {
return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_SHARE, null, stringifyParams(filterOutBadCharacters(params)), null, false);
}
/**
* <p>Configures and requests a content URL (defined as feature = sharing) to be generated by the Branch servers, via a synchronous
* call</p>
*
* @param tags An iterable {@link Collection} of {@link String} tags associated with a deep
* link.
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @return A {@link String} containing the resulting content URL.
*/
public String getContentUrlSync(Collection<String> tags, String channel, JSONObject params) {
return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_SHARE, null, stringifyParams(filterOutBadCharacters(params)), null, false);
}
/**
* <p>Configures and requests a short URL to be generated by the Branch servers, via a synchronous
* call; with a duration specified within which an app session should be matched to the link.</p>
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
*
* @param feature A {@link String} value identifying the feature that the link makes use of.
* Should not exceed 128 characters.
*
* @param stage A {@link String} value identifying the stage in an application or user flow process.
* Should not exceed 128 characters.
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @return A {@link String} containing the resulting short URL.
*/
public String getShortUrlSync(String channel, String feature, String stage, JSONObject params) {
return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false);
}
public String getShortUrlSync(String alias, String channel, String feature, String stage, JSONObject params) {
return generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false);
}
/**
* <p>Configures and requests a short URL to be generated by the Branch servers, via a synchronous
* call; with a duration specified within which an app session should be matched to the link.</p>
*
* @param type An {@link int} that can be used for scenarios where you want the link to
* only deep link the first time.
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
*
* @param feature A {@link String} value identifying the feature that the link makes use of.
* Should not exceed 128 characters.
*
* @param stage A {@link String} value identifying the stage in an application or user flow
* process. Should not exceed 128 characters.
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @return A {@link String} containing the resulting short URL.
*/
public String getShortUrlSync(int type, String channel, String feature, String stage, JSONObject params) {
return generateShortLink(null, type, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false);
}
/**
* <p>Configures and requests a short URL to be generated by the Branch servers, via a synchronous
* call; with a duration specified within which an app session should be matched to the link.</p>
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
*
* @param feature A {@link String} value identifying the feature that the link makes use of.
* Should not exceed 128 characters.
*
* @param stage A {@link String} value identifying the stage in an application or user flow
* process. Should not exceed 128 characters.
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @param duration A {@link Integer} value specifying the time that Branch allows a click to
* remain outstanding and be eligible to be matched with a new app session.
*
* @return A {@link String} containing the resulting short URL.
*/
public String getShortUrlSync(String channel, String feature, String stage, JSONObject params, int duration) {
return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false);
}
/**
* <p>Configures and requests a short URL to be generated by the Branch servers, via a synchronous
* call; with a duration specified within which an app session should be matched to the link.</p>
*
* @param tags An iterable {@link Collection} of {@link String} tags associated with a deep
* link.
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
*
* @param feature A {@link String} value identifying the feature that the link makes use of.
* Should not exceed 128 characters.
*
* @param stage A {@link String} value identifying the stage in an application or user flow
* process. Should not exceed 128 characters.
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @return A {@link String} containing the resulting short URL.
*/
public String getShortUrlSync(Collection<String> tags, String channel, String feature, String stage, JSONObject params) {
return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false);
}
public String getShortUrlSync(String alias, Collection<String> tags, String channel, String feature, String stage, JSONObject params) {
return generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false);
}
/**
* <p>Configures and requests a short URL to be generated by the Branch servers, via a synchronous
* call; with a duration specified within which an app session should be matched to the link.</p>
*
* @param type An {@link int} that can be used for scenarios where you want the link to
* only deep link the first time.
*
* @param tags An iterable {@link Collection} of {@link String} tags associated with a deep
* link.
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
*
* @param feature A {@link String} value identifying the feature that the link makes use of.
* Should not exceed 128 characters.
*
* @param stage A {@link String} value identifying the stage in an application or user flow
* process. Should not exceed 128 characters.
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @return A {@link String} containing the resulting short URL.
*/
public String getShortUrlSync(int type, Collection<String> tags, String channel, String feature, String stage, JSONObject params) {
return generateShortLink(null, type, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false);
}
/**
* <p>Configures and requests a short URL to be generated by the Branch servers, via a synchronous
* call; with a duration specified within which an app session should be matched to the link.</p>
*
* @param tags An iterable {@link Collection} of {@link String} tags associated with a deep
* link.
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
*
* @param feature A {@link String} value identifying the feature that the link makes use of.
* Should not exceed 128 characters.
*
* @param stage A {@link String} value identifying the stage in an application or user flow
* process. Should not exceed 128 characters.
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @param duration A {@link Integer} value specifying the time that Branch allows a click to
* remain outstanding and be eligible to be matched with a new app session.
*
* @return A {@link String} containing the resulting short URL.
*/
public String getShortUrlSync(Collection<String> tags, String channel, String feature, String stage, JSONObject params, int duration) {
return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false);
}
/**
* <p>Configures and requests a short URL to be generated by the Branch servers.</p>
*
* @param callback A {@link BranchLinkCreateListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*/
public void getShortUrl(BranchLinkCreateListener callback) {
generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, stringifyParams(null), callback, true);
}
/**
* <p>Configures and requests a short URL to be generated by the Branch servers.</p>
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @param callback A {@link BranchLinkCreateListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*
* @see BranchLinkData
* @see BranchLinkData#putParams(String)
* @see BranchLinkCreateListener
*/
public void getShortUrl(JSONObject params, BranchLinkCreateListener callback) {
generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, stringifyParams(filterOutBadCharacters(params)), callback, true);
}
/**
* <p>Configures and requests a referral URL (feature = referral) to be generated by the Branch servers.</p>
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @param callback A {@link BranchLinkCreateListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*
* @see BranchLinkData
* @see BranchLinkData#putChannel(String)
* @see BranchLinkData#putParams(String)
* @see BranchLinkCreateListener
*/
public void getReferralUrl(String channel, JSONObject params, BranchLinkCreateListener callback) {
generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(filterOutBadCharacters(params)), callback, true);
}
/**
* <p>Configures and requests a referral URL (feature = referral) to be generated by the Branch servers.</p>
*
* @param tags An iterable {@link Collection} of {@link String} tags associated with a deep
* link.
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @param callback A {@link BranchLinkCreateListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*
* @see BranchLinkData
* @see BranchLinkData#putTags(Collection)
* @see BranchLinkData#putChannel(String)
* @see BranchLinkData#putParams(String)
* @see BranchLinkCreateListener
*/
public void getReferralUrl(Collection<String> tags, String channel, JSONObject params, BranchLinkCreateListener callback) {
generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(filterOutBadCharacters(params)), callback, true);
}
/**
* <p>Configures and requests a content URL (defined as feature = sharing) to be generated by the Branch servers.</p>
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @param callback A {@link BranchLinkCreateListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*
* @see BranchLinkData
* @see BranchLinkData#putChannel(String)
* @see BranchLinkData#putParams(String)
* @see BranchLinkCreateListener
*/
public void getContentUrl(String channel, JSONObject params, BranchLinkCreateListener callback) {
generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_SHARE, null, stringifyParams(filterOutBadCharacters(params)), callback, true);
}
/**
* <p>Configures and requests a content URL (defined as feature = sharing) to be generated by the Branch servers.</p>
*
* @param tags An iterable {@link Collection} of {@link String} tags associated with a deep
* link.
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @param callback A {@link BranchLinkCreateListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*
* @see BranchLinkData
* @see BranchLinkData#putTags(Collection)
* @see BranchLinkData#putChannel(String)
* @see BranchLinkData#putParams(String)
* @see BranchLinkCreateListener
*/
public void getContentUrl(Collection<String> tags, String channel, JSONObject params, BranchLinkCreateListener callback) {
generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_SHARE, null, stringifyParams(filterOutBadCharacters(params)), callback, true);
}
/**
* <p>Configures and requests a short URL to be generated by the Branch servers.</p>
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
*
* @param feature A {@link String} value identifying the feature that the link makes use of.
* Should not exceed 128 characters.
*
* @param stage A {@link String} value identifying the stage in an application or user flow
* process. Should not exceed 128 characters.
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @param callback A {@link BranchLinkCreateListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*
* @see BranchLinkData
* @see BranchLinkData#putChannel(String)
* @see BranchLinkData#putFeature(String)
* @see BranchLinkData#putStage(String)
* @see BranchLinkData#putParams(String)
* @see BranchLinkCreateListener
*/
public void getShortUrl(String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) {
generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true);
}
public void getShortUrl(String alias, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) {
generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true);
}
/**
* <p>Configures and requests a short URL to be generated by the Branch servers.</p>
*
* @param type An {@link int} that can be used for scenarios where you want the link to
* only deep link the first time.
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
*
* @param feature A {@link String} value identifying the feature that the link makes use of.
* Should not exceed 128 characters.
*
* @param stage A {@link String} value identifying the stage in an application or user flow process.
* Should not exceed 128 characters.
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @param callback A {@link BranchLinkCreateListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*
* @see BranchLinkData
* @see BranchLinkData#putType(int)
* @see BranchLinkData#putChannel(String)
* @see BranchLinkData#putFeature(String)
* @see BranchLinkData#putStage(String)
* @see BranchLinkData#putParams(String)
* @see BranchLinkCreateListener
*/
public void getShortUrl(int type, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) {
generateShortLink(null, type, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true);
}
/**
* <p>Configures and requests a short URL to be generated by the Branch servers.</p>
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
*
* @param feature A {@link String} value identifying the feature that the link makes use of.
* Should not exceed 128 characters.
*
* @param stage A {@link String} value identifying the stage in an application or user flow
* process. Should not exceed 128 characters.
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @param duration An {@link int} the time that Branch allows a click to remain outstanding and
* be eligible to be matched with a new app session.
*
* @param callback A {@link BranchLinkCreateListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*
* @see BranchLinkData
* @see BranchLinkData#putTags(Collection)
* @see BranchLinkData#putChannel(String)
* @see BranchLinkData#putFeature(String)
* @see BranchLinkData#putStage(String)
* @see BranchLinkData#putParams(String)
* @see BranchLinkCreateListener
*/
public void getShortUrl(String channel, String feature, String stage, JSONObject params, int duration, BranchLinkCreateListener callback) {
generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true);
}
/**
* <p>Configures and requests a short URL to be generated by the Branch servers.</p>
*
* @param tags An iterable {@link Collection} of {@link String} tags associated with a deep
* link.
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
*
* @param feature A {@link String} value identifying the feature that the link makes use of.
* Should not exceed 128 characters.
*
* @param stage A {@link String} value identifying the stage in an application or user flow
* process. Should not exceed 128 characters.
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @param callback A {@link BranchLinkCreateListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*
* @see BranchLinkData
* @see BranchLinkData#putTags(Collection)
* @see BranchLinkData#putChannel(String)
* @see BranchLinkData#putFeature(String)
* @see BranchLinkData#putStage(String)
* @see BranchLinkData#putParams(String)
* @see BranchLinkCreateListener
*/
public void getShortUrl(Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) {
generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true);
}
public void getShortUrl(String alias, Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) {
generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true);
}
/**
* <p>Configures and requests a short URL to be generated by the Branch servers.</p>
*
* @param type An {@link int} that can be used for scenarios where you want the link to
* only deep link the first time.
*
* @param tags An iterable {@link Collection} of {@link String} tags associated with a deep
* link.
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
*
* @param feature A {@link String} value identifying the feature that the link makes use of.
* Should not exceed 128 characters.
*
* @param stage A {@link String} value identifying the stage in an application or user flow
* process. Should not exceed 128 characters.
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @param callback A {@link BranchLinkCreateListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*
* @see BranchLinkData
* @see BranchLinkData#putType(int)
* @see BranchLinkData#putTags(Collection)
* @see BranchLinkData#putChannel(String)
* @see BranchLinkData#putFeature(String)
* @see BranchLinkData#putStage(String)
* @see BranchLinkData#putParams(String)
* @see BranchLinkCreateListener
*/
public void getShortUrl(int type, Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) {
generateShortLink(null, type, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true);
}
/**
* <p>Configures and requests a short URL to be generated by the Branch servers.</p>
*
* @param tags An iterable {@link Collection} of {@link String} tags associated with a deep
* link.
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
*
* @param feature A {@link String} value identifying the feature that the link makes use of.
* Should not exceed 128 characters.
*
* @param stage A {@link String} value identifying the stage in an application or user flow
* process. Should not exceed 128 characters.
*
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
*
* @param duration An {@link int} the time that Branch allows a click to remain outstanding
* and be eligible to be matched with a new app session.
*
* @param callback A {@link BranchLinkCreateListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*
* @see BranchLinkData
* @see BranchLinkData#putTags(Collection)
* @see BranchLinkData#putChannel(String)
* @see BranchLinkData#putFeature(String)
* @see BranchLinkData#putStage(String)
* @see BranchLinkData#putParams(String)
* @see BranchLinkData#putDuration(int)
* @see BranchLinkCreateListener
*/
public void getShortUrl(Collection<String> tags, String channel, String feature, String stage, JSONObject params, int duration, BranchLinkCreateListener callback) {
generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true);
}
/**
* <p>Configures and requests a referral code to be generated by the Branch servers.</p>
*
* @param callback A {@link BranchReferralInitListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a referral code request.
*/
public void getReferralCode(BranchReferralInitListener callback) {
ServerRequest req = new ServerRequestGetReferralCode(context_, callback);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>Configures and requests a referral code to be generated by the Branch servers.</p>
*
* @param amount An {@link Integer} value of credits associated with this referral code.
*
* @param callback A {@link BranchReferralInitListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a referral code request.
*/
public void getReferralCode(final int amount, BranchReferralInitListener callback) {
this.getReferralCode(null, amount, null, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback);
}
/**
* <p>Configures and requests a referral code to be generated by the Branch servers.</p>
*
* @param prefix A {@link String} containing the developer-specified prefix code to be applied
* to the start of a referral code. e.g. for code OFFER4867, the prefix would
* be "OFFER".
*
* @param amount An {@link Integer} value of credits associated with this referral code.
*
* @param callback A {@link BranchReferralInitListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a referral code request.
*/
public void getReferralCode(final String prefix, final int amount, BranchReferralInitListener callback) {
this.getReferralCode(prefix, amount, null, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback);
}
/**
* <p>Configures and requests a referral code to be generated by the Branch servers.</p>
*
* @param amount An {@link Integer} value of credits associated with this referral code.
*
* @param expiration Optional expiration {@link Date} of the offer code.
*
* @param callback A {@link BranchReferralInitListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a referral code
* request.
*/
public void getReferralCode(final int amount, final Date expiration, BranchReferralInitListener callback) {
this.getReferralCode(null, amount, expiration, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback);
}
/**
* <p>Configures and requests a referral code to be generated by the Branch servers.</p>
*
* @param prefix A {@link String} containing the developer-specified prefix code to be
* applied to the start of a referral code. e.g. for code OFFER4867, the
* prefix would be "OFFER".
*
* @param amount An {@link Integer} value of credits associated with this referral code.
*
* @param expiration Optional expiration {@link Date} of the offer code.
*
* @param callback A {@link BranchReferralInitListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a referral code
* request.
*/
public void getReferralCode(final String prefix, final int amount, final Date expiration, BranchReferralInitListener callback) {
this.getReferralCode(prefix, amount, expiration, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback);
}
/**
* <p>Configures and requests a referral code to be generated by the Branch servers.</p>
*
* @param prefix A {@link String} containing the developer-specified prefix code to be
* applied to the start of a referral code. e.g. for code OFFER4867, the
* prefix would be "OFFER".
*
* @param amount An {@link Integer} value of credits associated with this referral code.
*
* @param calculationType The type of referral calculation. i.e.
* {@link #LINK_TYPE_UNLIMITED_USE} or
* {@link #LINK_TYPE_ONE_TIME_USE}
*
* @param location The user to reward for applying the referral code.
*
* <p>Valid options:</p>
*
* <ul>
* <li>{@link #REFERRAL_CODE_LOCATION_REFERREE}</li>
* <li>{@link #REFERRAL_CODE_LOCATION_REFERRING_USER}</li>
* <li>{@link #REFERRAL_CODE_LOCATION_BOTH}</li>
* </ul>
*
* @param callback A {@link BranchReferralInitListener} callback instance that will
* trigger actions defined therein upon receipt of a response to a
* referral code request.
*/
public void getReferralCode(final String prefix, final int amount, final int calculationType, final int location, BranchReferralInitListener callback) {
this.getReferralCode(prefix, amount, null, REFERRAL_BUCKET_DEFAULT, calculationType, location, callback);
}
/**
* <p>Configures and requests a referral code to be generated by the Branch servers.</p>
*
* @param prefix A {@link String} containing the developer-specified prefix code to
* be applied to the start of a referral code. e.g. for code OFFER4867,
* the prefix would be "OFFER".
* @param amount An {@link Integer} value of credits associated with this referral code.
* @param expiration Optional expiration {@link Date} of the offer code.
* @param bucket A {@link String} value containing the name of the referral bucket
* that the code will belong to.
* @param calculationType The type of referral calculation. i.e.
* {@link #LINK_TYPE_UNLIMITED_USE} or
* {@link #LINK_TYPE_ONE_TIME_USE}
* @param location The user to reward for applying the referral code.
* <p/>
* <p>Valid options:</p>
* <p/>
* <ul>
* <li>{@link #REFERRAL_CODE_LOCATION_REFERREE}</li>
* <li>{@link #REFERRAL_CODE_LOCATION_REFERRING_USER}</li>
* <li>{@link #REFERRAL_CODE_LOCATION_BOTH}</li>
* </ul>
* @param callback A {@link BranchReferralInitListener} callback instance that will
* trigger actions defined therein upon receipt of a response to a
* referral code request.
*/
public void getReferralCode(final String prefix, final int amount, final Date expiration, final String bucket, final int calculationType, final int location, BranchReferralInitListener callback) {
String date = null;
if (expiration != null)
date = convertDate(expiration);
ServerRequest req = new ServerRequestGetReferralCode(context_, prefix, amount, date, bucket,
calculationType, location, callback);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>Validates the supplied referral code on initialisation without applying it to the current
* session.</p>
*
* @param code A {@link String} object containing the referral code supplied.
* @param callback A {@link BranchReferralInitListener} callback to handle the server response
* of the referral submission request.
*/
public void validateReferralCode(final String code, BranchReferralInitListener callback) {
ServerRequest req = new ServerRequestValidateReferralCode(context_, callback, code);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>Applies a supplied referral code to the current user session upon initialisation.</p>
*
* @param code A {@link String} object containing the referral code supplied.
* @param callback A {@link BranchReferralInitListener} callback to handle the server
* response of the referral submission request.
* @see BranchReferralInitListener
*/
public void applyReferralCode(final String code, final BranchReferralInitListener callback) {
ServerRequest req = new ServerRequestApplyReferralCode(context_, callback, code);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
// PRIVATE FUNCTIONS
private String convertDate(Date date) {
return android.text.format.DateFormat.format("yyyy-MM-dd", date).toString();
}
private String stringifyParams(JSONObject params) {
if (params == null) {
params = new JSONObject();
}
try {
params.put("source", "android");
} catch (JSONException e) {
e.printStackTrace();
}
return params.toString();
}
private String generateShortLink(final String alias, final int type, final int duration, final Collection<String> tags, final String channel, final String feature, final String stage, final String params, BranchLinkCreateListener callback, boolean async) {
ServerRequestCreateUrl req = new ServerRequestCreateUrl(context_, alias, type, duration, tags,
channel, feature, stage,
params, callback, async);
if (!req.constructError_ && !req.handleErrors(context_)) {
if (linkCache_.containsKey(req.getLinkPost())) {
String url = linkCache_.get(req.getLinkPost());
if (callback != null) {
callback.onLinkCreate(url, null);
}
return url;
} else {
if (async) {
generateShortLinkAsync(req);
} else {
return generateShortLinkSync(req);
}
}
}
return null;
}
private String generateShortLinkSync(ServerRequest req) {
if (initState_ == SESSION_STATE.INITIALISED) {
ServerResponse response = kRemoteInterface_.createCustomUrlSync(req.getPost());
String url = prefHelper_.getUserURL();
if (response.getStatusCode() == 200) {
try {
url = response.getObject().getString("url");
if (response.getLinkData() != null) {
linkCache_.put(response.getLinkData(), url);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return url;
} else {
Log.i("BranchSDK", "Branch Warning: User session has not been initialized");
}
return null;
}
private void generateShortLinkAsync(final ServerRequest req) {
handleNewRequest(req);
}
private JSONObject filterOutBadCharacters(JSONObject inputObj) {
JSONObject filteredObj = new JSONObject();
if (inputObj != null) {
Iterator<?> keys = inputObj.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
try {
if (inputObj.has(key) && inputObj.get(key).getClass().equals(String.class)) {
filteredObj.put(key, inputObj.getString(key).replace("\n", "\\n").replace("\r", "\\r").replace("\"", "\\\""));
} else if (inputObj.has(key)) {
filteredObj.put(key, inputObj.get(key));
}
} catch(JSONException ignore) {
}
}
}
return filteredObj;
}
private JSONObject convertParamsStringToDictionary(String paramString) {
if (paramString.equals(PrefHelper.NO_STRING_VALUE)) {
return new JSONObject();
} else {
try {
return new JSONObject(paramString);
} catch (JSONException e) {
byte[] encodedArray = Base64.decode(paramString.getBytes(), Base64.NO_WRAP);
try {
return new JSONObject(new String(encodedArray));
} catch (JSONException ex) {
ex.printStackTrace();
return new JSONObject();
}
}
}
}
/**
* <p>Schedules a repeating threaded task to get the following details and report them to the
* Branch API <b>once a week</b>:</p>
* <p/>
* <pre style="background:#fff;padding:10px;border:2px solid silver;">
* int interval = 7 * 24 * 60 * 60;
* appListingSchedule_ = scheduler.scheduleAtFixedRate(
* periodicTask, (days * 24 + hours) * 60 * 60, interval, TimeUnit.SECONDS);</pre>
* <p/>
* <ul>
* <li>{@link SystemObserver#getAppKey()}</li>
* <li>{@link SystemObserver#getOS()}</li>
* <li>{@link SystemObserver#getDeviceFingerPrintID()}</li>
* <li>{@link SystemObserver#getListOfApps()}</li>
* </ul>
*
* @see {@link SystemObserver}
* @see {@link PrefHelper}
*/
private void scheduleListOfApps() {
ScheduledThreadPoolExecutor scheduler = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);
Runnable periodicTask = new Runnable() {
@Override
public void run() {
ServerRequest req = new ServerRequestSendAppList(context_);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
};
Date date = new Date();
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(date);
int days = Calendar.SATURDAY - calendar.get(Calendar.DAY_OF_WEEK); // days to Saturday
int hours = 2 - calendar.get(Calendar.HOUR_OF_DAY); // hours to 2am, can be negative
if (days == 0 && hours < 0) {
days = 7;
}
int interval = 7 * 24 * 60 * 60;
appListingSchedule_ = scheduler.scheduleAtFixedRate(periodicTask, (days * 24 + hours) * 60 * 60, interval, TimeUnit.SECONDS);
}
private void processNextQueueItem() {
try {
serverSema_.acquire();
if (networkCount_ == 0 && requestQueue_.getSize() > 0) {
networkCount_ = 1;
ServerRequest req = requestQueue_.peek();
serverSema_.release();
//All request except Install request need a valid IdentityID
if (!(req instanceof ServerRequestRegisterInstall) && !hasUser()) {
Log.i("BranchSDK", "Branch Error: User session has not been initialized!");
networkCount_ = 0;
handleFailure(requestQueue_.getSize() - 1, BranchError.ERR_NO_SESSION);
return;
}
//All request except open and install need a session to execute
else if (!req.isSessionInitRequest() && (!hasSession() || !hasDeviceFingerPrint())) {
networkCount_ = 0;
handleFailure(requestQueue_.getSize() - 1, BranchError.ERR_NO_SESSION);
return;
} else {
BranchPostTask postTask = new BranchPostTask(req);
postTask.execute();
}
} else {
serverSema_.release();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void handleFailure(int index, int statusCode) {
ServerRequest req;
if (index >= requestQueue_.getSize()) {
req = requestQueue_.peekAt(requestQueue_.getSize() - 1);
} else {
req = requestQueue_.peekAt(index);
}
handleFailure(req, statusCode);
}
private void handleFailure(final ServerRequest req, int statusCode) {
if (req == null)
return;
req.handleFailure(statusCode);
}
private void updateAllRequestsInQueue() {
try {
for (int i = 0; i < requestQueue_.getSize(); i++) {
ServerRequest req = requestQueue_.peekAt(i);
if (req.getPost() != null) {
Iterator<?> keys = req.getPost().keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if (key.equals(Defines.Jsonkey.SessionID.getKey())) {
req.getPost().put(key, prefHelper_.getSessionID());
} else if (key.equals(Defines.Jsonkey.IdentityID.getKey())) {
req.getPost().put(key, prefHelper_.getIdentityID());
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void clearCloseTimer() {
if (rotateCloseTimer == null)
return;
rotateCloseTimer.cancel();
rotateCloseTimer.purge();
rotateCloseTimer = new Timer();
}
private void clearTimer() {
if (closeTimer == null)
return;
closeTimer.cancel();
closeTimer.purge();
closeTimer = new Timer();
}
private void keepAlive() {
keepAlive_ = true;
synchronized(lock) {
clearTimer();
closeTimer.schedule(new TimerTask() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
keepAlive_ = false;
}
}).start();
}
}, SESSION_KEEPALIVE);
}
}
private boolean hasSession() {
return !prefHelper_.getSessionID().equals(PrefHelper.NO_STRING_VALUE);
}
private boolean hasDeviceFingerPrint() {
return !prefHelper_.getDeviceFingerPrintID().equals(PrefHelper.NO_STRING_VALUE);
}
private boolean hasUser() {
return !prefHelper_.getIdentityID().equals(PrefHelper.NO_STRING_VALUE);
}
private void insertRequestAtFront(ServerRequest req) {
if (networkCount_ == 0) {
requestQueue_.insert(req, 0);
} else {
requestQueue_.insert(req, 1);
}
}
private void registerInstallOrOpen(ServerRequest req, BranchReferralInitListener callback) {
// If there isn't already an Open / Install request, add one to the queue
if (!requestQueue_.containsInstallOrOpen()) {
insertRequestAtFront(req);
}
// If there is already one in the queue, make sure it's in the front.
// Make sure a callback is associated with this request. This callback can
// be cleared if the app is terminated while an Open/Install is pending.
else {
requestQueue_.moveInstallOrOpenToFront(req, networkCount_, callback);
}
processNextQueueItem();
}
private void initializeSession(BranchReferralInitListener callback) {
if ((prefHelper_.getBranchKey() == null || prefHelper_.getBranchKey().equalsIgnoreCase(PrefHelper.NO_STRING_VALUE))
&& (prefHelper_.getAppKey() == null || prefHelper_.getAppKey().equalsIgnoreCase(PrefHelper.NO_STRING_VALUE))) {
initState_ = SESSION_STATE.UNINITIALISED;
//Report Key error on callback
if (callback != null) {
callback.onInitFinished(null, new BranchError("Trouble initializing Branch.", RemoteInterface.NO_BRANCH_KEY_STATUS));
}
Log.i("BranchSDK", "Branch Warning: Please enter your branch_key in your project's res/values/strings.xml!");
return;
} else if (prefHelper_.getBranchKey() != null && prefHelper_.getBranchKey().startsWith("key_test_")) {
Log.i("BranchSDK", "Branch Warning: You are using your test app's Branch Key. Remember to change it to live Branch Key during deployment.");
}
if (hasUser()) {
registerInstallOrOpen(new ServerRequestRegisterOpen(context_, callback, kRemoteInterface_.getSystemObserver()), callback);
} else {
registerInstallOrOpen(new ServerRequestRegisterInstall(context_, callback, kRemoteInterface_.getSystemObserver(), PrefHelper.NO_STRING_VALUE), callback);
}
}
/**
* Handles execution of a new request other than open or install.
* Checks for the session initialisation and adds a install/Open request in front of this request
* if the request need session to execute.
*
* @param req The {@link ServerRequest} to execute
*/
private void handleNewRequest(ServerRequest req) {
//If not initialised put an open or install request in front of this request(only if this needs session)
if (initState_ != SESSION_STATE.INITIALISED && req.isSessionInitRequest() == false) {
if((req instanceof ServerRequestLogout)){
Log.i(TAG, "Branch is not initialized, cannot logout");
return;
}
if((req instanceof ServerRequestRegisterClose)){
Log.i(TAG, "Branch is not initialized, cannot close session");
return;
}
else{
initializeSession(null);
}
}
requestQueue_.enqueue(req);
processNextQueueItem();
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void setActivityLifeCycleObserver(Application application) {
try {
activityLifeCycleObserver_ = new BranchActivityLifeCycleObserver();
/* Set an observer for activity life cycle events. */
application.unregisterActivityLifecycleCallbacks(activityLifeCycleObserver_);
application.registerActivityLifecycleCallbacks(activityLifeCycleObserver_);
isActivityLifeCycleCallbackRegistered_ = true;
} catch (NoSuchMethodError Ex) {
isActivityLifeCycleCallbackRegistered_ = false;
isAutoSessionMode_ = false;
/* LifeCycleEvents are available only from API level 14. */
Log.w(TAG, BranchException.BRANCH_API_LVL_ERR_MSG);
} catch (NoClassDefFoundError Ex) {
isActivityLifeCycleCallbackRegistered_ = false;
isAutoSessionMode_ = false;
/* LifeCycleEvents are available only from API level 14. */
Log.w(TAG, BranchException.BRANCH_API_LVL_ERR_MSG);
}
}
/**
* <p>Class that observes activity life cycle events and determines when to start and stop
* session.</p>
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private class BranchActivityLifeCycleObserver implements Application.ActivityLifecycleCallbacks{
private int activityCnt_ = 0; //Keep the count of live activities.
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {}
@Override
public void onActivityStarted(Activity activity) {
if (activityCnt_ < 1) { // Check if this is the first Activity.If so start a session.
initSession();// indicate starting of session.
}
activityCnt_++;
}
@Override
public void onActivityResumed(Activity activity) {
//Set the activity for touch debug
if (prefHelper_.getTouchDebugging()) {
setTouchDebugInternal(activity);
}
}
@Override
public void onActivityPaused(Activity activity) {
clearTouchDebugInternal(activity);
}
@Override
public void onActivityStopped(Activity activity) {
activityCnt_--; // Check if this is the last activity.If so stop
// session.
if (activityCnt_ < 1) {
closeSessionInternal();
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {}
@Override
public void onActivityDestroyed(Activity activity) {}
}
/**
* <p>An Interface class that is implemented by all classes that make use of
* {@link BranchReferralInitListener}, defining a single method that takes a list of params in
* {@link JSONObject} format, and an error message of {@link BranchError} format that will be
* returned on failure of the request response.</p>
*
* @see JSONObject
* @see BranchError
*/
public interface BranchReferralInitListener {
public void onInitFinished(JSONObject referringParams, BranchError error);
}
/**
* <p>An Interface class that is implemented by all classes that make use of
* {@link BranchReferralStateChangedListener}, defining a single method that takes a value of
* {@link Boolean} format, and an error message of {@link BranchError} format that will be
* returned on failure of the request response.</p>
*
* @see Boolean
* @see BranchError
*/
public interface BranchReferralStateChangedListener {
public void onStateChanged(boolean changed, BranchError error);
}
/**
* <p>An Interface class that is implemented by all classes that make use of
* {@link BranchLinkCreateListener}, defining a single method that takes a URL
* {@link String} format, and an error message of {@link BranchError} format that will be
* returned on failure of the request response.</p>
*
* @see String
* @see BranchError
*/
public interface BranchLinkCreateListener {
public void onLinkCreate(String url, BranchError error);
}
/**
* <p>An Interface class that is implemented by all classes that make use of
* {@link BranchListResponseListener}, defining a single method that takes a list of
* {@link JSONArray} format, and an error message of {@link BranchError} format that will be
* returned on failure of the request response.</p>
*
* @see JSONArray
* @see BranchError
*/
public interface BranchListResponseListener {
public void onReceivingResponse(JSONArray list, BranchError error);
}
/**
* <p>enum containing the sort options for return of credit history.</p>
*/
public enum CreditHistoryOrder {
kMostRecentFirst, kLeastRecentFirst
}
/**
* Asynchronous task handling execution of server requests. Execute the network task on background
* thread and request are executed in sequential manner. Handles the request execution in
* Synchronous-Asynchronous pattern. Should be invoked only form main thread and the results are
* published in the main thread.
*/
private class BranchPostTask extends AsyncTask<Void, Void, ServerResponse> {
int timeOut_ = 0;
ServerRequest thisReq_;
public BranchPostTask(ServerRequest request) {
thisReq_ = request;
timeOut_ = prefHelper_.getTimeout();
}
@Override
protected ServerResponse doInBackground(Void... voids) {
if (thisReq_.isGetRequest()) {
return kRemoteInterface_.make_restful_get(thisReq_.getRequestUrl(), thisReq_.getRequestPath(), timeOut_);
} else {
return kRemoteInterface_.make_restful_post(thisReq_.getPost(), thisReq_.getRequestUrl(), thisReq_.getRequestPath(), timeOut_);
}
}
@Override
protected void onPostExecute(ServerResponse serverResponse) {
super.onPostExecute(serverResponse);
if (serverResponse != null) {
try {
int status = serverResponse.getStatusCode();
hasNetwork_ = true;
//If the request is not succeeded
if (status != 200) {
//If failed request is an initialisation request then mark session not initialised
if (thisReq_.isSessionInitRequest()) {
initState_ = SESSION_STATE.UNINITIALISED;
}
//On a bad request continue processing
if (status == 409) {
if (thisReq_ instanceof ServerRequestCreateUrl) {
((ServerRequestCreateUrl) thisReq_).handleDuplicateURLError();
} else {
Log.i("BranchSDK", "Branch API Error: Conflicting resource error code from API");
handleFailure(0, status);
}
}
//On Network error or Branch is down fail all the pending requests in the queue except
//for request which need to be replayed on failure.
else {
hasNetwork_ = false;
//Collect all request from the queue which need to be failed.
ArrayList<ServerRequest> requestToFail = new ArrayList<ServerRequest>();
for (int i = 0; i < requestQueue_.getSize(); i++) {
requestToFail.add(requestQueue_.peekAt(i));
}
//Remove the requests from the request queue first
for (ServerRequest req : requestToFail) {
if (!req.shouldRetryOnFail()) {
requestQueue_.remove(req);
}
}
// Then, set the network count to zero, indicating that requests can be started again.
networkCount_ = 0;
//Finally call the request callback with the error.
for (ServerRequest req : requestToFail) {
req.handleFailure(status);
//If request need to be replayed, no need for the callbacks
if (req.shouldRetryOnFail())
req.clearCallbacks();
}
}
}
//If the request succeeded
else {
hasNetwork_ = true;
//On create new url cache the url.
if (thisReq_ instanceof ServerRequestCreateUrl) {
final String url = serverResponse.getObject().getString("url");
// cache the link
linkCache_.put(serverResponse.getLinkData(), url);
}
//On Logout clear the link cache and all pending requests
else if (thisReq_ instanceof ServerRequestLogout) {
linkCache_.clear();
requestQueue_.clear();
}
//On setting a new identity Id clear teh link cache
else if (thisReq_ instanceof ServerRequestIdentifyUserRequest) {
try {
String new_Identity_Id = serverResponse.getObject().getString(Defines.Jsonkey.IdentityID.getKey());
if (!prefHelper_.getIdentityID().equals(new_Identity_Id)) {
linkCache_.clear();
}
} catch (Exception ignore) {
}
}
//Publish success to listeners
thisReq_.onRequestSucceeded(serverResponse, branchReferral_);
//If this request changes a session update the session-id to queued requests.
if (thisReq_.isSessionInitRequest()) {
updateAllRequestsInQueue();
initState_ = SESSION_STATE.INITIALISED;
}
requestQueue_.dequeue();
}
networkCount_ = 0;
if (hasNetwork_ && initState_ != SESSION_STATE.UNINITIALISED) {
processNextQueueItem();
}
} catch (JSONException ex) {
ex.printStackTrace();
}
}
}
}
public class BranchWindowCallback implements Window.Callback {
private Runnable longPressed_;
private Window.Callback callback_;
public BranchWindowCallback(Window.Callback callback) {
callback_ = callback;
if (longPressed_ == null) {
longPressed_ = new Runnable() {
private Timer timer;
public void run() {
debugHandler_.removeCallbacks(longPressed_);
if (!debugStarted_) {
Log.i("Branch Debug","======= Start Debug Session =======");
prefHelper_.setDebug();
timer = new Timer();
timer.scheduleAtFixedRate(new KeepDebugConnectionTask(), new Date(), 20000);
} else {
Log.i("Branch Debug","======= End Debug Session =======");
prefHelper_.clearDebug();
if (timer != null) {
timer.cancel();
timer = null;
}
}
debugStarted_ = !debugStarted_;
}
};
}
}
class KeepDebugConnectionTask extends TimerTask {
public void run() {
if (debugStarted_ && !prefHelper_.keepDebugConnection() && longPressed_ != null) {
debugHandler_.post(longPressed_);
}
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
@Override
public boolean dispatchGenericMotionEvent(MotionEvent event) {
return callback_.dispatchGenericMotionEvent(event);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
return callback_.dispatchKeyEvent(event);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public boolean dispatchKeyShortcutEvent(KeyEvent event) {
return callback_.dispatchKeyShortcutEvent(event);
}
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
return callback_.dispatchPopulateAccessibilityEvent(event);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
if (systemObserver_.isSimulator()) {
debugHandler_.postDelayed(longPressed_, PrefHelper.DEBUG_TRIGGER_PRESS_TIME);
}
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_CANCEL:
debugHandler_.removeCallbacks(longPressed_);
break;
case MotionEvent.ACTION_UP:
debugHandler_.removeCallbacks(longPressed_);
break;
case MotionEvent.ACTION_POINTER_DOWN:
if (event.getPointerCount() == PrefHelper.DEBUG_TRIGGER_NUM_FINGERS) {
debugHandler_.postDelayed(longPressed_, PrefHelper.DEBUG_TRIGGER_PRESS_TIME);
}
break;
default:
break;
}
return callback_.dispatchTouchEvent(event);
}
@Override
public boolean dispatchTrackballEvent(MotionEvent event) {
return callback_.dispatchTrackballEvent(event);
}
@Override
public void onActionModeFinished(ActionMode mode) {
callback_.onActionModeFinished(mode);
}
@Override
public void onActionModeStarted(ActionMode mode) {
callback_.onActionModeStarted(mode);
}
@Override
public void onAttachedToWindow() {
callback_.onAttachedToWindow();
}
@Override
public void onContentChanged() {
callback_.onContentChanged();
}
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
return callback_.onCreatePanelMenu(featureId, menu);
}
@Override
public View onCreatePanelView(int featureId) {
return callback_.onCreatePanelView(featureId);
}
@SuppressLint("MissingSuperCall")
@Override
public void onDetachedFromWindow() {
callback_.onDetachedFromWindow();
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
return callback_.onMenuItemSelected(featureId, item);
}
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
return callback_.onMenuOpened(featureId, menu);
}
@Override
public void onPanelClosed(int featureId, Menu menu) {
callback_.onPanelClosed(featureId, menu);
}
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
return callback_.onPreparePanel(featureId, view, menu);
}
@Override
public boolean onSearchRequested() {
return callback_.onSearchRequested();
}
@Override
public void onWindowAttributesChanged(WindowManager.LayoutParams attrs) {
callback_.onWindowAttributesChanged(attrs);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
callback_.onWindowFocusChanged(hasFocus);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
return callback_.onWindowStartingActionMode(callback);
}
}
}
|
package io.branch.referral;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.util.SparseArray;
import android.view.ActionMode;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import io.branch.indexing.BranchUniversalObject;
import io.branch.referral.util.LinkProperties;
/**
* <p>
* The core object required when using Branch SDK. You should declare an object of this type at
* the class-level of each Activity or Fragment that you wish to use Branch functionality within.
* </p>
* <p/>
* <p>
* Normal instantiation of this object would look like this:
* </p>
* <p/>
* <pre style="background:#fff;padding:10px;border:2px solid silver;">
* Branch.getInstance(this.getApplicationContext()) // from an Activity
* <p/>
* Branch.getInstance(getActivity().getApplicationContext()) // from a Fragment
* </pre>
*/
public class Branch {
private static final String TAG = "BranchSDK";
/**
* Hard-coded {@link String} that denotes a {@link BranchLinkData#tags}; applies to links that
* are shared with others directly as a user action, via social media for instance.
*/
public static final String FEATURE_TAG_SHARE = "share";
/**
* Hard-coded {@link String} that denotes a 'referral' tag; applies to links that are associated
* with a referral program, incentivized or not.
*/
public static final String FEATURE_TAG_REFERRAL = "referral";
/**
* Hard-coded {@link String} that denotes a 'referral' tag; applies to links that are sent as
* referral actions by users of an app using an 'invite contacts' feature for instance.
*/
public static final String FEATURE_TAG_INVITE = "invite";
/**
* Hard-coded {@link String} that denotes a link that is part of a commercial 'deal' or offer.
*/
public static final String FEATURE_TAG_DEAL = "deal";
/**
* Hard-coded {@link String} that denotes a link tagged as a gift action within a service or
* product.
*/
public static final String FEATURE_TAG_GIFT = "gift";
/**
* The code to be passed as part of a deal or gift; retrieved from the Branch object as a
* tag upon initialisation. Of {@link String} format.
*/
public static final String REDEEM_CODE = "$redeem_code";
/**
* <p>Default value of referral bucket; referral buckets contain credits that are used when users
* are referred to your apps. These can be viewed in the Branch dashboard under Referrals.</p>
*/
public static final String REFERRAL_BUCKET_DEFAULT = "default";
/**
* <p>Hard-coded value for referral code type. Referral codes will always result on "credit" actions.
* Even if they are of 0 value.</p>
*/
public static final String REFERRAL_CODE_TYPE = "credit";
/**
* Branch SDK version for the current release of the Branch SDK.
*/
public static final int REFERRAL_CREATION_SOURCE_SDK = 2;
/**
* Key value for referral code as a parameter.
*/
public static final String REFERRAL_CODE = "referral_code";
/**
* The redirect URL provided when the link is handled by a desktop client.
*/
public static final String REDIRECT_DESKTOP_URL = "$desktop_url";
/**
* The redirect URL provided when the link is handled by an Android device.
*/
public static final String REDIRECT_ANDROID_URL = "$android_url";
/**
* The redirect URL provided when the link is handled by an iOS device.
*/
public static final String REDIRECT_IOS_URL = "$ios_url";
/**
* The redirect URL provided when the link is handled by a large form-factor iOS device such as
* an iPad.
*/
public static final String REDIRECT_IPAD_URL = "$ipad_url";
/**
* The redirect URL provided when the link is handled by an Amazon Fire device.
*/
public static final String REDIRECT_FIRE_URL = "$fire_url";
/**
* The redirect URL provided when the link is handled by a Blackberry device.
*/
public static final String REDIRECT_BLACKBERRY_URL = "$blackberry_url";
/**
* The redirect URL provided when the link is handled by a Windows Phone device.
*/
public static final String REDIRECT_WINDOWS_PHONE_URL = "$windows_phone_url";
public static final String OG_TITLE = "$og_title";
public static final String OG_DESC = "$og_description";
public static final String OG_IMAGE_URL = "$og_image_url";
public static final String OG_VIDEO = "$og_video";
public static final String OG_URL = "$og_url";
/**
* Unique identifier for the app in use.
*/
public static final String OG_APP_ID = "$og_app_id";
/**
* {@link String} value denoting the deep link path to override Branch's default one. By
* default, Branch will use yourapp://open?link_click_id=12345. If you specify this key/value,
* Branch will use yourapp://'$deeplink_path'?link_click_id=12345
*/
public static final String DEEPLINK_PATH = "$deeplink_path";
/**
* {@link String} value indicating whether the link should always initiate a deep link action.
* By default, unless overridden on the dashboard, Branch will only open the app if they are
* 100% sure the app is installed. This setting will cause the link to always open the app.
* Possible values are "true" or "false"
*/
public static final String ALWAYS_DEEPLINK = "$always_deeplink";
/**
* An {@link Integer} value indicating the user to reward for applying a referral code. In this
* case, the user applying the referral code receives credit.
*/
public static final int REFERRAL_CODE_LOCATION_REFERREE = 0;
/**
* An {@link Integer} value indicating the user to reward for applying a referral code. In this
* case, the user who created the referral code receives credit.
*/
public static final int REFERRAL_CODE_LOCATION_REFERRING_USER = 2;
/**
* An {@link Integer} value indicating the user to reward for applying a referral code. In this
* case, both the creator and applicant receive credit
*/
public static final int REFERRAL_CODE_LOCATION_BOTH = 3;
/**
* An {@link Integer} value indicating the calculation type of the referral code. In this case,
* the referral code can be applied continually.
*/
public static final int REFERRAL_CODE_AWARD_UNLIMITED = 1;
/**
* An {@link Integer} value indicating the calculation type of the referral code. In this case,
* a user can only apply a specific referral code once.
*/
public static final int REFERRAL_CODE_AWARD_UNIQUE = 0;
/**
* An {@link Integer} value indicating the link type. In this case, the link can be used an
* unlimited number of times.
*/
public static final int LINK_TYPE_UNLIMITED_USE = 0;
/**
* An {@link Integer} value indicating the link type. In this case, the link can be used only
* once. After initial use, subsequent attempts will not validate.
*/
public static final int LINK_TYPE_ONE_TIME_USE = 1;
private static final int SESSION_KEEPALIVE = 2000;
/**
* <p>An {@link Integer} value defining the timeout period in milliseconds to wait during a
* looping task before triggering an actual connection close during a session close action.</p>
*/
private static final int PREVENT_CLOSE_TIMEOUT = 500;
/**
* <p>A {@link Branch} object that is instantiated on init and holds the singleton instance of
* the class during application runtime.</p>
*/
private static Branch branchReferral_;
private BranchRemoteInterface kRemoteInterface_;
private PrefHelper prefHelper_;
private SystemObserver systemObserver_;
private Context context_;
final Object lock;
private Timer closeTimer;
private Timer rotateCloseTimer;
private boolean keepAlive_;
private Semaphore serverSema_;
private ServerRequestQueue requestQueue_;
private int networkCount_;
private boolean hasNetwork_;
private SparseArray<String> debugListenerInitHistory_;
private OnTouchListener debugOnTouchListener_;
private Handler debugHandler_;
private boolean debugStarted_;
private Map<BranchLinkData, String> linkCache_;
private ScheduledFuture<?> appListingSchedule_;
/* Set to true when application is instantiating {@BranchApp} by extending or adding manifest entry. */
private static boolean isAutoSessionMode_ = false;
/* Set to true when {@link Activity} life cycle callbacks are registered. */
private static boolean isActivityLifeCycleCallbackRegistered_ = false;
/* Enumeration for defining session initialisation state. */
private enum SESSION_STATE {
INITIALISED, INITIALISING, UNINITIALISED
}
/* Holds the current Session state. Default is set to UNINITIALISED. */
private SESSION_STATE initState_ = SESSION_STATE.UNINITIALISED;
/* Instance of share link manager to share links automatically with third party applications. */
private ShareLinkManager shareLinkManager_;
/* The current activity instance for the application.*/
private Activity currentActivity_;
/* Specifies the choice of user for isReferrable setting. used to determine the link click is referrable or not. See getAutoSession for usage */
private enum CUSTOM_REFERRABLE_SETTINGS {
USE_DEFAULT, REFERRABLE, NON_REFERRABLE
}
/* By default assume user want to use the default settings. Update this option when user specify custom referrable settings */
private static CUSTOM_REFERRABLE_SETTINGS customReferrableSettings_ = CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT;
/* Key to indicate whether the Activity was launched by Branch or not. */
private static final String AUTO_DEEP_LINKED = "io.branch.sdk.auto_linked";
/* Key for Auto Deep link param. The activities which need to automatically deep linked should define in this in the activity metadata. */
private static final String AUTO_DEEP_LINK_KEY = "io.branch.sdk.auto_link_keys";
/* Path for $deeplink_path or $android_deeplink_path to auto deep link. The activities which need to automatically deep linked should define in this in the activity metadata. */
private static final String AUTO_DEEP_LINK_PATH = "io.branch.sdk.auto_link_path";
/* Key for disabling auto deep link feature. Setting this to true in manifest will disable auto deep linking feature. */
private static final String AUTO_DEEP_LINK_DISABLE = "io.branch.sdk.auto_link_disable";
/*Key for defining a request code for an activity. should be added as a metadata for an activity. This is used as a request code for launching a an activity on auto deep link. */
private static final String AUTO_DEEP_LINK_REQ_CODE = "io.branch.sdk.auto_link_request_code";
/* Request code used to launch and activity on auto deep linking unless DEF_AUTO_DEEP_LINK_REQ_CODE is not specified for teh activity in manifest.*/
private static final int DEF_AUTO_DEEP_LINK_REQ_CODE = 1501;
/* Sets to true when the init session params are reported to the app though call back.*/
private boolean isInitReportedThroughCallBack = false;
/**
* <p>The main constructor of the Branch class is private because the class uses the Singleton
* pattern.</p>
* <p/>
* <p>Use {@link #getInstance(Context) getInstance} method when instantiating.</p>
*
* @param context A {@link Context} from which this call was made.
*/
private Branch(@NonNull Context context) {
prefHelper_ = PrefHelper.getInstance(context);
kRemoteInterface_ = new BranchRemoteInterface(context);
systemObserver_ = new SystemObserver(context);
requestQueue_ = ServerRequestQueue.getInstance(context);
serverSema_ = new Semaphore(1);
closeTimer = new Timer();
rotateCloseTimer = new Timer();
lock = new Object();
keepAlive_ = false;
networkCount_ = 0;
hasNetwork_ = true;
debugListenerInitHistory_ = new SparseArray<>();
debugOnTouchListener_ = retrieveOnTouchListener();
debugHandler_ = new Handler();
debugStarted_ = false;
linkCache_ = new HashMap<>();
}
/**
* <p>Singleton method to return the pre-initialised object of the type {@link Branch}.
* Make sure your app is instantiating {@link BranchApp} before calling this method
* or you have created an instance of Branch already by calling getInstance(Context ctx).</p>
*
* @return An initialised singleton {@link Branch} object
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static Branch getInstance() {
/* Check if BranchApp is instantiated. */
if (branchReferral_ == null) {
Log.e("BranchSDK", "Branch instance is not created yet. Make sure you have initialised Branch. [Consider Calling getInstance(Context ctx) if you still have issue.]");
} else if (isAutoSessionMode_) {
/* Check if Activity life cycle callbacks are set if in auto session mode. */
if (!isActivityLifeCycleCallbackRegistered_) {
Log.e("BranchSDK", "Branch instance is not properly initialised. Make sure your Application class is extending BranchApp class. " +
"If you are not extending BranchApp class make sure you are initialising Branch in your Applications onCreate()");
}
}
return branchReferral_;
}
public static Branch getInstance(@NonNull Context context, @NonNull String branchKey) {
if (branchReferral_ == null) {
branchReferral_ = Branch.initInstance(context);
}
branchReferral_.context_ = context.getApplicationContext();
if (branchKey.startsWith("key_")) {
boolean isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(branchKey);
//on setting a new key clear link cache and pending requests
if (isNewBranchKeySet) {
branchReferral_.linkCache_.clear();
branchReferral_.requestQueue_.clear();
}
} else {
branchReferral_.prefHelper_.setAppKey(branchKey);
}
return branchReferral_;
}
private static Branch getBranchInstance(@NonNull Context context, boolean isLive) {
if (branchReferral_ == null) {
branchReferral_ = Branch.initInstance(context);
String branchKey = branchReferral_.prefHelper_.readBranchKey(isLive);
boolean isNewBranchKeySet;
if (branchKey == null || branchKey.equalsIgnoreCase(PrefHelper.NO_STRING_VALUE)) {
Log.i("BranchSDK", "Branch Warning: Please enter your branch_key in your project's Manifest file!");
isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(PrefHelper.NO_STRING_VALUE);
} else {
isNewBranchKeySet = branchReferral_.prefHelper_.setBranchKey(branchKey);
}
//on setting a new key clear link cache and pending requests
if (isNewBranchKeySet) {
branchReferral_.linkCache_.clear();
branchReferral_.requestQueue_.clear();
}
}
branchReferral_.context_ = context.getApplicationContext();
/* If {@link Application} is instantiated register for activity life cycle events. */
if (context instanceof BranchApp) {
isAutoSessionMode_ = true;
branchReferral_.setActivityLifeCycleObserver((Application) context);
}
return branchReferral_;
}
/**
* <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton
* object of the type {@link Branch}.</p>
* <p/>
* <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p>
*
* @param context A {@link Context} from which this call was made.
* @return An initialised {@link Branch} object, either fetched from a pre-initialised
* instance within the singleton class, or a newly instantiated object where
* one was not already requested during the current app lifecycle.
*/
public static Branch getInstance(@NonNull Context context) {
return getBranchInstance(context, true);
}
/**
* <p>If you configured the your Strings file according to the guide, you'll be able to use
* the test version of your app by just calling this static method before calling initSession.</p>
*
* @param context A {@link Context} from which this call was made.
* @return An initialised {@link Branch} object.
*/
public static Branch getTestInstance(@NonNull Context context) {
return getBranchInstance(context, false);
}
/**
* <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton
* object of the type {@link Branch}.</p>
* <p/>
* <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p>
*
* @param context A {@link Context} from which this call was made.
* @return An initialised {@link Branch} object, either fetched from a pre-initialised
* instance within the singleton class, or a newly instantiated object where
* one was not already requested during the current app lifecycle.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static Branch getAutoInstance(@NonNull Context context) {
isAutoSessionMode_ = true;
customReferrableSettings_ = CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT;
boolean isLive = !BranchUtil.isTestModeEnabled(context);
getBranchInstance(context, isLive);
branchReferral_.setActivityLifeCycleObserver((Application) context);
return branchReferral_;
}
/**
* <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton
* object of the type {@link Branch}.</p>
* <p/>
* <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p>
*
* @param context A {@link Context} from which this call was made.
* @param isReferrable A {@link Boolean} value indicating whether initialising a session on this Branch instance
* should be considered as potentially referrable or not. By default, a user is only referrable
* if initSession results in a fresh install. Overriding this gives you control of who is referrable.
* @return An initialised {@link Branch} object, either fetched from a pre-initialised
* instance within the singleton class, or a newly instantiated object where
* one was not already requested during the current app lifecycle.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static Branch getAutoInstance(@NonNull Context context, boolean isReferrable) {
isAutoSessionMode_ = true;
customReferrableSettings_ = isReferrable ? CUSTOM_REFERRABLE_SETTINGS.REFERRABLE : CUSTOM_REFERRABLE_SETTINGS.NON_REFERRABLE;
boolean isDebug = BranchUtil.isTestModeEnabled(context);
getBranchInstance(context, !isDebug);
branchReferral_.setActivityLifeCycleObserver((Application) context);
return branchReferral_;
}
/**
* <p>If you configured the your Strings file according to the guide, you'll be able to use
* the test version of your app by just calling this static method before calling initSession.</p>
*
* @param context A {@link Context} from which this call was made.
* @return An initialised {@link Branch} object.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static Branch getAutoTestInstance(@NonNull Context context) {
isAutoSessionMode_ = true;
customReferrableSettings_ = CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT;
getBranchInstance(context, false);
branchReferral_.setActivityLifeCycleObserver((Application) context);
return branchReferral_;
}
/**
* <p>If you configured the your Strings file according to the guide, you'll be able to use
* the test version of your app by just calling this static method before calling initSession.</p>
*
* @param context A {@link Context} from which this call was made.
* @param isReferrable A {@link Boolean} value indicating whether initialising a session on this Branch instance
* should be considered as potentially referrable or not. By default, a user is only referrable
* if initSession results in a fresh install. Overriding this gives you control of who is referrable.
* @return An initialised {@link Branch} object.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static Branch getAutoTestInstance(@NonNull Context context, boolean isReferrable) {
isAutoSessionMode_ = true;
customReferrableSettings_ = isReferrable ? CUSTOM_REFERRABLE_SETTINGS.REFERRABLE : CUSTOM_REFERRABLE_SETTINGS.NON_REFERRABLE;
getBranchInstance(context, false);
branchReferral_.setActivityLifeCycleObserver((Application) context);
return branchReferral_;
}
/**
* <p>Initialises an instance of the Branch object.</p>
*
* @param context A {@link Context} from which this call was made.
* @return An initialised {@link Branch} object.
*/
private static Branch initInstance(@NonNull Context context) {
return new Branch(context.getApplicationContext());
}
/**
* <p>Manually sets the {@link Boolean} value, that indicates that the Branch API connection has
* been initialised, to false - forcing re-initialisation.</p>
*/
public void resetUserSession() {
initState_ = SESSION_STATE.UNINITIALISED;
}
/**
* <p>Sets the number of times to re-attempt a timed-out request to the Branch API, before
* considering the request to have failed entirely. Default 5.</p>
*
* @param retryCount An {@link Integer} specifying the number of times to retry before giving
* up and declaring defeat.
*/
public void setRetryCount(int retryCount) {
if (prefHelper_ != null && retryCount > 0) {
prefHelper_.setRetryCount(retryCount);
}
}
/**
* <p>Sets the amount of time in milliseconds to wait before re-attempting a timed-out request
* to the Branch API. Default 3000 ms.</p>
*
* @param retryInterval An {@link Integer} value specifying the number of milliseconds to
* wait before re-attempting a timed-out request.
*/
public void setRetryInterval(int retryInterval) {
if (prefHelper_ != null && retryInterval > 0) {
prefHelper_.setRetryInterval(retryInterval);
}
}
/**
* <p>Sets the duration in milliseconds that the system should wait for a response before considering
* any Branch API call to have timed out. Default 3000 ms.</p>
* <p/>
* <p>Increase this to perform better in low network speed situations, but at the expense of
* responsiveness to error situation.</p>
*
* @param timeout An {@link Integer} value specifying the number of milliseconds to wait before
* considering the request to have timed out.
*/
public void setNetworkTimeout(int timeout) {
if (prefHelper_ != null && timeout > 0) {
prefHelper_.setTimeout(timeout);
}
}
/**
* <p>Sets the library to function in debug mode, enabling logging of all requests.</p>
* <p>If you want to flag debug, call this <b>before</b> initUserSession</p>
*
* @deprecated use <meta-data android:name="io.branch.sdk.TestMode" android:value="true" /> in the manifest instead.
*/
@Deprecated
public void setDebug() {
prefHelper_.setExternDebug();
}
/**
* <p>Calls the {@link PrefHelper#disableExternAppListing()} on the local instance to prevent
* a list of installed apps from being returned to the Branch API.</p>
*/
public void disableAppList() {
prefHelper_.disableExternAppListing();
}
/**
* <p>Calls the {@link PrefHelper#disableTouchDebugging()} ()} on the local instance to prevent
* touch debugging feature.</p>
*/
public void disableTouchDebugging() {
prefHelper_.disableTouchDebugging();
}
/**
* <p>If there's further Branch API call happening within the two seconds, we then don't close
* the session; otherwise, we close the session after two seconds.</p>
* <p/>
* <p>Call this method if you don't want this smart session feature and would rather manage
* the session yourself.</p>
* <p/>
* <p><b>Note:</b> smart session - we keep session alive for two seconds</p>
*/
public void disableSmartSession() {
prefHelper_.disableSmartSession();
}
/**
* <p>Initialises a session with the Branch API, assigning a {@link BranchUniversalReferralInitListener}
* to perform an action upon successful initialisation.</p>
*
* @param callback A {@link BranchUniversalReferralInitListener} instance that will be called following
* successful (or unsuccessful) initialisation of the session with the Branch API.
* @return A {@link Boolean} value, indicating <i>false</i> if initialisation is
* unsuccessful.
*/
public boolean initSession(BranchUniversalReferralInitListener callback) {
initSession(callback, (Activity) null);
return false;
}
/**
* <p>Initialises a session with the Branch API, assigning a {@link BranchReferralInitListener}
* to perform an action upon successful initialisation.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called following
* successful (or unsuccessful) initialisation of the session with the Branch API.
* @return A {@link Boolean} value, indicating <i>false</i> if initialisation is
* unsuccessful.
*/
public boolean initSession(BranchReferralInitListener callback) {
initSession(callback, (Activity) null);
return false;
}
/**
* <p>Initialises a session with the Branch API, passing the {@link Activity} and assigning a
* {@link BranchUniversalReferralInitListener} to perform an action upon successful initialisation.</p>
*
* @param callback A {@link BranchUniversalReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value, indicating <i>false</i> if initialisation is
* unsuccessful.
*/
public boolean initSession(BranchUniversalReferralInitListener callback, Activity activity) {
if (customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT) {
initUserSessionInternal(callback, activity, true);
} else {
boolean isReferrable = customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.REFERRABLE;
initUserSessionInternal(callback, activity, isReferrable);
}
return false;
}
/**
* <p>Initialises a session with the Branch API, passing the {@link Activity} and assigning a
* {@link BranchReferralInitListener} to perform an action upon successful initialisation.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value, indicating <i>false</i> if initialisation is
* unsuccessful.
*/
public boolean initSession(BranchReferralInitListener callback, Activity activity) {
if (customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT) {
initUserSessionInternal(callback, activity, true);
} else {
boolean isReferrable = customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.REFERRABLE;
initUserSessionInternal(callback, activity, isReferrable);
}
return false;
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchUniversalReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param data A {@link Uri} variable containing the details of the source link that
* led to this initialisation action.
* @return A {@link Boolean} value that will return <i>false</i> if the supplied
* <i>data</i> parameter cannot be handled successfully - i.e. is not of a
* valid URI format.
*/
public boolean initSession(BranchUniversalReferralInitListener callback, @NonNull Uri data) {
return initSession(callback, data, null);
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param data A {@link Uri} variable containing the details of the source link that
* led to this initialisation action.
* @return A {@link Boolean} value that will return <i>false</i> if the supplied
* <i>data</i> parameter cannot be handled successfully - i.e. is not of a
* valid URI format.
*/
public boolean initSession(BranchReferralInitListener callback, @NonNull Uri data) {
return initSession(callback, data, null);
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchUniversalReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param data A {@link Uri} variable containing the details of the source link that
* led to this initialisation action.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value that will return <i>false</i> if the supplied
* <i>data</i> parameter cannot be handled successfully - i.e. is not of a
* valid URI format.
*/
public boolean initSession(BranchUniversalReferralInitListener callback, @NonNull Uri data, Activity activity) {
boolean uriHandled = readAndStripParam(data, activity);
initSession(callback, activity);
return uriHandled;
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param data A {@link Uri} variable containing the details of the source link that
* led to this initialisation action.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value that will return <i>false</i> if the supplied
* <i>data</i> parameter cannot be handled successfully - i.e. is not of a
* valid URI format.
*/
public boolean initSession(BranchReferralInitListener callback, @NonNull Uri data, Activity activity) {
boolean uriHandled = readAndStripParam(data, activity);
initSession(callback, activity);
return uriHandled;
}
/**
* <p>Initialises a session with the Branch API, without a callback or {@link Activity}.</p>
*
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession() {
return initSession((Activity) null);
}
/**
* <p>Initialises a session with the Branch API, without a callback or {@link Activity}.</p>
*
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(Activity activity) {
return initSession((BranchReferralInitListener) null, activity);
}
/**
* <p>Initialises a session with the Branch API, with associated data from the supplied
* {@link Uri}.</p>
*
* @param data A {@link Uri} variable containing the details of the source link that
* led to this
* initialisation action.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSessionWithData(@NonNull Uri data) {
return initSessionWithData(data, null);
}
/**
* <p>Initialises a session with the Branch API, with associated data from the supplied
* {@link Uri}.</p>
*
* @param data A {@link Uri} variable containing the details of the source link that led to this
* initialisation action.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSessionWithData(Uri data, Activity activity) {
boolean uriHandled = readAndStripParam(data, activity);
initSession((BranchReferralInitListener) null, activity);
return uriHandled;
}
/**
* <p>Initialises a session with the Branch API, specifying whether the initialisation can count
* as a referrable action.</p>
*
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(boolean isReferrable) {
return initSession((BranchReferralInitListener) null, isReferrable, (Activity) null);
}
/**
* <p>Initialises a session with the Branch API, specifying whether the initialisation can count
* as a referrable action, and supplying the calling {@link Activity} for context.</p>
*
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(boolean isReferrable, @NonNull Activity activity) {
return initSession((BranchReferralInitListener) null, isReferrable, activity);
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchUniversalReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @param data A {@link Uri} variable containing the details of the source link that
* led to this initialisation action.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(BranchUniversalReferralInitListener callback, boolean isReferrable, Uri data) {
return initSession(callback, isReferrable, data, null);
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @param data A {@link Uri} variable containing the details of the source link that
* led to this initialisation action.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, @NonNull Uri data) {
return initSession(callback, isReferrable, data, null);
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchUniversalReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @param data A {@link Uri} variable containing the details of the source link that
* led to this initialisation action.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(BranchUniversalReferralInitListener callback, boolean isReferrable, @NonNull Uri data, Activity activity) {
boolean uriHandled = readAndStripParam(data, activity);
initSession(callback, isReferrable, activity);
return uriHandled;
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @param data A {@link Uri} variable containing the details of the source link that
* led to this initialisation action.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, @NonNull Uri data, Activity activity) {
boolean uriHandled = readAndStripParam(data, activity);
initSession(callback, isReferrable, activity);
return uriHandled;
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchUniversalReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(BranchUniversalReferralInitListener callback, boolean isReferrable) {
return initSession(callback, isReferrable, (Activity) null);
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(BranchReferralInitListener callback, boolean isReferrable) {
return initSession(callback, isReferrable, (Activity) null);
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchUniversalReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(BranchUniversalReferralInitListener callback, boolean isReferrable, Activity activity) {
initUserSessionInternal(callback, activity, isReferrable);
return false;
}
/**
* <p>Initialises a session with the Branch API.</p>
*
* @param callback A {@link BranchReferralInitListener} instance that will be called
* following successful (or unsuccessful) initialisation of the session
* with the Branch API.
* @param isReferrable A {@link Boolean} value indicating whether this initialisation
* session should be considered as potentially referrable or not.
* By default, a user is only referrable if initSession results in a
* fresh install. Overriding this gives you control of who is referrable.
* @param activity The calling {@link Activity} for context.
* @return A {@link Boolean} value that returns <i>false</i> if unsuccessful.
*/
public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, Activity activity) {
initUserSessionInternal(callback, activity, isReferrable);
return false;
}
private void initUserSessionInternal(BranchUniversalReferralInitListener callback, Activity activity, boolean isReferrable) {
BranchUniversalReferralInitWrapper branchUniversalReferralInitWrapper = new BranchUniversalReferralInitWrapper(callback);
initUserSessionInternal(branchUniversalReferralInitWrapper, activity, isReferrable);
}
private void initUserSessionInternal(BranchReferralInitListener callback, Activity activity, boolean isReferrable) {
currentActivity_ = activity;
//If already initialised
if (hasUser() && hasSession() && initState_ == SESSION_STATE.INITIALISED) {
if (callback != null) {
if (isAutoSessionMode_) {
// Since Auto session mode initialise the session by itself on starting the first activity, we need to provide user
// the referring params if they call init session after init is completed. Note that user wont do InitSession per activity in auto session mode.
if (!isInitReportedThroughCallBack) { //Check if session params are reported already in case user call initsession form a different activity(not a noraml case)
callback.onInitFinished(getLatestReferringParams(), null);
isInitReportedThroughCallBack = true;
} else {
callback.onInitFinished(new JSONObject(), null);
}
} else {
// Since user will do init session per activity in non auto session mode , we don't want to repeat the referring params with each initSession()call.
callback.onInitFinished(new JSONObject(), null);
}
}
clearCloseTimer();
keepAlive();
}
//If uninitialised or initialising
else {
// In case of Auto session init will be called from Branch before user. So initialising
// State also need to look for isReferrable value
if (isReferrable) {
this.prefHelper_.setIsReferrable();
} else {
this.prefHelper_.clearIsReferrable();
}
//If initialising ,then set new callbacks.
if (initState_ == SESSION_STATE.INITIALISING) {
requestQueue_.setInstallOrOpenCallback(callback);
}
//if Uninitialised move request to the front if there is an existing request or create a new request.
else {
initState_ = SESSION_STATE.INITIALISING;
initializeSession(callback);
}
}
if (prefHelper_.getTouchDebugging()) {
if (activity != null && debugListenerInitHistory_.get(System.identityHashCode(activity)) == null) {
debugListenerInitHistory_.put(System.identityHashCode(activity), "init");
View view = activity.getWindow().getDecorView().findViewById(android.R.id.content);
if (view != null) {
view.setOnTouchListener(debugOnTouchListener_);
}
}
}
}
/**
* <p>Set the current activity window for the debug touch events. Only for internal usage.</p>
*
* @param activity The current activity.
*/
private void setTouchDebugInternal(Activity activity) {
if (activity != null && debugListenerInitHistory_.get(System.identityHashCode(activity)) == null) {
debugListenerInitHistory_.put(System.identityHashCode(activity), "init");
activity.getWindow().setCallback(new BranchWindowCallback(activity.getWindow().getCallback()));
}
}
private void clearTouchDebugInternal(Activity activity) {
if (activity.getWindow().getCallback() instanceof BranchWindowCallback) {
Window.Callback originalCallback =
((BranchWindowCallback) activity.getWindow().getCallback()).callback_;
activity.getWindow().setCallback(originalCallback);
debugListenerInitHistory_.remove(System.identityHashCode(activity));
//Remove the pending threads on the handler inorder to prevent any leak.
if (debugHandler_ != null) {
debugHandler_.removeCallbacksAndMessages(null);
}
}
}
private OnTouchListener retrieveOnTouchListener() {
if (debugOnTouchListener_ == null) {
debugOnTouchListener_ = new OnTouchListener() {
class KeepDebugConnectionTask extends TimerTask {
public void run() {
if (!prefHelper_.keepDebugConnection()) {
debugHandler_.post(_longPressed);
}
}
}
Runnable _longPressed = new Runnable() {
private boolean started = false;
private Timer timer;
public void run() {
debugHandler_.removeCallbacks(_longPressed);
if (!started) {
Log.i("Branch Debug", "======= Start Debug Session =======");
prefHelper_.setDebug();
timer = new Timer();
timer.scheduleAtFixedRate(new KeepDebugConnectionTask(), new Date(), 20000);
} else {
Log.i("Branch Debug", "======= End Debug Session =======");
prefHelper_.clearDebug();
timer.cancel();
timer = null;
}
this.started = !this.started;
}
};
@Override
public boolean onTouch(View v, MotionEvent ev) {
int pointerCount = ev.getPointerCount();
final int actionPerformed = ev.getAction();
switch (actionPerformed & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
if (systemObserver_.isSimulator()) {
debugHandler_.postDelayed(_longPressed, PrefHelper.DEBUG_TRIGGER_PRESS_TIME);
}
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_CANCEL:
debugHandler_.removeCallbacks(_longPressed);
break;
case MotionEvent.ACTION_UP:
v.performClick();
debugHandler_.removeCallbacks(_longPressed);
break;
case MotionEvent.ACTION_POINTER_DOWN:
if (pointerCount == PrefHelper.DEBUG_TRIGGER_NUM_FINGERS) {
debugHandler_.postDelayed(_longPressed, PrefHelper.DEBUG_TRIGGER_PRESS_TIME);
}
break;
}
return true;
}
};
}
return debugOnTouchListener_;
}
/**
* <p>Closes the current session, dependent on the state of the
* {@link PrefHelper#getSmartSession()} {@link Boolean} value. If <i>true</i>, take no action.
* If false, close the sesion via the {@link #executeClose()} method.</p>
* <p>Note that if smartSession is enabled, closeSession cannot be called within
* a 2 second time span of another Branch action. This has to do with the method that
* Branch uses to keep a session alive during Activity transitions</p>
*/
public void closeSession() {
if (isAutoSessionMode_) {
/*
* Ignore any session close request from user if session is managed
* automatically.This is handle situation of closeSession() in
* closed by developer by error while running in auto session mode.
*/
return;
}
if (prefHelper_.getSmartSession()) {
if (keepAlive_) {
return;
}
// else, real close
synchronized (lock) {
clearCloseTimer();
rotateCloseTimer.schedule(new TimerTask() {
@Override
public void run() {
//Since non auto session has no lifecycle callback enabled free up the currentActivity_
currentActivity_ = null;
executeClose();
}
}, PREVENT_CLOSE_TIMEOUT);
}
} else {
//Since non auto session has no lifecycle callback enabled free up the currentActivity_
currentActivity_ = null;
executeClose();
}
if (prefHelper_.getExternAppListing()) {
if (appListingSchedule_ == null) {
scheduleListOfApps();
}
}
/* Close any opened sharing dialog.*/
if (shareLinkManager_ != null) {
shareLinkManager_.cancelShareLinkDialog(true);
}
}
/*
* <p>Closes the current session. Should be called by on getting the last actvity onStop() event.
* </p>
*/
private void closeSessionInternal() {
executeClose();
if (prefHelper_.getExternAppListing()) {
if (appListingSchedule_ == null) {
scheduleListOfApps();
}
}
}
/**
* <p>Perform the state-safe actions required to terminate any open session, and report the
* closed application event to the Branch API.</p>
*/
private void executeClose() {
if (initState_ != SESSION_STATE.UNINITIALISED) {
if (!hasNetwork_) {
// if there's no network connectivity, purge the old install/open
ServerRequest req = requestQueue_.peek();
if (req != null && (req instanceof ServerRequestRegisterInstall) || (req instanceof ServerRequestRegisterOpen)) {
requestQueue_.dequeue();
}
} else {
if (!requestQueue_.containsClose()) {
ServerRequest req = new ServerRequestRegisterClose(context_);
handleNewRequest(req);
}
}
initState_ = SESSION_STATE.UNINITIALISED;
}
}
private boolean readAndStripParam(Uri data, Activity activity) {
// Capture the intent URI and extra for analytics in case started by external intents such as google app search
try {
if (data != null) {
prefHelper_.setExternalIntentUri(data.toString());
}
if (activity != null && activity.getIntent() != null && activity.getIntent().getExtras() != null) {
Bundle bundle = activity.getIntent().getExtras();
Set<String> extraKeys = bundle.keySet();
if (extraKeys.size() > 0) {
JSONObject extrasJson = new JSONObject();
for (String key : extraKeys) {
extrasJson.put(key, bundle.get(key));
}
prefHelper_.setExternalIntentExtra(extrasJson.toString());
}
}
} catch (Exception ignore) {
}
//Check for any push identifier in case app is launched by a push notification
if (activity != null && activity.getIntent() != null && activity.getIntent().getExtras() != null) {
String pushIdentifier = activity.getIntent().getExtras().getString(Defines.Jsonkey.AndroidPushNotificationKey.getKey());
if (pushIdentifier != null && pushIdentifier.length() > 0) {
prefHelper_.setPushIdentifier(pushIdentifier);
return false;
}
}
//Check for link click id or app link
if (data != null && data.isHierarchical() && activity != null) {
if (data.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey()) != null) {
prefHelper_.setLinkClickIdentifier(data.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey()));
String paramString = "link_click_id=" + data.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey());
String uriString = activity.getIntent().getDataString();
if (data.getQuery().length() == paramString.length()) {
paramString = "\\?" + paramString;
} else if ((uriString.length() - paramString.length()) == uriString.indexOf(paramString)) {
paramString = "&" + paramString;
} else {
paramString = paramString + "&";
}
Uri newData = Uri.parse(uriString.replaceFirst(paramString, ""));
activity.getIntent().setData(newData);
return true;
} else {
// Check if the clicked url is an app link pointing to this app
String scheme = data.getScheme();
if (scheme != null) {
if ((scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https"))
&& data.getHost() != null && data.getHost().length() > 0) {
prefHelper_.setAppLink(data.toString());
return false;
}
}
}
}
return false;
}
/**
* <p>Identifies the current user to the Branch API by supplying a unique identifier as a
* {@link String} value. No callback.</p>
*
* @param userId A {@link String} value containing the unique identifier of the user.
*/
public void setIdentity(@NonNull String userId) {
setIdentity(userId, null);
}
/**
* <p>Identifies the current user to the Branch API by supplying a unique identifier as a
* {@link String} value, with a callback specified to perform a defined action upon successful
* response to request.</p>
*
* @param userId A {@link String} value containing the unique identifier of the user.
* @param callback A {@link BranchReferralInitListener} callback instance that will return
* the data associated with the user id being assigned, if available.
*/
public void setIdentity(@NonNull String userId, @Nullable BranchReferralInitListener callback) {
ServerRequest req = new ServerRequestIdentifyUserRequest(context_, callback, userId);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
} else {
if (((ServerRequestIdentifyUserRequest) req).isExistingID()) {
((ServerRequestIdentifyUserRequest) req).handleUserExist(branchReferral_);
}
}
}
/**
* Indicates whether or not this user has a custom identity specified for them. Note that this is independent of installs.
* If you call setIdentity, this device will have that identity associated with this user until logout is called.
* This includes persisting through uninstalls, as we track device id.
*
* @return A {@link Boolean} value that will return <i>true</i> only if user already has an identity.
*/
public boolean isUserIdentified() {
return !prefHelper_.getIdentity().equals(PrefHelper.NO_STRING_VALUE);
}
/**
* <p>This method should be called if you know that a different person is about to use the app. For example,
* if you allow users to log out and let their friend use the app, you should call this to notify Branch
* to create a new user for this device. This will clear the first and latest params, as a new session is created.</p>
*/
public void logout() {
logout(null);
}
/**
* <p>This method should be called if you know that a different person is about to use the app. For example,
* if you allow users to log out and let their friend use the app, you should call this to notify Branch
* to create a new user for this device. This will clear the first and latest params, as a new session is created.</p>
*
* @param callback An instance of {@link io.branch.referral.Branch.LogoutStatusListener} to callback with the logout operation status.
*/
public void logout(LogoutStatusListener callback) {
ServerRequest req = new ServerRequestLogout(context_, callback);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
@Deprecated
public void loadActionCounts() {
//noinspection deprecation
loadActionCounts(null);
}
@Deprecated
public void loadActionCounts(BranchReferralStateChangedListener callback) {
ServerRequest req = new ServerRequestGetReferralCount(context_, callback);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>Fire-and-forget retrieval of rewards for the current session. Without a callback.</p>
*/
public void loadRewards() {
loadRewards(null);
}
/**
* <p>Retrieves rewards for the current session, with a callback to perform a predefined
* action following successful report of state change. You'll then need to call getCredits
* in the callback to update the credit totals in your UX.</p>
*
* @param callback A {@link BranchReferralStateChangedListener} callback instance that will
* trigger actions defined therein upon a referral state change.
*/
public void loadRewards(BranchReferralStateChangedListener callback) {
ServerRequest req = new ServerRequestGetRewards(context_, callback);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>Retrieve the number of credits available for the "default" bucket.</p>
*
* @return An {@link Integer} value of the number credits available in the "default" bucket.
*/
public int getCredits() {
return prefHelper_.getCreditCount();
}
/**
* Returns an {@link Integer} of the number of credits available for use within the supplied
* bucket name.
*
* @param bucket A {@link String} value indicating the name of the bucket to get credits for.
* @return An {@link Integer} value of the number credits available in the specified
* bucket.
*/
public int getCreditsForBucket(String bucket) {
return prefHelper_.getCreditCount(bucket);
}
@Deprecated
public int getTotalCountsForAction(@NonNull String action) {
return prefHelper_.getActionTotalCount(action);
}
@Deprecated
public int getUniqueCountsForAction(@NonNull String action) {
return prefHelper_.getActionUniqueCount(action);
}
/**
* <p>Redeems the specified number of credits from the "default" bucket, if there are sufficient
* credits within it. If the number to redeem exceeds the number available in the bucket, all of
* the available credits will be redeemed instead.</p>
*
* @param count A {@link Integer} specifying the number of credits to attempt to redeem from
* the bucket.
*/
public void redeemRewards(int count) {
redeemRewards(Defines.Jsonkey.DefaultBucket.getKey(), count, null);
}
/**
* <p>Redeems the specified number of credits from the "default" bucket, if there are sufficient
* credits within it. If the number to redeem exceeds the number available in the bucket, all of
* the available credits will be redeemed instead.</p>
*
* @param count A {@link Integer} specifying the number of credits to attempt to redeem from
* the bucket.
* @param callback A {@link BranchReferralStateChangedListener} callback instance that will
* trigger actions defined therein upon a executing redeem rewards.
*/
public void redeemRewards(int count, BranchReferralStateChangedListener callback) {
redeemRewards(Defines.Jsonkey.DefaultBucket.getKey(), count, callback);
}
/**
* <p>Redeems the specified number of credits from the named bucket, if there are sufficient
* credits within it. If the number to redeem exceeds the number available in the bucket, all of
* the available credits will be redeemed instead.</p>
*
* @param bucket A {@link String} value containing the name of the referral bucket to attempt
* to redeem credits from.
* @param count A {@link Integer} specifying the number of credits to attempt to redeem from
* the specified bucket.
*/
public void redeemRewards(@NonNull final String bucket, final int count) {
redeemRewards(bucket, count, null);
}
/**
* <p>Redeems the specified number of credits from the named bucket, if there are sufficient
* credits within it. If the number to redeem exceeds the number available in the bucket, all of
* the available credits will be redeemed instead.</p>
*
* @param bucket A {@link String} value containing the name of the referral bucket to attempt
* to redeem credits from.
* @param count A {@link Integer} specifying the number of credits to attempt to redeem from
* the specified bucket.
* @param callback A {@link BranchReferralStateChangedListener} callback instance that will
* trigger actions defined therein upon a executing redeem rewards.
*/
public void redeemRewards(@NonNull final String bucket, final int count, BranchReferralStateChangedListener callback) {
ServerRequestRedeemRewards req = new ServerRequestRedeemRewards(context_, bucket, count, callback);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>Gets the credit history of the specified bucket and triggers a callback to handle the
* response.</p>
*
* @param callback A {@link BranchListResponseListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*/
public void getCreditHistory(BranchListResponseListener callback) {
getCreditHistory(null, null, 100, CreditHistoryOrder.kMostRecentFirst, callback);
}
/**
* <p>Gets the credit history of the specified bucket and triggers a callback to handle the
* response.</p>
*
* @param bucket A {@link String} value containing the name of the referral bucket that the
* code will belong to.
* @param callback A {@link BranchListResponseListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*/
public void getCreditHistory(@NonNull final String bucket, BranchListResponseListener callback) {
getCreditHistory(bucket, null, 100, CreditHistoryOrder.kMostRecentFirst, callback);
}
/**
* <p>Gets the credit history of the specified bucket and triggers a callback to handle the
* response.</p>
*
* @param afterId A {@link String} value containing the ID of the history record to begin after.
* This allows for a partial history to be retrieved, rather than the entire
* credit history of the bucket.
* @param length A {@link Integer} value containing the number of credit history records to
* return.
* @param order A {@link CreditHistoryOrder} object indicating which order the results should
* be returned in.
* <p/>
* <p>Valid choices:</p>
* <p/>
* <ul>
* <li>{@link CreditHistoryOrder#kMostRecentFirst}</li>
* <li>{@link CreditHistoryOrder#kLeastRecentFirst}</li>
* </ul>
* @param callback A {@link BranchListResponseListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*/
public void getCreditHistory(@NonNull final String afterId, final int length, @NonNull final CreditHistoryOrder order, BranchListResponseListener callback) {
getCreditHistory(null, afterId, length, order, callback);
}
/**
* <p>Gets the credit history of the specified bucket and triggers a callback to handle the
* response.</p>
*
* @param bucket A {@link String} value containing the name of the referral bucket that the
* code will belong to.
* @param afterId A {@link String} value containing the ID of the history record to begin after.
* This allows for a partial history to be retrieved, rather than the entire
* credit history of the bucket.
* @param length A {@link Integer} value containing the number of credit history records to
* return.
* @param order A {@link CreditHistoryOrder} object indicating which order the results should
* be returned in.
* <p/>
* <p>Valid choices:</p>
* <p/>
* <ul>
* <li>{@link CreditHistoryOrder#kMostRecentFirst}</li>
* <li>{@link CreditHistoryOrder#kLeastRecentFirst}</li>
* </ul>
* @param callback A {@link BranchListResponseListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
*/
public void getCreditHistory(final String bucket, final String afterId, final int length, @NonNull final CreditHistoryOrder order, BranchListResponseListener callback) {
ServerRequest req = new ServerRequestGetRewardHistory(context_, bucket, afterId, length, order, callback);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>A void call to indicate that the user has performed a specific action and for that to be
* reported to the Branch API, with additional app-defined meta data to go along with that action.</p>
*
* @param action A {@link String} value to be passed as an action that the user has carried
* out. For example "registered" or "logged in".
* @param metadata A {@link JSONObject} containing app-defined meta-data to be attached to a
* user action that has just been completed.
*/
public void userCompletedAction(@NonNull final String action, JSONObject metadata) {
if (metadata != null)
metadata = BranchUtil.filterOutBadCharacters(metadata);
ServerRequest req = new ServerRequestActionCompleted(context_, action, metadata);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>A void call to indicate that the user has performed a specific action and for that to be
* reported to the Branch API.</p>
*
* @param action A {@link String} value to be passed as an action that the user has carried
* out. For example "registered" or "logged in".
*/
public void userCompletedAction(final String action) {
userCompletedAction(action, null);
}
/**
* <p>Returns the parameters associated with the link that referred the user. This is only set once,
* the first time the user is referred by a link. Think of this as the user referral parameters.
* It is also only set if isReferrable is equal to true, which by default is only true
* on a fresh install (not upgrade or reinstall). This will change on setIdentity (if the
* user already exists from a previous device) and logout.</p>
*
* @return A {@link JSONObject} containing the install-time parameters as configured
* locally.
*/
public JSONObject getFirstReferringParams() {
String storedParam = prefHelper_.getInstallParams();
return convertParamsStringToDictionary(storedParam);
}
/**
* <p>Returns the parameters associated with the link that referred the session. If a user
* clicks a link, and then opens the app, initSession will return the paramters of the link
* and then set them in as the latest parameters to be retrieved by this method. By default,
* sessions persist for the duration of time that the app is in focus. For example, if you
* minimize the app, these parameters will be cleared when closeSession is called.</p>
*
* @return A {@link JSONObject} containing the latest referring parameters as
* configured locally.
*/
public JSONObject getLatestReferringParams() {
String storedParam = prefHelper_.getSessionParams();
return convertParamsStringToDictionary(storedParam);
}
@Deprecated
public String getShortUrlSync() {
//noinspection deprecation
return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, BranchUtil.stringifyAndAddSource(new JSONObject()), null, false);
}
@Deprecated
public String getShortUrlSync(JSONObject params) {
//noinspection deprecation
return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, BranchUtil.formatAndStringifyLinkParam(params), null, false);
}
@Deprecated
public String getShortUrlSync(String channel, String feature, String stage, JSONObject params) {
//noinspection deprecation
return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), null, false);
}
@Deprecated
public String getShortUrlSync(String alias, String channel, String feature, String stage, JSONObject params) {
//noinspection deprecation
return generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), null, false);
}
@Deprecated
public String getShortUrlSync(int type, String channel, String feature, String stage, JSONObject params) {
//noinspection deprecation
return generateShortLink(null, type, 0, null, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), null, false);
}
@Deprecated
public String getShortUrlSync(String channel, String feature, String stage, JSONObject params, int duration) {
//noinspection deprecation
return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, null, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), null, false);
}
@Deprecated
public String getShortUrlSync(Collection<String> tags, String channel, String feature, String stage, JSONObject params) {
//noinspection deprecation
return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), null, false);
}
@Deprecated
public String getShortUrlSync(String alias, Collection<String> tags, String channel, String feature, String stage, JSONObject params) {
//noinspection deprecation
return generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), null, false);
}
@Deprecated
public String getShortUrlSync(int type, Collection<String> tags, String channel, String feature, String stage, JSONObject params) {
//noinspection deprecation
return generateShortLink(null, type, 0, tags, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), null, false);
}
@Deprecated
public String getShortUrlSync(Collection<String> tags, String channel, String feature, String stage, JSONObject params, int duration) {
//noinspection deprecation
return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, tags, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), null, false);
}
@Deprecated
public void getShortUrl(BranchLinkCreateListener callback) {
//noinspection deprecation
generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, BranchUtil.stringifyAndAddSource(new JSONObject()), callback, true);
}
@Deprecated
public void getShortUrl(JSONObject params, BranchLinkCreateListener callback) {
//noinspection deprecation
generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, BranchUtil.formatAndStringifyLinkParam(params), callback, true);
}
@Deprecated
public void getShortUrl(String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) {
//noinspection deprecation
generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), callback, true);
}
@Deprecated
public void getShortUrl(String alias, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) {
//noinspection deprecation
generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), callback, true);
}
@Deprecated
public void getShortUrl(int type, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) {
//noinspection deprecation
generateShortLink(null, type, 0, null, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), callback, true);
}
@Deprecated
public void getShortUrl(String channel, String feature, String stage, JSONObject params, int duration, BranchLinkCreateListener callback) {
//noinspection deprecation
generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, null, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), callback, true);
}
@Deprecated
public void getShortUrl(Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) {
//noinspection deprecation
generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), callback, true);
}
@Deprecated
public void getShortUrl(String alias, Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) {
//noinspection deprecation
generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), callback, true);
}
@Deprecated
public void getShortUrl(int type, Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) {
//noinspection deprecation
generateShortLink(null, type, 0, tags, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), callback, true);
}
@Deprecated
public void getShortUrl(Collection<String> tags, String channel, String feature, String stage, JSONObject params, int duration, BranchLinkCreateListener callback) {
//noinspection deprecation
generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, tags, channel, feature, stage, BranchUtil.formatAndStringifyLinkParam(params), callback, true);
}
@Deprecated
private String generateShortLink(final String alias, final int type, final int duration, final Collection<String> tags, final String channel, final String feature, final String stage, final String params, BranchLinkCreateListener callback, boolean async) {
ServerRequestCreateUrl req = new ServerRequestCreateUrl(context_, alias, type, duration, tags,
channel, feature, stage,
params, callback, async);
if (!req.constructError_ && !req.handleErrors(context_)) {
if (linkCache_.containsKey(req.getLinkPost())) {
String url = linkCache_.get(req.getLinkPost());
if (callback != null) {
callback.onLinkCreate(url, null);
}
return url;
} else {
if (async) {
generateShortLinkAsync(req);
} else {
return generateShortLinkSync(req);
}
}
}
return null;
}
/**
* <p> Generates a shorl url fot the given {@link ServerRequestCreateUrl} object </p>
*
* @param req An instance of {@link ServerRequestCreateUrl} with parameters create the short link.
* @return A url created with the given request if the request is synchronous else null.
* Note : This method can be used only internally. Use {@link BranchUrlBuilder} for creating short urls.
*/
public String generateShortLinkInternal(ServerRequestCreateUrl req) {
if (!req.constructError_ && !req.handleErrors(context_)) {
if (linkCache_.containsKey(req.getLinkPost())) {
String url = linkCache_.get(req.getLinkPost());
req.onUrlAvailable(url);
return url;
} else {
if (req.isAsync()) {
generateShortLinkAsync(req);
} else {
return generateShortLinkSync(req);
}
}
}
return null;
}
/**
* <p>Configures and requests a referral URL (feature = referral) to be generated by the Branch servers.</p>
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
* @param callback A {@link BranchLinkCreateListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
* @see BranchLinkData
* @see BranchLinkData#putChannel(String)
* @see BranchLinkData#putParams(String)
* @see BranchLinkCreateListener
* @deprecated use {@link BranchReferralUrlBuilder} instead.
*/
@Deprecated
public void getReferralUrl(String channel, JSONObject params, BranchLinkCreateListener callback) {
//noinspection deprecation
generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_REFERRAL, null, BranchUtil.formatAndStringifyLinkParam(params), callback, true);
}
/**
* <p>Configures and requests a referral URL (feature = referral) to be generated by the Branch servers.</p>
*
* @param tags An iterable {@link Collection} of {@link String} tags associated with a deep
* link.
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
* @param callback A {@link BranchLinkCreateListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
* @see BranchLinkData
* @see BranchLinkData#putTags(Collection)
* @see BranchLinkData#putChannel(String)
* @see BranchLinkData#putParams(String)
* @see BranchLinkCreateListener
* @deprecated use {@link BranchReferralUrlBuilder} instead.
*/
@Deprecated
public void getReferralUrl(Collection<String> tags, String channel, JSONObject params, BranchLinkCreateListener callback) {
//noinspection deprecation
generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_REFERRAL, null, BranchUtil.formatAndStringifyLinkParam(params), callback, true);
}
/**
* <p>Configures and requests a referral URL to be generated by the Branch servers, via a synchronous
* call; with a duration specified within which an app session should be matched to the link.</p>
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
* @return A {@link String} containing the resulting referral URL.
* @deprecated use {@link BranchReferralUrlBuilder} instead.
*/
@Deprecated
public String getReferralUrlSync(String channel, JSONObject params) {
//noinspection deprecation
return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_REFERRAL, null, BranchUtil.formatAndStringifyLinkParam(params), null, false);
}
/**
* <p>Configures and requests a referral URL to be generated by the Branch servers, via a synchronous
* call; with a duration specified within which an app session should be matched to the link.</p>
*
* @param tags An iterable {@link Collection} of {@link String} tags associated with a deep
* link.
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
* @return A {@link String} containing the resulting referral URL.
* @deprecated use {@link BranchReferralUrlBuilder} instead.
*/
@Deprecated
public String getReferralUrlSync(Collection<String> tags, String channel, JSONObject params) {
//noinspection deprecation
return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_REFERRAL, null, BranchUtil.formatAndStringifyLinkParam(params), null, false);
}
/**
* <p>Configures and requests a content URL (defined as feature = sharing) to be generated by the Branch servers.</p>
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
* @param callback A {@link BranchLinkCreateListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
* @see BranchLinkData
* @see BranchLinkData#putChannel(String)
* @see BranchLinkData#putParams(String)
* @see BranchLinkCreateListener
* @deprecated use {@link BranchContentUrlBuilder} instead.
*/
@Deprecated
public void getContentUrl(String channel, JSONObject params, BranchLinkCreateListener callback) {
//noinspection deprecation
generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_SHARE, null, BranchUtil.formatAndStringifyLinkParam(params), callback, true);
}
/**
* <p>Configures and requests a content URL (defined as feature = sharing) to be generated by the Branch servers.</p>
*
* @param tags An iterable {@link Collection} of {@link String} tags associated with a deep
* link.
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
* @param callback A {@link BranchLinkCreateListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a create link request.
* @see BranchLinkData
* @see BranchLinkData#putTags(Collection)
* @see BranchLinkData#putChannel(String)
* @see BranchLinkData#putParams(String)
* @see BranchLinkCreateListener
* @deprecated use {@link BranchContentUrlBuilder} instead.
*/
@Deprecated
public void getContentUrl(Collection<String> tags, String channel, JSONObject params, BranchLinkCreateListener callback) {
//noinspection deprecation
generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_SHARE, null, BranchUtil.formatAndStringifyLinkParam(params), callback, true);
}
/**
* <p>Configures and requests a content URL (defined as feature = sharing) to be generated by the Branch servers, via a synchronous
* call</p>
*
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
* @return A {@link String} containing the resulting content URL.
* @deprecated use {@link BranchContentUrlBuilder} instead.
*/
@Deprecated
public String getContentUrlSync(String channel, JSONObject params) {
//noinspection deprecation
return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_SHARE, null, BranchUtil.formatAndStringifyLinkParam(params), null, false);
}
/**
* <p>Configures and requests a content URL (defined as feature = sharing) to be generated by the Branch servers, via a synchronous
* call</p>
*
* @param tags An iterable {@link Collection} of {@link String} tags associated with a deep
* link.
* @param channel A {@link String} denoting the channel that the link belongs to. Should not
* exceed 128 characters.
* @param params A {@link JSONObject} value containing the deep linked params associated with
* the link that will be passed into a new app session when clicked
* @return A {@link String} containing the resulting content URL.
* @deprecated use {@link BranchContentUrlBuilder} instead.
*/
@Deprecated
public String getContentUrlSync(Collection<String> tags, String channel, JSONObject params) {
//noinspection deprecation
return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_SHARE, null, BranchUtil.formatAndStringifyLinkParam(params), null, false);
}
/**
* <p>Configures and requests a referral code to be generated by the Branch servers.</p>
*
* @param callback A {@link BranchReferralInitListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a referral code request.
* @deprecated This method has been deprecated. v1.10.1 onwards Branch will not support any improvements or modifications for referral code functionality.
*/
@Deprecated
public void getReferralCode(BranchReferralInitListener callback) {
ServerRequest req = new ServerRequestGetReferralCode(context_, callback);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>Configures and requests a referral code to be generated by the Branch servers.</p>
*
* @param amount An {@link Integer} value of credits associated with this referral code.
* @param callback A {@link BranchReferralInitListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a referral code request.
* @deprecated This method has been deprecated. v1.10.1 onwards Branch will not support any improvements or modifications for referral code functionality.
*/
@Deprecated
public void getReferralCode(final int amount, BranchReferralInitListener callback) {
//noinspection deprecation
this.getReferralCode(null, amount, null, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback);
}
/**
* <p>Configures and requests a referral code to be generated by the Branch servers.</p>
*
* @param prefix A {@link String} containing the developer-specified prefix code to be applied
* to the start of a referral code. e.g. for code OFFER4867, the prefix would
* be "OFFER".
* @param amount An {@link Integer} value of credits associated with this referral code.
* @param callback A {@link BranchReferralInitListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a referral code request.
* @deprecated This method has been deprecated. v1.10.1 onwards Branch will not support any improvements or modifications for referral code functionality.
*/
@Deprecated
public void getReferralCode(final String prefix, final int amount, BranchReferralInitListener callback) {
//noinspection deprecation
this.getReferralCode(prefix, amount, null, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback);
}
/**
* <p>Configures and requests a referral code to be generated by the Branch servers.</p>
*
* @param amount An {@link Integer} value of credits associated with this referral code.
* @param expiration Optional expiration {@link Date} of the offer code.
* @param callback A {@link BranchReferralInitListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a referral code
* request.
* @deprecated This method has been deprecated. v1.10.1 onwards Branch will not support any improvements or modifications for referral code functionality.
*/
@Deprecated
public void getReferralCode(final int amount, final Date expiration, BranchReferralInitListener callback) {
//noinspection deprecation
this.getReferralCode(null, amount, expiration, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback);
}
/**
* <p>Configures and requests a referral code to be generated by the Branch servers.</p>
*
* @param prefix A {@link String} containing the developer-specified prefix code to be
* applied to the start of a referral code. e.g. for code OFFER4867, the
* prefix would be "OFFER".
* @param amount An {@link Integer} value of credits associated with this referral code.
* @param expiration Optional expiration {@link Date} of the offer code.
* @param callback A {@link BranchReferralInitListener} callback instance that will trigger
* actions defined therein upon receipt of a response to a referral code
* request.
* @deprecated This method has been deprecated. v1.10.1 onwards Branch will not support any improvements or modifications for referral code functionality.
*/
@Deprecated
public void getReferralCode(final String prefix, final int amount, final Date expiration, BranchReferralInitListener callback) {
//noinspection deprecation
this.getReferralCode(prefix, amount, expiration, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback);
}
/**
* <p>Configures and requests a referral code to be generated by the Branch servers.</p>
*
* @param prefix A {@link String} containing the developer-specified prefix code to be
* applied to the start of a referral code. e.g. for code OFFER4867, the
* prefix would be "OFFER".
* @param amount An {@link Integer} value of credits associated with this referral code.
* @param calculationType The type of referral calculation. i.e.
* {@link #LINK_TYPE_UNLIMITED_USE} or
* {@link #LINK_TYPE_ONE_TIME_USE}
* @param location The user to reward for applying the referral code.
* <p/>
* <p>Valid options:</p>
* <p/>
* <ul>
* <li>{@link #REFERRAL_CODE_LOCATION_REFERREE}</li>
* <li>{@link #REFERRAL_CODE_LOCATION_REFERRING_USER}</li>
* <li>{@link #REFERRAL_CODE_LOCATION_BOTH}</li>
* </ul>
* @param callback A {@link BranchReferralInitListener} callback instance that will
* trigger actions defined therein upon receipt of a response to a
* referral code request.
* @deprecated This method has been deprecated. v1.10.1 onwards Branch will not support any improvements or modifications for referral code functionality.
*/
@Deprecated
public void getReferralCode(final String prefix, final int amount, final int calculationType, final int location, BranchReferralInitListener callback) {
//noinspection deprecation
this.getReferralCode(prefix, amount, null, REFERRAL_BUCKET_DEFAULT, calculationType, location, callback);
}
/**
* <p>Configures and requests a referral code to be generated by the Branch servers.</p>
*
* @param prefix A {@link String} containing the developer-specified prefix code to
* be applied to the start of a referral code. e.g. for code OFFER4867,
* the prefix would be "OFFER".
* @param amount An {@link Integer} value of credits associated with this referral code.
* @param expiration Optional expiration {@link Date} of the offer code.
* @param bucket A {@link String} value containing the name of the referral bucket
* that the code will belong to.
* @param calculationType The type of referral calculation. i.e.
* {@link #LINK_TYPE_UNLIMITED_USE} or
* {@link #LINK_TYPE_ONE_TIME_USE}
* @param location The user to reward for applying the referral code.
* <p/>
* <p>Valid options:</p>
* <p/>
* <ul>
* <li>{@link #REFERRAL_CODE_LOCATION_REFERREE}</li>
* <li>{@link #REFERRAL_CODE_LOCATION_REFERRING_USER}</li>
* <li>{@link #REFERRAL_CODE_LOCATION_BOTH}</li>
* </ul>
* @param callback A {@link BranchReferralInitListener} callback instance that will
* trigger actions defined therein upon receipt of a response to a
* referral code request.
* @deprecated This method has been deprecated. v1.10.1 onwards Branch will not support any improvements or modifications for referral code functionality.
*/
@Deprecated
public void getReferralCode(final String prefix, final int amount, final Date expiration, final String bucket, final int calculationType, final int location, BranchReferralInitListener callback) {
String date = null;
if (expiration != null)
date = convertDate(expiration);
ServerRequest req = new ServerRequestGetReferralCode(context_, prefix, amount, date, bucket,
calculationType, location, callback);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>Validates the supplied referral code on initialisation without applying it to the current
* session.</p>
*
* @param code A {@link String} object containing the referral code supplied.
* @param callback A {@link BranchReferralInitListener} callback to handle the server response
* of the referral submission request.
* @deprecated This method has been deprecated. v1.10.1 onwards Branch will not support any improvements or modifications for referral code functionality.
*/
@Deprecated
public void validateReferralCode(final String code, BranchReferralInitListener callback) {
ServerRequest req = new ServerRequestValidateReferralCode(context_, callback, code);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>Applies a supplied referral code to the current user session upon initialisation.</p>
*
* @param code A {@link String} object containing the referral code supplied.
* @param callback A {@link BranchReferralInitListener} callback to handle the server
* response of the referral submission request.
* @see BranchReferralInitListener
* @deprecated This method has been deprecated. v1.10.1 onwards Branch will not support any improvements or modifications for referral code functionality.
*/
@Deprecated
public void applyReferralCode(final String code, final BranchReferralInitListener callback) {
ServerRequest req = new ServerRequestApplyReferralCode(context_, callback, code);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
/**
* <p>Creates options for sharing a link with other Applications. Creates a link with given attributes and shares with the
* user selected clients.</p>
*
* @param builder A {@link io.branch.referral.Branch.ShareLinkBuilder} instance to build share link.
*/
private void shareLink(ShareLinkBuilder builder) {
//Cancel any existing sharing in progress.
if (shareLinkManager_ != null) {
shareLinkManager_.cancelShareLinkDialog(true);
}
shareLinkManager_ = new ShareLinkManager();
shareLinkManager_.shareLink(builder);
}
/**
* <p>Cancel current share link operation and Application selector dialog. If your app is not using auto session management, make sure you are
* calling this method before your activity finishes inorder to prevent any window leak. </p>
*
* @param animateClose A {@link Boolean} to specify whether to close the dialog with an animation.
* A value of true will close the dialog with an animation. Setting this value
* to false will close the Dialog immediately.
*/
public void cancelShareLinkDialog(boolean animateClose) {
if (shareLinkManager_ != null) {
shareLinkManager_.cancelShareLinkDialog(animateClose);
}
}
// PRIVATE FUNCTIONS
private String convertDate(Date date) {
return android.text.format.DateFormat.format("yyyy-MM-dd", date).toString();
}
private String generateShortLinkSync(ServerRequestCreateUrl req) {
if (initState_ == SESSION_STATE.INITIALISED) {
ServerResponse response = null;
try {
int timeOut = prefHelper_.getTimeout() + 2000; // Time out is set to slightly more than link creation time to prevent any edge case
response = new getShortLinkTask().execute(req).get(timeOut, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException ignore) {
}
String url = req.getLongUrl();
if (response != null && response.getStatusCode() == HttpURLConnection.HTTP_OK) {
try {
url = response.getObject().getString("url");
if (response.getLinkData() != null) {
linkCache_.put(response.getLinkData(), url);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return url;
} else {
Log.i("BranchSDK", "Branch Warning: User session has not been initialized");
}
return null;
}
private void generateShortLinkAsync(final ServerRequest req) {
handleNewRequest(req);
}
private JSONObject convertParamsStringToDictionary(String paramString) {
if (paramString.equals(PrefHelper.NO_STRING_VALUE)) {
return new JSONObject();
} else {
try {
return new JSONObject(paramString);
} catch (JSONException e) {
byte[] encodedArray = Base64.decode(paramString.getBytes(), Base64.NO_WRAP);
try {
return new JSONObject(new String(encodedArray));
} catch (JSONException ex) {
ex.printStackTrace();
return new JSONObject();
}
}
}
}
/**
* <p>Schedules a repeating threaded task to get the following details and report them to the
* Branch API <b>once a week</b>:</p>
* <p/>
* <pre style="background:#fff;padding:10px;border:2px solid silver;">
* int interval = 7 * 24 * 60 * 60;
* appListingSchedule_ = scheduler.scheduleAtFixedRate(
* periodicTask, (days * 24 + hours) * 60 * 60, interval, TimeUnit.SECONDS);</pre>
* <p/>
* <ul>
* <li>{@link SystemObserver#getOS()}</li>
* <li>{@link SystemObserver#getListOfApps()}</li>
* </ul>
*
* @see {@link SystemObserver}
* @see {@link PrefHelper}
*/
private void scheduleListOfApps() {
ScheduledThreadPoolExecutor scheduler = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);
Runnable periodicTask = new Runnable() {
@Override
public void run() {
ServerRequest req = new ServerRequestSendAppList(context_);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
};
Date date = new Date();
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(date);
int days = Calendar.SATURDAY - calendar.get(Calendar.DAY_OF_WEEK); // days to Saturday
int hours = 2 - calendar.get(Calendar.HOUR_OF_DAY); // hours to 2am, can be negative
if (days == 0 && hours < 0) {
days = 7;
}
int interval = 7 * 24 * 60 * 60;
appListingSchedule_ = scheduler.scheduleAtFixedRate(periodicTask, (days * 24 + hours) * 60 * 60, interval, TimeUnit.SECONDS);
}
private void processNextQueueItem() {
try {
serverSema_.acquire();
if (networkCount_ == 0 && requestQueue_.getSize() > 0) {
networkCount_ = 1;
ServerRequest req = requestQueue_.peek();
serverSema_.release();
if (req != null) {
//All request except Install request need a valid IdentityID
if (!(req instanceof ServerRequestRegisterInstall) && !hasUser()) {
Log.i("BranchSDK", "Branch Error: User session has not been initialized!");
networkCount_ = 0;
handleFailure(requestQueue_.getSize() - 1, BranchError.ERR_NO_SESSION);
}
//All request except open and install need a session to execute
else if (!(req instanceof ServerRequestInitSession) && (!hasSession() || !hasDeviceFingerPrint())) {
networkCount_ = 0;
handleFailure(requestQueue_.getSize() - 1, BranchError.ERR_NO_SESSION);
} else {
BranchPostTask postTask = new BranchPostTask(req);
postTask.execute();
}
} else {
requestQueue_.remove(null); //Inc ase there is any request nullified remove it.
}
} else {
serverSema_.release();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void handleFailure(int index, int statusCode) {
ServerRequest req;
if (index >= requestQueue_.getSize()) {
req = requestQueue_.peekAt(requestQueue_.getSize() - 1);
} else {
req = requestQueue_.peekAt(index);
}
handleFailure(req, statusCode);
}
private void handleFailure(final ServerRequest req, int statusCode) {
if (req == null)
return;
req.handleFailure(statusCode, "");
}
private void updateAllRequestsInQueue() {
try {
for (int i = 0; i < requestQueue_.getSize(); i++) {
ServerRequest req = requestQueue_.peekAt(i);
if (req.getPost() != null) {
Iterator<?> keys = req.getPost().keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if (key.equals(Defines.Jsonkey.SessionID.getKey())) {
req.getPost().put(key, prefHelper_.getSessionID());
} else if (key.equals(Defines.Jsonkey.IdentityID.getKey())) {
req.getPost().put(key, prefHelper_.getIdentityID());
} else if (key.equals(Defines.Jsonkey.DeviceFingerprintID.getKey())) {
req.getPost().put(key, prefHelper_.getDeviceFingerPrintID());
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void clearCloseTimer() {
if (rotateCloseTimer == null)
return;
rotateCloseTimer.cancel();
rotateCloseTimer.purge();
rotateCloseTimer = new Timer();
}
private void clearTimer() {
if (closeTimer == null)
return;
closeTimer.cancel();
closeTimer.purge();
closeTimer = new Timer();
}
private void keepAlive() {
keepAlive_ = true;
synchronized (lock) {
clearTimer();
closeTimer.schedule(new TimerTask() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
keepAlive_ = false;
}
}).start();
}
}, SESSION_KEEPALIVE);
}
}
private boolean hasSession() {
return !prefHelper_.getSessionID().equals(PrefHelper.NO_STRING_VALUE);
}
private boolean hasDeviceFingerPrint() {
return !prefHelper_.getDeviceFingerPrintID().equals(PrefHelper.NO_STRING_VALUE);
}
private boolean hasUser() {
return !prefHelper_.getIdentityID().equals(PrefHelper.NO_STRING_VALUE);
}
private void insertRequestAtFront(ServerRequest req) {
if (networkCount_ == 0) {
requestQueue_.insert(req, 0);
} else {
requestQueue_.insert(req, 1);
}
}
private void registerInstallOrOpen(ServerRequest req, BranchReferralInitListener callback) {
// If there isn't already an Open / Install request, add one to the queue
if (!requestQueue_.containsInstallOrOpen()) {
insertRequestAtFront(req);
}
// If there is already one in the queue, make sure it's in the front.
// Make sure a callback is associated with this request. This callback can
// be cleared if the app is terminated while an Open/Install is pending.
else {
// Update the callback to the latest one in initsession call
requestQueue_.setInstallOrOpenCallback(callback);
requestQueue_.moveInstallOrOpenToFront(req, networkCount_, callback);
}
processNextQueueItem();
}
private void initializeSession(BranchReferralInitListener callback) {
if ((prefHelper_.getBranchKey() == null || prefHelper_.getBranchKey().equalsIgnoreCase(PrefHelper.NO_STRING_VALUE))
&& (prefHelper_.getAppKey() == null || prefHelper_.getAppKey().equalsIgnoreCase(PrefHelper.NO_STRING_VALUE))) {
initState_ = SESSION_STATE.UNINITIALISED;
//Report Key error on callback
if (callback != null) {
callback.onInitFinished(null, new BranchError("Trouble initializing Branch.", RemoteInterface.NO_BRANCH_KEY_STATUS));
}
Log.i("BranchSDK", "Branch Warning: Please enter your branch_key in your project's res/values/strings.xml!");
return;
} else if (prefHelper_.getBranchKey() != null && prefHelper_.getBranchKey().startsWith("key_test_")) {
Log.i("BranchSDK", "Branch Warning: You are using your test app's Branch Key. Remember to change it to live Branch Key during deployment.");
}
if (hasUser()) {
registerInstallOrOpen(new ServerRequestRegisterOpen(context_, callback, kRemoteInterface_.getSystemObserver()), callback);
} else {
registerInstallOrOpen(new ServerRequestRegisterInstall(context_, callback, kRemoteInterface_.getSystemObserver(), InstallListener.getInstallationID()), callback);
}
}
/**
* Handles execution of a new request other than open or install.
* Checks for the session initialisation and adds a install/Open request in front of this request
* if the request need session to execute.
*
* @param req The {@link ServerRequest} to execute
*/
public void handleNewRequest(ServerRequest req) {
//If not initialised put an open or install request in front of this request(only if this needs session)
if (initState_ != SESSION_STATE.INITIALISED && !(req instanceof ServerRequestInitSession)) {
if ((req instanceof ServerRequestLogout)) {
req.handleFailure(BranchError.ERR_NO_SESSION, "");
Log.i(TAG, "Branch is not initialized, cannot logout");
return;
}
if ((req instanceof ServerRequestRegisterClose)) {
Log.i(TAG, "Branch is not initialized, cannot close session");
return;
} else {
if (customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.USE_DEFAULT) {
initUserSessionInternal((BranchReferralInitListener) null, currentActivity_, true);
} else {
boolean isReferrable = customReferrableSettings_ == CUSTOM_REFERRABLE_SETTINGS.REFERRABLE;
initUserSessionInternal((BranchReferralInitListener) null, currentActivity_, isReferrable);
}
}
}
requestQueue_.enqueue(req);
processNextQueueItem();
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void setActivityLifeCycleObserver(Application application) {
try {
BranchActivityLifeCycleObserver activityLifeCycleObserver = new BranchActivityLifeCycleObserver();
/* Set an observer for activity life cycle events. */
application.unregisterActivityLifecycleCallbacks(activityLifeCycleObserver);
application.registerActivityLifecycleCallbacks(activityLifeCycleObserver);
isActivityLifeCycleCallbackRegistered_ = true;
} catch (NoSuchMethodError | NoClassDefFoundError Ex) {
isActivityLifeCycleCallbackRegistered_ = false;
isAutoSessionMode_ = false;
/* LifeCycleEvents are available only from API level 14. */
Log.w(TAG, new BranchError("", BranchError.ERR_API_LVL_14_NEEDED).getMessage());
}
}
/**
* <p>Class that observes activity life cycle events and determines when to start and stop
* session.</p>
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private class BranchActivityLifeCycleObserver implements Application.ActivityLifecycleCallbacks {
private int activityCnt_ = 0; //Keep the count of live activities.
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
}
@Override
public void onActivityStarted(Activity activity) {
if (activityCnt_ < 1) { // Check if this is the first Activity.If so start a session.
// Check if debug mode is set in manifest. If so enable debug.
if (BranchUtil.isTestModeEnabled(context_)) {
//noinspection deprecation
setDebug();
}
Uri intentData = null;
if (activity.getIntent() != null) {
intentData = activity.getIntent().getData();
}
initSessionWithData(intentData, activity); // indicate starting of session.
}
activityCnt_++;
}
@Override
public void onActivityResumed(Activity activity) {
currentActivity_ = activity;
//Set the activity for touch debug
if (prefHelper_.getTouchDebugging()) {
setTouchDebugInternal(activity);
}
}
@Override
public void onActivityPaused(Activity activity) {
clearTouchDebugInternal(activity);
/* Close any opened sharing dialog.*/
if (shareLinkManager_ != null) {
shareLinkManager_.cancelShareLinkDialog(true);
}
}
@Override
public void onActivityStopped(Activity activity) {
activityCnt_--; // Check if this is the last activity.If so stop
// session.
if (activityCnt_ < 1) {
closeSessionInternal();
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
if (currentActivity_ == activity) {
currentActivity_ = null;
}
}
}
/**
* <p>An Interface class that is implemented by all classes that make use of
* {@link BranchReferralInitListener}, defining a single method that takes a list of params in
* {@link JSONObject} format, and an error message of {@link BranchError} format that will be
* returned on failure of the request response.</p>
*
* @see JSONObject
* @see BranchError
*/
public interface BranchReferralInitListener {
void onInitFinished(JSONObject referringParams, BranchError error);
}
/**
* <p>An Interface class that is implemented by all classes that make use of
* {@link BranchUniversalReferralInitListener}, defining a single method that provides
* {@link BranchUniversalObject}, {@link LinkProperties} and an error message of {@link BranchError} format that will be
* returned on failure of the request response.
* In case of an error the value for {@link BranchUniversalObject} and {@link LinkProperties} are set to null.</p>
*
* @see BranchUniversalObject
* @see LinkProperties
* @see BranchError
*/
public interface BranchUniversalReferralInitListener {
void onInitFinished(BranchUniversalObject branchUniversalObject, LinkProperties linkProperties, BranchError error);
}
/**
* <p>An Interface class that is implemented by all classes that make use of
* {@link BranchReferralStateChangedListener}, defining a single method that takes a value of
* {@link Boolean} format, and an error message of {@link BranchError} format that will be
* returned on failure of the request response.</p>
*
* @see Boolean
* @see BranchError
*/
public interface BranchReferralStateChangedListener {
void onStateChanged(boolean changed, BranchError error);
}
/**
* <p>An Interface class that is implemented by all classes that make use of
* {@link BranchLinkCreateListener}, defining a single method that takes a URL
* {@link String} format, and an error message of {@link BranchError} format that will be
* returned on failure of the request response.</p>
*
* @see String
* @see BranchError
*/
public interface BranchLinkCreateListener {
void onLinkCreate(String url, BranchError error);
}
/**
* <p>An Interface class that is implemented by all classes that make use of
* {@link BranchLinkShareListener}, defining methods to listen for link sharing status.</p>
*/
public interface BranchLinkShareListener {
/**
* <p> Callback method to update when share link dialog is launched.</p>
*/
void onShareLinkDialogLaunched();
/**
* <p> Callback method to update when sharing dialog is dismissed.</p>
*/
void onShareLinkDialogDismissed();
/**
* <p> Callback method to update the sharing status. Called on sharing completed or on error.</p>
*
* @param sharedLink The link shared to the channel.
* @param sharedChannel Channel selected for sharing.
* @param error A {@link BranchError} to update errors, if there is any.
*/
void onLinkShareResponse(String sharedLink, String sharedChannel, BranchError error);
/**
* <p>Called when user select a channel for sharing a deep link.
* Branch will create a deep link for the selected channel and share with it after calling this
* method. On sharing complete, status is updated by onLinkShareResponse() callback. Consider
* having a sharing in progress UI if you wish to prevent user activity in the window between selecting a channel
* and sharing complete.</p>
*
* @param channelName Name of the selected application to share the link.
*/
void onChannelSelected(String channelName);
}
/**
* <p>An Interface class that is implemented by all classes that make use of
* {@link BranchListResponseListener}, defining a single method that takes a list of
* {@link JSONArray} format, and an error message of {@link BranchError} format that will be
* returned on failure of the request response.</p>
*
* @see JSONArray
* @see BranchError
*/
public interface BranchListResponseListener {
void onReceivingResponse(JSONArray list, BranchError error);
}
/**
* <p>
* Callback interface for listening logout status
* </p>
*/
public interface LogoutStatusListener {
/**
* Called on finishing the the logout process
*
* @param loggedOut A {@link Boolean} which is set to true if logout succeeded
* @param error An instance of {@link BranchError} to notify any error occurred during logout.
* A null value is set if logout succeeded.
*/
void onLogoutFinished(boolean loggedOut, BranchError error);
}
/**
* <p>enum containing the sort options for return of credit history.</p>
*/
public enum CreditHistoryOrder {
kMostRecentFirst, kLeastRecentFirst
}
/**
* Async Task to create a shorlink for synchronous methods
*/
private class getShortLinkTask extends AsyncTask<ServerRequest, Void, ServerResponse> {
@Override
protected ServerResponse doInBackground(ServerRequest... serverRequests) {
return kRemoteInterface_.createCustomUrlSync(serverRequests[0].getPost());
}
}
/**
* Asynchronous task handling execution of server requests. Execute the network task on background
* thread and request are executed in sequential manner. Handles the request execution in
* Synchronous-Asynchronous pattern. Should be invoked only form main thread and the results are
* published in the main thread.
*/
private class BranchPostTask extends AsyncTask<Void, Void, ServerResponse> {
int timeOut_ = 0;
ServerRequest thisReq_;
public BranchPostTask(ServerRequest request) {
thisReq_ = request;
timeOut_ = prefHelper_.getTimeout();
}
@Override
protected ServerResponse doInBackground(Void... voids) {
//Google ADs ID and LAT value are updated using reflection. These method need background thread
//So updating them for install and open on background thread.
if (thisReq_ instanceof ServerRequestInitSession
|| thisReq_ instanceof ServerRequestRegisterView) {
thisReq_.updateGAdsParams(systemObserver_);
}
if (thisReq_.isGetRequest()) {
return kRemoteInterface_.make_restful_get(thisReq_.getRequestUrl(), thisReq_.getGetParams(), thisReq_.getRequestPath(), timeOut_);
} else {
return kRemoteInterface_.make_restful_post(thisReq_.getPost(), thisReq_.getRequestUrl(), thisReq_.getRequestPath(), timeOut_);
}
}
@Override
protected void onPostExecute(ServerResponse serverResponse) {
super.onPostExecute(serverResponse);
if (serverResponse != null) {
try {
int status = serverResponse.getStatusCode();
hasNetwork_ = true;
//If the request is not succeeded
if (status != 200) {
//If failed request is an initialisation request then mark session not initialised
if (thisReq_ instanceof ServerRequestInitSession) {
initState_ = SESSION_STATE.UNINITIALISED;
}
// On a bad request notify with call back and remove the request.
if (status == 409) {
requestQueue_.remove(thisReq_);
if (thisReq_ instanceof ServerRequestCreateUrl) {
((ServerRequestCreateUrl) thisReq_).handleDuplicateURLError();
} else {
Log.i("BranchSDK", "Branch API Error: Conflicting resource error code from API");
handleFailure(0, status);
}
}
//On Network error or Branch is down fail all the pending requests in the queue except
//for request which need to be replayed on failure.
else {
hasNetwork_ = false;
//Collect all request from the queue which need to be failed.
ArrayList<ServerRequest> requestToFail = new ArrayList<>();
for (int i = 0; i < requestQueue_.getSize(); i++) {
requestToFail.add(requestQueue_.peekAt(i));
}
//Remove the requests from the request queue first
for (ServerRequest req : requestToFail) {
if (req == null || !req.shouldRetryOnFail()) { // Should remove any nullified request object also from queque
requestQueue_.remove(req);
}
}
// Then, set the network count to zero, indicating that requests can be started again.
networkCount_ = 0;
//Finally call the request callback with the error.
for (ServerRequest req : requestToFail) {
if (req != null) {
req.handleFailure(status, serverResponse.getFailReason());
//If request need to be replayed, no need for the callbacks
if (req.shouldRetryOnFail())
req.clearCallbacks();
}
}
}
}
//If the request succeeded
else {
hasNetwork_ = true;
//On create new url cache the url.
if (thisReq_ instanceof ServerRequestCreateUrl) {
if (serverResponse.getObject() != null) {
final String url = serverResponse.getObject().getString("url");
// cache the link
linkCache_.put(serverResponse.getLinkData(), url);
}
}
//On Logout clear the link cache and all pending requests
else if (thisReq_ instanceof ServerRequestLogout) {
linkCache_.clear();
requestQueue_.clear();
}
requestQueue_.dequeue();
// If this request changes a session update the session-id to queued requests.
if (thisReq_ instanceof ServerRequestInitSession
|| thisReq_ instanceof ServerRequestIdentifyUserRequest) {
// Immediately set session and Identity and update the pending request with the params
if (serverResponse.getObject() != null) {
boolean updateRequestsInQueue = false;
if (serverResponse.getObject().has(Defines.Jsonkey.SessionID.getKey())) {
prefHelper_.setSessionID(serverResponse.getObject().getString(Defines.Jsonkey.SessionID.getKey()));
updateRequestsInQueue = true;
}
if (serverResponse.getObject().has(Defines.Jsonkey.IdentityID.getKey())) {
String new_Identity_Id = serverResponse.getObject().getString(Defines.Jsonkey.IdentityID.getKey());
if (!prefHelper_.getIdentityID().equals(new_Identity_Id)) {
//On setting a new identity Id clear the link cache
linkCache_.clear();
prefHelper_.setIdentityID(serverResponse.getObject().getString(Defines.Jsonkey.IdentityID.getKey()));
updateRequestsInQueue = true;
}
}
if (serverResponse.getObject().has(Defines.Jsonkey.DeviceFingerprintID.getKey())) {
prefHelper_.setDeviceFingerPrintID(serverResponse.getObject().getString(Defines.Jsonkey.DeviceFingerprintID.getKey()));
updateRequestsInQueue = true;
}
if (updateRequestsInQueue) {
updateAllRequestsInQueue();
}
if (thisReq_ instanceof ServerRequestInitSession) {
initState_ = SESSION_STATE.INITIALISED;
// Publish success to listeners
thisReq_.onRequestSucceeded(serverResponse, branchReferral_);
isInitReportedThroughCallBack = ((ServerRequestInitSession) thisReq_).hasCallBack();
checkForAutoDeepLinkConfiguration();
} else {
// For setting identity just call only request succeeded
thisReq_.onRequestSucceeded(serverResponse, branchReferral_);
}
}
} else {
//Publish success to listeners
thisReq_.onRequestSucceeded(serverResponse, branchReferral_);
}
}
networkCount_ = 0;
if (hasNetwork_ && initState_ != SESSION_STATE.UNINITIALISED) {
processNextQueueItem();
}
} catch (JSONException ex) {
ex.printStackTrace();
}
}
}
}
/**
* <p>Checks if an activity is launched by Branch auto deep link feature. Branch launches activitie configured for auto deep link on seeing matching keys.
* Keys for auto deep linking should be specified to each activity as a meta data in manifest.</p>
* <p>
* Configure your activity in your manifest to enable auto deep linking as follows
* <activity android:name=".YourActivity">
* <meta-data android:name="io.branch.sdk.auto_link" android:value="DeepLinkKey1","DeepLinkKey2" />
* </activity>
* </p>
*
* @param activity Instance of activity to check if launched on auto deep link.
* @return A {Boolean} value whose value is true if this activity is launched by Branch auto deeplink feature.
*/
public static boolean isAutoDeepLinkLaunch(Activity activity) {
return (activity.getIntent().getStringExtra(AUTO_DEEP_LINKED) != null);
}
private void checkForAutoDeepLinkConfiguration() {
JSONObject latestParams = getLatestReferringParams();
String deepLinkActivity = null;
try {
//Check if the application is launched by clicking a Branch link.
if (!latestParams.has(Defines.Jsonkey.Clicked_Branch_Link.getKey())
|| !latestParams.getBoolean(Defines.Jsonkey.Clicked_Branch_Link.getKey())) {
return;
}
if (latestParams.length() > 0) {
// Check if auto deep link is disabled.
ApplicationInfo appInfo = context_.getPackageManager().getApplicationInfo(context_.getPackageName(), PackageManager.GET_META_DATA);
if (appInfo.metaData != null && appInfo.metaData.getBoolean(AUTO_DEEP_LINK_DISABLE, false)) {
return;
}
PackageInfo info = context_.getPackageManager().getPackageInfo(context_.getPackageName(), PackageManager.GET_ACTIVITIES | PackageManager.GET_META_DATA);
ActivityInfo[] activityInfos = info.activities;
int deepLinkActivityReqCode = DEF_AUTO_DEEP_LINK_REQ_CODE;
if (activityInfos != null) {
for (ActivityInfo activityInfo : activityInfos) {
if (activityInfo != null && activityInfo.metaData != null && (activityInfo.metaData.getString(AUTO_DEEP_LINK_KEY) != null || activityInfo.metaData.getString(AUTO_DEEP_LINK_PATH) != null)) {
if (checkForAutoDeepLinkKeys(latestParams, activityInfo) || checkForAutoDeepLinkPath(latestParams, activityInfo)) {
deepLinkActivity = activityInfo.name;
deepLinkActivityReqCode = activityInfo.metaData.getInt(AUTO_DEEP_LINK_REQ_CODE, DEF_AUTO_DEEP_LINK_REQ_CODE);
break;
}
}
}
}
if (deepLinkActivity != null && currentActivity_ != null) {
Intent intent = new Intent(currentActivity_, Class.forName(deepLinkActivity));
intent.putExtra(AUTO_DEEP_LINKED, "true");
// Put the raw JSON params as extra in case need to get the deep link params as JSON String
intent.putExtra(Defines.Jsonkey.ReferringData.getKey(), latestParams.toString());
// Add individual parameters in the data
Iterator<?> keys = latestParams.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
intent.putExtra(key, latestParams.getString(key));
}
currentActivity_.startActivityForResult(intent, deepLinkActivityReqCode);
}
}
} catch (final PackageManager.NameNotFoundException e) {
Log.i("BranchSDK", "Branch Warning: Please make sure Activity names set for auto deep link are correct!");
} catch (ClassNotFoundException e) {
Log.i("BranchSDK", "Branch Warning: Please make sure Activity names set for auto deep link are correct! Error while looking for activity " + deepLinkActivity);
} catch (JSONException ignore) {
}
}
private boolean checkForAutoDeepLinkKeys(JSONObject params, ActivityInfo activityInfo) {
if (activityInfo.metaData.getString(AUTO_DEEP_LINK_KEY) != null) {
String[] activityLinkKeys = activityInfo.metaData.getString(AUTO_DEEP_LINK_KEY).split(",");
for (String activityLinkKey : activityLinkKeys) {
if (params.has(activityLinkKey)) {
return true;
}
}
}
return false;
}
private boolean checkForAutoDeepLinkPath(JSONObject params, ActivityInfo activityInfo) {
String deepLinkPath = null;
try {
if (params.has(Defines.Jsonkey.AndroidDeepLinkPath.getKey())) {
deepLinkPath = params.getString(Defines.Jsonkey.AndroidDeepLinkPath.getKey());
} else if (params.has(Defines.Jsonkey.DeepLinkPath.getKey())) {
deepLinkPath = params.getString(Defines.Jsonkey.DeepLinkPath.getKey());
}
} catch (JSONException ignored) {
}
if (activityInfo.metaData.getString(AUTO_DEEP_LINK_PATH) != null && deepLinkPath != null) {
String[] activityLinkPaths = activityInfo.metaData.getString(AUTO_DEEP_LINK_PATH).split(",");
for (String activityLinkPath : activityLinkPaths) {
if (pathMatch(activityLinkPath.trim(), deepLinkPath)) {
return true;
}
}
}
return false;
}
private boolean pathMatch(String templatePath, String path) {
boolean matched = true;
String[] pathSegmentsTemplate = templatePath.split("\\?")[0].split("/");
String[] pathSegmentsTarget = path.split("\\?")[0].split("/");
if (pathSegmentsTemplate.length != pathSegmentsTarget.length) {
return false;
}
for (int i = 0; i < pathSegmentsTemplate.length && i < pathSegmentsTarget.length; i++) {
String pathSegmentTemplate = pathSegmentsTemplate[i];
String pathSegmentTarget = pathSegmentsTarget[i];
if (!pathSegmentTemplate.equals(pathSegmentTarget) && !pathSegmentTemplate.contains("*")) {
matched = false;
break;
}
}
return matched;
}
public class BranchWindowCallback implements Window.Callback {
private Runnable longPressed_;
private Window.Callback callback_;
public BranchWindowCallback(Window.Callback callback) {
callback_ = callback;
if (longPressed_ == null) {
longPressed_ = new Runnable() {
private Timer timer;
public void run() {
debugHandler_.removeCallbacks(longPressed_);
if (!debugStarted_) {
Log.i("Branch Debug", "======= Start Debug Session =======");
prefHelper_.setDebug();
timer = new Timer();
timer.scheduleAtFixedRate(new KeepDebugConnectionTask(), new Date(), 20000);
} else {
Log.i("Branch Debug", "======= End Debug Session =======");
prefHelper_.clearDebug();
if (timer != null) {
timer.cancel();
timer = null;
}
}
debugStarted_ = !debugStarted_;
}
};
}
}
class KeepDebugConnectionTask extends TimerTask {
public void run() {
if (debugStarted_ && !prefHelper_.keepDebugConnection() && longPressed_ != null) {
debugHandler_.post(longPressed_);
}
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
@Override
public boolean dispatchGenericMotionEvent(MotionEvent event) {
return callback_.dispatchGenericMotionEvent(event);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
return callback_.dispatchKeyEvent(event);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public boolean dispatchKeyShortcutEvent(KeyEvent event) {
return callback_.dispatchKeyShortcutEvent(event);
}
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
return callback_.dispatchPopulateAccessibilityEvent(event);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
if (systemObserver_.isSimulator()) {
debugHandler_.postDelayed(longPressed_, PrefHelper.DEBUG_TRIGGER_PRESS_TIME);
}
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_CANCEL:
debugHandler_.removeCallbacks(longPressed_);
break;
case MotionEvent.ACTION_UP:
debugHandler_.removeCallbacks(longPressed_);
break;
case MotionEvent.ACTION_POINTER_DOWN:
if (event.getPointerCount() == PrefHelper.DEBUG_TRIGGER_NUM_FINGERS) {
debugHandler_.postDelayed(longPressed_, PrefHelper.DEBUG_TRIGGER_PRESS_TIME);
}
break;
default:
break;
}
return callback_.dispatchTouchEvent(event);
}
@Override
public boolean dispatchTrackballEvent(MotionEvent event) {
return callback_.dispatchTrackballEvent(event);
}
@SuppressLint("NewApi")
@Override
public void onActionModeFinished(ActionMode mode) {
callback_.onActionModeFinished(mode);
}
@SuppressLint("NewApi")
@Override
public void onActionModeStarted(ActionMode mode) {
callback_.onActionModeStarted(mode);
}
@Override
public void onAttachedToWindow() {
callback_.onAttachedToWindow();
}
@Override
public void onContentChanged() {
callback_.onContentChanged();
}
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
return callback_.onCreatePanelMenu(featureId, menu);
}
@Override
public View onCreatePanelView(int featureId) {
return callback_.onCreatePanelView(featureId);
}
@SuppressLint("MissingSuperCall")
@Override
public void onDetachedFromWindow() {
callback_.onDetachedFromWindow();
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
return callback_.onMenuItemSelected(featureId, item);
}
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
return callback_.onMenuOpened(featureId, menu);
}
@Override
public void onPanelClosed(int featureId, Menu menu) {
callback_.onPanelClosed(featureId, menu);
}
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
return callback_.onPreparePanel(featureId, view, menu);
}
@Override
public boolean onSearchRequested() {
return callback_.onSearchRequested();
}
@Override
public void onWindowAttributesChanged(WindowManager.LayoutParams attrs) {
callback_.onWindowAttributesChanged(attrs);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
callback_.onWindowFocusChanged(hasFocus);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
return callback_.onWindowStartingActionMode(callback);
}
}
/**
* <p> Class for building a share link dialog.This creates a chooser for selecting application for
* sharing a link created with given parameters. </p>
*/
public static class ShareLinkBuilder {
private final Activity activity_;
private final Branch branch_;
private String shareMsg_;
private String shareSub_;
private Branch.BranchLinkShareListener callback_ = null;
private ArrayList<SharingHelper.SHARE_WITH> preferredOptions_;
private String defaultURL_;
//Customise more and copy url option
private Drawable moreOptionIcon_;
private String moreOptionText_;
private Drawable copyUrlIcon_;
private String copyURlText_;
private String urlCopiedMessage_;
BranchShortLinkBuilder shortLinkBuilder_;
/**
* <p>Creates options for sharing a link with other Applications. Creates a builder for sharing the link with
* user selected clients</p>
*
* @param activity The {@link Activity} to show the dialog for choosing sharing application.
* @param parameters @param params A {@link JSONObject} value containing the deep link params.
*/
public ShareLinkBuilder(Activity activity, JSONObject parameters) {
this.activity_ = activity;
this.branch_ = branchReferral_;
shortLinkBuilder_ = new BranchShortLinkBuilder(activity);
try {
Iterator<String> keys = parameters.keys();
while (keys.hasNext()) {
String key = keys.next();
shortLinkBuilder_.addParameters(key, (String) parameters.get(key));
}
} catch (Exception ignore) {
}
shareMsg_ = "";
callback_ = null;
preferredOptions_ = new ArrayList<>();
defaultURL_ = null;
moreOptionIcon_ = BranchUtil.getDrawable(activity.getApplicationContext(), android.R.drawable.ic_menu_more);
moreOptionText_ = "More...";
copyUrlIcon_ = BranchUtil.getDrawable(activity.getApplicationContext(), android.R.drawable.ic_menu_save);
copyURlText_ = "Copy link";
urlCopiedMessage_ = "Copied link to clipboard!";
}
/**
* *<p>Creates options for sharing a link with other Applications. Creates a builder for sharing the link with
* user selected clients</p>
*
* @param activity The {@link Activity} to show the dialog for choosing sharing application.
* @param shortLinkBuilder An instance of {@link BranchShortLinkBuilder} to create link to be shared
*/
public ShareLinkBuilder(Activity activity, BranchShortLinkBuilder shortLinkBuilder) {
this(activity, new JSONObject());
shortLinkBuilder_ = shortLinkBuilder;
}
/**
* <p>Sets the message to be shared with the link.</p>
*
* @param message A {@link String} to be shared with the link
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setMessage(String message) {
this.shareMsg_ = message;
return this;
}
/**
* <p>Sets the subject of this message. This will be added to Email and SMS Application capable of handling subject in the message.</p>
*
* @param subject A {@link String} subject of this message.
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setSubject(String subject) {
this.shareSub_ = subject;
return this;
}
/**
* <p>Adds the given tag an iterable {@link Collection} of {@link String} tags associated with a deep
* link.</p>
*
* @param tag A {@link String} to be added to the iterable {@link Collection} of {@link String} tags associated with a deep
* link.
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder addTag(String tag) {
this.shortLinkBuilder_.addTag(tag);
return this;
}
/**
* <p>Adds the given tag an iterable {@link Collection} of {@link String} tags associated with a deep
* link.</p>
*
* @param tags A {@link java.util.List} of tags to be added to the iterable {@link Collection} of {@link String} tags associated with a deep
* link.
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder addTags(ArrayList<String> tags) {
this.shortLinkBuilder_.addTags(tags);
return this;
}
/**
* <p>Adds a feature that make use of the link.</p>
*
* @param feature A {@link String} value identifying the feature that the link makes use of.
* Should not exceed 128 characters.
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setFeature(String feature) {
this.shortLinkBuilder_.setFeature(feature);
return this;
}
/**
* <p>Adds a stage application or user flow associated with this link.</p>
*
* @param stage A {@link String} value identifying the stage in an application or user flow
* process. Should not exceed 128 characters.
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setStage(String stage) {
this.shortLinkBuilder_.setStage(stage);
return this;
}
/**
* <p>Adds a callback to get the sharing status.</p>
*
* @param callback A {@link BranchLinkShareListener} instance for getting sharing status.
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setCallback(BranchLinkShareListener callback) {
this.callback_ = callback;
return this;
}
/**
* <p>Adds application to the preferred list of applications which are shown on share dialog.
* Only these options will be visible when the application selector dialog launches. Other options can be
* accessed by clicking "More"</p>
*
* @param preferredOption A list of applications to be added as preferred options on the app chooser.
* Preferred applications are defined in {@link io.branch.referral.SharingHelper.SHARE_WITH}.
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder addPreferredSharingOption(SharingHelper.SHARE_WITH preferredOption) {
this.preferredOptions_.add(preferredOption);
return this;
}
/**
* <p>Adds application to the preferred list of applications which are shown on share dialog.
* Only these options will be visible when the application selector dialog launches. Other options can be
* accessed by clicking "More"</p>
*
* @param preferredOptions A list of applications to be added as preferred options on the app chooser.
* Preferred applications are defined in {@link io.branch.referral.SharingHelper.SHARE_WITH}.
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder addPreferredSharingOptions(ArrayList<SharingHelper.SHARE_WITH> preferredOptions) {
this.preferredOptions_.addAll(preferredOptions);
return this;
}
/**
* Add the given key value to the deep link parameters
*
* @param key A {@link String} with value for the key for the deep link params
* @param value A {@link String} with deep link parameters value
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder addParam(String key, String value) {
try {
this.shortLinkBuilder_.addParameters(key, value);
} catch (Exception ignore) {
}
return this;
}
/**
* <p> Set a default url to share in case there is any error creating the deep link </p>
*
* @param url A {@link String} with value of default url to be shared with the selected application in case deep link creation fails.
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setDefaultURL(String url) {
defaultURL_ = url;
return this;
}
/**
* <p> Set the icon and label for the option to expand the application list to see more options.
* Default label is set to "More" </p>
*
* @param icon Drawable to set as the icon for more option. Default icon is system menu_more icon.
* @param label A {@link String} with value for the more option label. Default label is "More"
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setMoreOptionStyle(Drawable icon, String label) {
moreOptionIcon_ = icon;
moreOptionText_ = label;
return this;
}
/**
* <p> Set the icon and label for the option to expand the application list to see more options.
* Default label is set to "More" </p>
*
* @param drawableIconID Resource ID for the drawable to set as the icon for more option. Default icon is system menu_more icon.
* @param stringLabelID Resource ID for String label for the more option. Default label is "More"
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setMoreOptionStyle(int drawableIconID, int stringLabelID) {
moreOptionIcon_ = BranchUtil.getDrawable(activity_.getApplicationContext(), drawableIconID);
moreOptionText_ = activity_.getResources().getString(stringLabelID);
return this;
}
/**
* <p> Set the icon, label and success message for copy url option. Default label is "Copy link".</p>
*
* @param icon Drawable to set as the icon for copy url option. Default icon is system menu_save icon
* @param label A {@link String} with value for the copy url option label. Default label is "Copy link"
* @param message A {@link String} with value for a toast message displayed on copying a url.
* Default message is "Copied link to clipboard!"
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setCopyUrlStyle(Drawable icon, String label, String message) {
copyUrlIcon_ = icon;
copyURlText_ = label;
urlCopiedMessage_ = message;
return this;
}
/**
* <p> Set the icon, label and success message for copy url option. Default label is "Copy link".</p>
*
* @param drawableIconID Resource ID for the drawable to set as the icon for copy url option. Default icon is system menu_save icon
* @param stringLabelID Resource ID for the string label the copy url option. Default label is "Copy link"
* @param stringMessageID Resource ID for the string message to show toast message displayed on copying a url
* @return A {@link io.branch.referral.Branch.ShareLinkBuilder} instance.
*/
public ShareLinkBuilder setCopyUrlStyle(int drawableIconID, int stringLabelID, int stringMessageID) {
copyUrlIcon_ = BranchUtil.getDrawable(activity_.getApplicationContext(), drawableIconID);
copyURlText_ = activity_.getResources().getString(stringLabelID);
urlCopiedMessage_ = activity_.getResources().getString(stringMessageID);
return this;
}
public ShareLinkBuilder setAlias(String alias) {
this.shortLinkBuilder_.setAlias(alias);
return this;
}
/**
* <p> Sets the amount of time that Branch allows a click to remain outstanding.</p>
*
* @param matchDuration A {@link Integer} value specifying the time that Branch allows a click to
* remain outstanding and be eligible to be matched with a new app session.
* @return This Builder object to allow for chaining of calls to set methods.
*/
public ShareLinkBuilder setMatchDuration(int matchDuration) {
this.shortLinkBuilder_.setDuration(matchDuration);
return this;
}
public void setShortLinkBuilderInternal(BranchShortLinkBuilder shortLinkBuilder) {
this.shortLinkBuilder_ = shortLinkBuilder;
}
/**
* <p>Creates an application selector dialog and share a link with user selected sharing option.
* The link is created with the parameters provided to the builder. </p>
*/
public void shareLink() {
branchReferral_.shareLink(this);
}
public Activity getActivity() {
return activity_;
}
public ArrayList<SharingHelper.SHARE_WITH> getPreferredOptions() {
return preferredOptions_;
}
public Branch getBranch() {
return branch_;
}
public String getShareMsg() {
return shareMsg_;
}
public String getShareSub() {
return shareSub_;
}
public BranchLinkShareListener getCallback() {
return callback_;
}
public String getDefaultURL() {
return defaultURL_;
}
public Drawable getMoreOptionIcon() {
return moreOptionIcon_;
}
public String getMoreOptionText() {
return moreOptionText_;
}
public Drawable getCopyUrlIcon() {
return copyUrlIcon_;
}
public String getCopyURlText() {
return copyURlText_;
}
public String getUrlCopiedMessage() {
return urlCopiedMessage_;
}
public BranchShortLinkBuilder getShortLinkBuilder() {
return shortLinkBuilder_;
}
}
public void registerView(BranchUniversalObject branchUniversalObject, BranchUniversalObject.RegisterViewStatusListener callback) {
ServerRequest req;
req = new ServerRequestRegisterView(currentActivity_, branchUniversalObject, systemObserver_, callback);
if (!req.constructError_ && !req.handleErrors(context_)) {
handleNewRequest(req);
}
}
}
|
package hudson.util;
import hudson.Extension;
import hudson.model.AdministrativeMonitor;
/**
* A convenient {@link AdministrativeMonitor} implementations that show an error message
* and optional stack trace. This is useful for notifying a non-fatal error to the administrator.
*
* <p>
* These errors are registered when instances are created. No need to use {@link Extension}.
*
* @author Kohsuke Kawaguchi
* @deprecated Implement {@link hudson.model.AdministrativeMonitor} directly instead.
*/
@Deprecated
public class AdministrativeError extends AdministrativeMonitor {
public final String message;
public final String title;
public final Throwable details;
/**
* @param id
* Unique ID that distinguishes this error from other errors.
* Must remain the same across Hudson executions. Use a caller class name, or something like that.
* @param title
* A title of the problem. This is used as the HTML title
* of the details page. Should be just one sentence, like "ZFS migration error."
* @param message
* A short description of the problem. This is used in the "/manage" page, and can include HTML, but it should be still short.
* @param details
* An exception indicating the problem. The administrator can see this once they click "more details".
*/
public AdministrativeError(String id, String title, String message, Throwable details) {
super(id);
this.message = message;
this.title = title;
this.details = details;
all().add(this);
}
@Override
public boolean isActivated() {
return true;
}
}
|
package net.tomp2p.p2p;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.concurrent.atomic.AtomicReferenceArray;
import net.tomp2p.futures.BaseFuture;
import net.tomp2p.futures.FutureResponse;
import net.tomp2p.futures.FutureRouting;
import net.tomp2p.p2p.builder.RoutingBuilder;
import net.tomp2p.peers.Number160;
import net.tomp2p.peers.PeerAddress;
import net.tomp2p.peers.PeerFilter;
import net.tomp2p.peers.PeerStatistic;
import net.tomp2p.rpc.DigestInfo;
import net.tomp2p.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RoutingMechanism {
private static final Logger LOG = LoggerFactory.getLogger(RoutingMechanism.class);
private final AtomicReferenceArray<FutureResponse> futureResponses;
private final FutureRouting futureRoutingResponse;
private final Collection<PeerFilter> peerFilters;
private NavigableSet<PeerStatistic> queueToAsk;
private SortedSet<PeerAddress> alreadyAsked;
private SortedMap<PeerAddress, DigestInfo> directHits;
private NavigableSet<PeerAddress> potentialHits;
private int nrNoNewInfo = 0;
private int nrFailures = 0;
private int nrSuccess = 0;
private int maxDirectHits;
private int maxNoNewInfo;
private int maxFailures;
private int maxSuccess;
private boolean stopCreatingNewFutures;
/**
* Creates the routing mechanism. Make sure to set the max* fields.
*
* @param futureResponses
* The current future responeses that are running
* @param futureRoutingResponse
* The reponse future from this routing request
*/
public RoutingMechanism(final AtomicReferenceArray<FutureResponse> futureResponses,
final FutureRouting futureRoutingResponse, final Collection<PeerFilter> peerFilters) {
this.futureResponses = futureResponses;
this.futureRoutingResponse = futureRoutingResponse;
this.peerFilters = peerFilters;
}
public FutureRouting futureRoutingResponse() {
return futureRoutingResponse;
}
/**
* @return The number of parallel requests. The number is determined by the length of the future response array
*/
public int parallel() {
return futureResponses.length();
}
/**
* @return True if we should stop creating more futures, false otherwise
*/
public boolean isStopCreatingNewFutures() {
return stopCreatingNewFutures;
}
/**
* @param i
* The number of the future response to get
* @return The future response at position i
*/
public FutureResponse futureResponse(final int i) {
return futureResponses.get(i);
}
/**
* @param i
* The number of the future response to get and set
* @param futureResponse
* The future response to set
* @return The old future response
*/
public FutureResponse futureResponse(final int i, final FutureResponse futureResponse) {
return futureResponses.getAndSet(i, futureResponse);
}
/**
* @param queueToAsk
* The queue that contains the peers that will be queried in the future
* @return This class
*/
public RoutingMechanism queueToAsk(final NavigableSet<PeerStatistic> queueToAsk) {
this.queueToAsk = queueToAsk;
return this;
}
/**
* @return The queue that contains the peers that will be queried in the future
*/
public NavigableSet<PeerStatistic> queueToAsk() {
synchronized (this) {
return queueToAsk;
}
}
/**
* @param alreadyAsked
* The peer we have already queried, we need to store them to not ask the same peers again
* @return This class
*/
public RoutingMechanism alreadyAsked(final SortedSet<PeerAddress> alreadyAsked) {
this.alreadyAsked = alreadyAsked;
return this;
}
/**
* @return The peer we have already queried, we need to store them to not ask the same peers again
*/
public SortedSet<PeerAddress> alreadyAsked() {
synchronized (this) {
return alreadyAsked;
}
}
/**
* @param potentialHits
* The potential hits are those reported by other peers that we did not check if they contain certain
* data.
* @return This class
*/
public RoutingMechanism potentialHits(final NavigableSet<PeerAddress> potentialHits) {
this.potentialHits = potentialHits;
return this;
}
/**
* @return The potential hits are those reported by other peers that we did not check if they contain certain data.
*/
public NavigableSet<PeerAddress> potentialHits() {
synchronized (this) {
return potentialHits;
}
}
/**
* @param directHits
* The peers that have certain data stored on it
* @return This class
*/
public RoutingMechanism directHits(final SortedMap<PeerAddress, DigestInfo> directHits) {
this.directHits = directHits;
return this;
}
/**
* @return The peers that have certain data stored on it
*/
public SortedMap<PeerAddress, DigestInfo> directHits() {
return directHits;
}
public int getMaxDirectHits() {
return maxDirectHits;
}
public void maxDirectHits(int maxDirectHits) {
this.maxDirectHits = maxDirectHits;
}
public int maxNoNewInfo() {
return maxNoNewInfo;
}
public void maxNoNewInfo(int maxNoNewInfo) {
this.maxNoNewInfo = maxNoNewInfo;
}
public int maxFailures() {
return maxFailures;
}
public void maxFailures(int maxFailures) {
this.maxFailures = maxFailures;
}
public int maxSucess() {
return maxSuccess;
}
public void maxSucess(int maxSucess) {
this.maxSuccess = maxSucess;
}
public PeerAddress pollFirstInQueueToAsk() {
synchronized (this) {
PeerStatistic first = queueToAsk.pollFirst();
if (first == null)
return null;
return first.peerAddress();
}
}
public PeerAddress pollRandomInQueueToAsk(Random rnd) {
synchronized (this) {
PeerStatistic first = Utils.pollRandom(queueToAsk(), rnd);
if (first == null)
return null;
return first.peerAddress();
}
}
public void addToAlreadyAsked(PeerAddress next) {
synchronized (this) {
alreadyAsked.add(next);
}
}
public void neighbors(RoutingBuilder builder) {
synchronized (this) {
futureRoutingResponse.neighbors(directHits, potentialHits, alreadyAsked,
builder.isBootstrap(), builder.isRoutingToOthers());
}
}
/**
* Cancel the future that causes the underlying futures to cancel as well.
*/
public void cancel() {
int len = futureResponses.length();
for (int i = 0; i < len; i++) {
BaseFuture baseFuture = futureResponses.get(i);
if (baseFuture != null) {
baseFuture.cancel();
}
}
}
public AtomicReferenceArray<FutureResponse> futureResponses() {
return futureResponses;
}
public void addPotentialHits(PeerAddress remotePeer) {
synchronized (this) {
potentialHits.add(remotePeer);
}
}
public void stopCreatingNewFutures(boolean stopCreatingNewFutures) {
this.stopCreatingNewFutures = stopCreatingNewFutures;
}
public boolean evaluateFailed() {
return (++nrFailures) > maxFailures();
}
public boolean evaluateSuccess(PeerAddress remotePeer, DigestInfo digestBean,
Collection<PeerStatistic> newNeighbors, boolean last, Number160 locationkey) {
boolean finished;
synchronized (this) {
filterPeers(newNeighbors, alreadyAsked, queueToAsk, locationkey);
if (evaluateDirectHits(remotePeer, directHits, digestBean, getMaxDirectHits())) {
// stop immediately
LOG.debug("we have enough direct hits {}", directHits);
finished = true;
stopCreatingNewFutures = true;
} else if ((++nrSuccess) > maxSucess()) {
// wait until pending futures are finished
LOG.debug("we have reached max success {}", nrSuccess);
finished = last;
stopCreatingNewFutures = true;
} else if (evaluateInformation(newNeighbors, queueToAsk, alreadyAsked, maxNoNewInfo())) {
// wait until pending futures are finished
LOG.debug("we have no new information for the {} time", maxNoNewInfo());
finished = last;
stopCreatingNewFutures = true;
} else {
// continue
finished = false;
stopCreatingNewFutures = false;
}
}
return finished;
}
private void filterPeers(Collection<PeerStatistic> newNeighbors, SortedSet<PeerAddress> alreadyAsked,
NavigableSet<PeerStatistic> queueToAsk, Number160 locationkey) {
if (peerFilters == null || peerFilters.size() == 0) {
return;
}
Collection<PeerAddress> all = new ArrayList<PeerAddress>();
all.addAll(alreadyAsked);
for (PeerStatistic peerStatistic : queueToAsk) {
all.add(peerStatistic.peerAddress());
}
for (Iterator<PeerStatistic> iterator = newNeighbors.iterator(); iterator.hasNext();) {
PeerAddress newNeighbor = iterator.next().peerAddress();
for (PeerFilter peerFilter : peerFilters) {
if (peerFilter.reject(newNeighbor, all, locationkey)) {
iterator.remove();
}
}
}
}
/**
* For get requests we can finish earlier if we found the data we were looking for. This checks if we reached the
* end of our search.
*
* @param remotePeer
* The remote peer that gave us thi digest information
* @param directHits
* The result map that will store how many peers reported that data is there
* @param digestBean
* The digest information coming from the remote peer
* @param maxDirectHits
* The max. number of direct hits, e.g. finding the value we were looking for before we can stop.
* @return True if we can stop, false, if we should continue.
*/
static boolean evaluateDirectHits(final PeerAddress remotePeer,
final Map<PeerAddress, DigestInfo> directHits, final DigestInfo digestBean,
final int maxDirectHits) {
if (digestBean.size() > 0) {
directHits.put(remotePeer, digestBean);
if (directHits.size() >= maxDirectHits) {
return true;
}
}
return false;
}
/**
* Checks if we reached the end of our search.
*
* @param newNeighbors
* The new neighbors we just received
* @param queueToAsk
* The peers that are in the queue to be asked
* @param alreadyAsked
* The peers we have already asked
* @param maxNoNewInfo
* The maximum number of replies from neighbors that do not give us closer peers
* @return True if we should stop, false if we should continue with the routing
*/
boolean evaluateInformation(final Collection<PeerStatistic> newNeighbors,
final SortedSet<PeerStatistic> queueToAsk, final Set<PeerAddress> alreadyAsked,
final int maxNoNewInfo) {
boolean newInformation = merge(queueToAsk, newNeighbors, alreadyAsked);
if (newInformation) {
nrNoNewInfo = 0;
return false;
} else {
return (++nrNoNewInfo) >= maxNoNewInfo;
}
}
/**
* Updates queueToAsk with new data, returns if we found peers closer than we already know.
*
* @param queueToAsk
* The queue to get updated
* @param newPeers
* The new peers reported from remote peers. Since the remote peers do not know what we know, we need to
* filter this information.
* @param alreadyAsked
* The peers we already know.
* @return True if we added peers that are closer to the target than we already knew. Please note, it will return
* false if we add new peers that are not closer to a target.
*/
static boolean merge(final SortedSet<PeerStatistic> queueToAsk, final Collection<PeerStatistic> newPeers,
final Collection<PeerAddress> alreadyAsked) {
final SortedSet<PeerStatistic> result = new UpdatableTreeSet<PeerStatistic>(queueToAsk.comparator());
// Remove peers we already asked
for (Iterator<PeerStatistic> iterator = newPeers.iterator(); iterator.hasNext(); ) {
PeerStatistic newPeer = iterator.next();
if (!alreadyAsked.contains(newPeer.peerAddress()))
result.add(newPeer);
}
if (result.size() == 0) {
return false;
}
PeerStatistic first = result.first();
boolean newInfo = isNew(queueToAsk, first);
queueToAsk.addAll(result);
return newInfo;
}
/**
* Checks if an item will be the highest in a sorted set.
*
* @param queueToAsk
* The sorted set to check
* @param item
* The element to check if it will be the highest in the sorted set
* @return True, if item will be the highest element.
*/
private static boolean isNew(final SortedSet<PeerStatistic> queueToAsk, final PeerStatistic item) {
if (queueToAsk.contains(item)) {
return false;
}
SortedSet<PeerStatistic> tmp = queueToAsk.headSet(item);
return tmp.size() == 0;
}
public int nrNoNewInfo() {
return nrNoNewInfo;
}
}
|
package org.kohsuke.stapler;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.jvnet.tiger_types.Lister;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
/**
* {@link StaplerRequest} implementation.
*
* @author Kohsuke Kawaguchi
*/
public class RequestImpl extends HttpServletRequestWrapper implements StaplerRequest {
public final TokenList tokens;
public final List<AncestorImpl> ancestors;
private final List<Ancestor> ancestorsView;
public final Stapler stapler;
private final String originalRequestURI;
/**
* Cached result of {@link #getSubmittedForm()}
*/
private JSONObject structuredForm;
/**
* If the request is "multipart/form-data", parsed result goes here.
*
* @see #parseMultipartFormData()
*/
private Map<String, FileItem> parsedFormData;
public RequestImpl(Stapler stapler, HttpServletRequest request, List<AncestorImpl> ancestors, TokenList tokens) {
super(request);
this.stapler = stapler;
this.ancestors = ancestors;
this.ancestorsView = Collections.<Ancestor>unmodifiableList(ancestors);
this.tokens = tokens;
this.originalRequestURI = request.getRequestURI();
}
public Stapler getStapler() {
return stapler;
}
public String getRestOfPath() {
return tokens.assembleRestOfPath();
}
public String getOriginalRestOfPath() {
return tokens.assembleOriginalRestOfPath();
}
public ServletContext getServletContext() {
return stapler.getServletContext();
}
public RequestDispatcher getView(Object it,String viewName) throws IOException {
return getView(it.getClass(),it,viewName);
}
public RequestDispatcher getView(Class clazz, String viewName) throws IOException {
return getView(clazz,null,viewName);
}
public RequestDispatcher getView(Class clazz, Object it, String viewName) throws IOException {
for( Facet f : stapler.getWebApp().facets ) {
RequestDispatcher rd = f.createRequestDispatcher(this,clazz,it,viewName);
if(rd!=null)
return rd;
}
return null;
}
public String getRootPath() {
StringBuffer buf = super.getRequestURL();
int idx = 0;
for( int i=0; i<3; i++ )
idx += buf.substring(idx).indexOf("/")+1;
buf.setLength(idx-1);
buf.append(super.getContextPath());
return buf.toString();
}
public String getReferer() {
return getHeader("Referer");
}
public List<Ancestor> getAncestors() {
return ancestorsView;
}
public Ancestor findAncestor(Class type) {
for( int i = ancestors.size()-1; i>=0; i
AncestorImpl a = ancestors.get(i);
Object o = a.getObject();
if (type.isInstance(o))
return a;
}
return null;
}
public <T> T findAncestorObject(Class<T> type) {
Ancestor a = findAncestor(type);
if(a==null) return null;
return type.cast(a.getObject());
}
public Ancestor findAncestor(Object anc) {
for( int i = ancestors.size()-1; i>=0; i
AncestorImpl a = ancestors.get(i);
Object o = a.getObject();
if (o==anc)
return a;
}
return null;
}
public boolean hasParameter(String name) {
return getParameter(name)!=null;
}
public String getOriginalRequestURI() {
return originalRequestURI;
}
public boolean checkIfModified(long lastModified, StaplerResponse rsp) {
return checkIfModified(lastModified,rsp,0);
}
public boolean checkIfModified(long lastModified, StaplerResponse rsp, long expiration) {
if(lastModified<=0)
return false;
// send out Last-Modified, or check If-Modified-Since
String since = getHeader("If-Modified-Since");
SimpleDateFormat format = Stapler.HTTP_DATE_FORMAT.get();
if(since!=null) {
try {
long ims = format.parse(since).getTime();
if(lastModified<ims+1000) {
// +1000 because date header is second-precision and Java has milli-second precision
rsp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return true;
}
} catch (NumberFormatException e) {
// just ignore and serve the content
} catch (ParseException e) {
// just ignore and serve the content
}
}
String tm = format.format(new Date(lastModified));
rsp.setHeader("Last-Modified", tm);
if(expiration==0) {
// don't let browsers
rsp.setHeader("Expires", tm);
} else {
// expire in "NOW+expiration"
rsp.setHeader("Expires",format.format(new Date(new Date().getTime()+expiration)));
}
return false;
}
public boolean checkIfModified(Date timestampOfResource, StaplerResponse rsp) {
return checkIfModified(timestampOfResource.getTime(),rsp);
}
public boolean checkIfModified(Calendar timestampOfResource, StaplerResponse rsp) {
return checkIfModified(timestampOfResource.getTimeInMillis(),rsp);
}
public void bindParameters(Object bean) {
bindParameters(bean,"");
}
public void bindParameters(Object bean, String prefix) {
Enumeration e = getParameterNames();
while(e.hasMoreElements()) {
String name = (String)e.nextElement();
if(name.startsWith(prefix))
fill(bean,name.substring(prefix.length()), getParameter(name) );
}
}
public <T>
List<T> bindParametersToList(Class<T> type, String prefix) {
List<T> r = new ArrayList<T>();
int len = Integer.MAX_VALUE;
Enumeration e = getParameterNames();
while(e.hasMoreElements()) {
String name = (String)e.nextElement();
if(name.startsWith(prefix))
len = Math.min(len,getParameterValues(name).length);
}
if(len==Integer.MAX_VALUE)
return r; // nothing
try {
loadConstructorParamNames(type);
// use the designated constructor for databinding
for( int i=0; i<len; i++ )
r.add(bindParameters(type,prefix,i));
} catch (NoStaplerConstructorException _) {
// no designated data binding constructor. use reflection
try {
for( int i=0; i<len; i++ ) {
T t = type.newInstance();
r.add(t);
e = getParameterNames();
while(e.hasMoreElements()) {
String name = (String)e.nextElement();
if(name.startsWith(prefix))
fill(t, name.substring(prefix.length()), getParameterValues(name)[i] );
}
}
} catch (InstantiationException x) {
throw new InstantiationError(x.getMessage());
} catch (IllegalAccessException x) {
throw new IllegalAccessError(x.getMessage());
}
}
return r;
}
public <T> T bindParameters(Class<T> type, String prefix) {
return bindParameters(type,prefix,0);
}
public <T> T bindParameters(Class<T> type, String prefix, int index) {
String[] names = loadConstructorParamNames(type);
// the actual arguments to invoke the constructor with.
Object[] args = new Object[names.length];
// constructor
Constructor<T> c = findConstructor(type, names.length);
Class[] types = c.getParameterTypes();
// convert parameters
for( int i=0; i<names.length; i++ ) {
String[] values = getParameterValues(prefix + names[i]);
String param;
if(values!=null)
param = values[index];
else
param = null;
Converter converter = Stapler.lookupConverter(types[i]);
if (converter==null)
throw new IllegalArgumentException("Unable to convert to "+types[i]);
args[i] = converter.convert(types[i],param);
}
return invokeConstructor(c, args);
}
public <T> T bindJSON(Class<T> type, JSONObject src) {
try {
if(src.has("stapler-class")) {
// sub-type is specified in JSON.
// note that this can come from malicious clients, so we need to make sure we don't have seucrity issues.
ClassLoader cl = stapler.getWebApp().getClassLoader();
String className = src.getString("stapler-class");
try {
Class<?> subType = cl.loadClass(className);
if(!type.isAssignableFrom(subType))
throw new IllegalArgumentException("Specified type "+subType+" is not assignable to th expected "+type);
type = (Class)subType; // I'm being lazy here
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Class "+className+" is specified in JSON, but no such class found in "+cl,e);
}
}
String[] names = loadConstructorParamNames(type);
// the actual arguments to invoke the constructor with.
Object[] args = new Object[names.length];
// constructor
Constructor<T> c = findConstructor(type, names.length);
Class[] types = c.getParameterTypes();
Type[] genTypes = c.getGenericParameterTypes();
// convert parameters
for( int i=0; i<names.length; i++ ) {
try {
args[i] = new TypePair(genTypes[i],types[i]).convertJSON(src.get(names[i]));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Failed to convert the "+names[i]+" parameter of the constructor "+c,e);
}
}
return invokeConstructor(c, args);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Failed to instantiate "+type+" from "+src,e);
}
}
public void bindJSON(Object bean, JSONObject src) {
try {
for( String key : (Set<String>)src.keySet() ) {
TypePair type = getPropertyType(bean, key);
if(type==null)
continue;
fill(bean,key, type.convertJSON(src.get(key)));
}
} catch (IllegalAccessException e) {
IllegalAccessError x = new IllegalAccessError(e.getMessage());
x.initCause(e);
throw x;
} catch (InvocationTargetException x) {
Throwable e = x.getTargetException();
if(e instanceof RuntimeException)
throw (RuntimeException)e;
if(e instanceof Error)
throw (Error)e;
throw new RuntimeException(x);
}
}
public <T> List<T> bindJSONToList(Class<T> type, Object src) {
ArrayList<T> r = new ArrayList<T>();
if (src instanceof JSONObject) {
JSONObject j = (JSONObject) src;
r.add(bindJSON(type,j));
}
if (src instanceof JSONArray) {
JSONArray a = (JSONArray) src;
for (Object o : a) {
if (o instanceof JSONObject) {
JSONObject j = (JSONObject) o;
r.add(bindJSON(type,j));
}
}
}
return r;
}
private <T> T invokeConstructor(Constructor<T> c, Object[] args) {
try {
return c.newInstance(args);
} catch (InstantiationException e) {
InstantiationError x = new InstantiationError(e.getMessage());
x.initCause(e);
throw x;
} catch (IllegalAccessException e) {
IllegalAccessError x = new IllegalAccessError(e.getMessage());
x.initCause(e);
throw x;
} catch (InvocationTargetException e) {
Throwable x = e.getTargetException();
if(x instanceof Error)
throw (Error)x;
if(x instanceof RuntimeException)
throw (RuntimeException)x;
throw new IllegalArgumentException(x);
}
}
private <T> Constructor<T> findConstructor(Class<T> type, int length) {
Constructor<?>[] ctrs = type.getConstructors();
// one with DataBoundConstructor is the most reliable
for (Constructor c : ctrs) {
if(c.getAnnotation(DataBoundConstructor.class)!=null) {
if(c.getParameterTypes().length!=length)
throw new IllegalArgumentException(c+" has @DataBoundConstructor but it doesn't match with your .stapler file. Try clean rebuild");
return c;
}
}
// if not, maybe this was from @stapler-constructor,
// so look for the constructor with the expected argument length.
// this is not very reliable.
for (Constructor c : ctrs) {
if(c.getParameterTypes().length==length)
return c;
}
throw new IllegalArgumentException(type+" does not have a constructor with "+length+" arguments");
}
/**
* Determines the constructor parameter names.
*
* <p>
* If there's the .stapler file, load it as a property file and determines the constructor parameter names.
* Otherwise, look for {@link CapturedParameterNames} annotation.
*/
private String[] loadConstructorParamNames(Class<?> type) {
String resourceName = type.getName().replace('.', '/').replace('$','/') + ".stapler";
ClassLoader cl = type.getClassLoader();
if(cl==null)
throw new NoStaplerConstructorException(type+" is a built-in type");
InputStream s = cl.getResourceAsStream(resourceName);
if (s != null) {// load the property file and figure out parameter names
try {
Properties p = new Properties();
p.load(s);
s.close();
String v = p.getProperty("constructor");
if (v.length() == 0) return new String[0];
return v.split(",");
} catch (IOException e) {
throw new IllegalArgumentException("Unable to load " + resourceName, e);
}
}
// look for the one with @DataBoundConstructor and @CapturedParameterNames
Constructor<?>[] ctrs = type.getConstructors();
for (Constructor<?> c : ctrs) {
if (c.getAnnotation(DataBoundConstructor.class) != null) {
CapturedParameterNames cpn = c.getAnnotation(CapturedParameterNames.class);
if (cpn != null) return cpn.value();
// neither was found
throw new NoStaplerConstructorException(
"Unable to find " + resourceName + ". " +
"Run 'mvn clean compile' once to run the annotation processor.");
}
}
throw new NoStaplerConstructorException(
"Unable to find " + resourceName + ". " +
"There's no @DataBoundConstructor on any constructor of " + type);
}
private static void fill(Object bean, String key, Object value) {
StringTokenizer tokens = new StringTokenizer(key);
while(tokens.hasMoreTokens()) {
String token = tokens.nextToken();
boolean last = !tokens.hasMoreTokens(); // is this the last token?
try {
if(last) {
copyProperty(bean,token,value);
} else {
bean = BeanUtils.getProperty(bean,token);
}
} catch (IllegalAccessException x) {
throw new IllegalAccessError(x.getMessage());
} catch (InvocationTargetException x) {
Throwable e = x.getTargetException();
if(e instanceof RuntimeException)
throw (RuntimeException)e;
if(e instanceof Error)
throw (Error)e;
throw new RuntimeException(x);
} catch (NoSuchMethodException e) {
// ignore if there's no such property
}
}
}
/**
* Information about the type.
*/
private final class TypePair {
final Type genericType;
final Class type;
TypePair(Type genericType, Class type) {
this.genericType = genericType;
this.type = type;
}
TypePair(Field f) {
this(f.getGenericType(),f.getType());
}
/**
* Converts the given JSON object (either {@link JSONObject}, {@link JSONArray}, or other primitive types
* in JSON, to the type represented by the 'this' object.
*/
public Object convertJSON(Object o) {
if(o==null) return null;
Lister l = Lister.create(type,genericType);
if (o instanceof JSONObject) {
JSONObject j = (JSONObject) o;
if(l==null) {
// single value conversion
return bindJSON(type,j);
} else {
if(j.has("stapler-class-bag")) {
// this object is a hash from class names to their parameters
// build them into a collection via Lister
ClassLoader cl = stapler.getWebApp().getClassLoader();
for (Map.Entry<String,Object> e : (Set<Map.Entry<String,Object>>)j.entrySet()) {
Object v = e.getValue();
String className = e.getKey().replace('-','.'); // decode JSON-safe class name escaping
try {
Class<?> itemType = cl.loadClass(className);
if (v instanceof JSONObject) {
l.add(bindJSON(itemType, (JSONObject) v));
}
if (v instanceof JSONArray) {
for(Object i : bindJSONToList(itemType, (JSONArray) v))
l.add(i);
}
} catch (ClassNotFoundException e1) {
// ignore unrecognized element
}
}
} else if (Enum.class.isAssignableFrom(l.itemType)) {
// this is a hash of element names as enum constant names
for (Map.Entry<String,Object> e : (Set<Map.Entry<String,Object>>)j.entrySet()) {
Object v = e.getValue();
if (v==null || (v instanceof Boolean && !(Boolean)v))
continue; // skip if the value is null or false
l.add(Enum.valueOf(l.itemType,e.getKey()));
}
} else {
// only one value given to the collection
l.add(new TypePair(l.itemGenericType,l.itemType).convertJSON(j));
}
return l.toCollection();
}
}
if (o instanceof JSONArray) {
JSONArray a = (JSONArray) o;
TypePair itemType = new TypePair(l.itemGenericType,l.itemType);
for (Object item : a)
l.add(itemType.convertJSON(item));
return l.toCollection();
}
if(Enum.class.isAssignableFrom(type))
return Enum.valueOf(type,o.toString());
Converter converter = Stapler.lookupConverter(type);
if (converter==null)
throw new IllegalArgumentException("Unable to convert to "+type);
return converter.convert(type,o);
}
}
/**
* Gets the type of the field/property designate by the given name.
*/
private TypePair getPropertyType(Object bean, String name) throws IllegalAccessException, InvocationTargetException {
try {
PropertyDescriptor propDescriptor = PropertyUtils.getPropertyDescriptor(bean, name);
if(propDescriptor!=null) {
Method m = propDescriptor.getWriteMethod();
if(m!=null)
return new TypePair(m.getGenericParameterTypes()[0], m.getParameterTypes()[0]);
}
} catch (NoSuchMethodException e) {
// no such property
}
// try a field
try {
return new TypePair(bean.getClass().getField(name));
} catch (NoSuchFieldException e) {
// no such field
}
return null;
}
/**
* Sets the property/field value of the given name, by performing a value type conversion if necessary.
*/
private static void copyProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException {
PropertyDescriptor propDescriptor;
try {
propDescriptor =
PropertyUtils.getPropertyDescriptor(bean, name);
} catch (NoSuchMethodException e) {
propDescriptor = null;
}
if ((propDescriptor != null) &&
(propDescriptor.getWriteMethod() == null)) {
propDescriptor = null;
}
if (propDescriptor != null) {
Converter converter = Stapler.lookupConverter(propDescriptor.getPropertyType());
if (converter != null)
value = converter.convert(propDescriptor.getPropertyType(), value);
try {
PropertyUtils.setSimpleProperty(bean, name, value);
} catch (NoSuchMethodException e) {
throw new NoSuchMethodError(e.getMessage());
}
return;
}
// try a field
try {
Field field = bean.getClass().getField(name);
Converter converter = ConvertUtils.lookup(field.getType());
if (converter != null)
value = converter.convert(field.getType(), value);
field.set(bean,value);
} catch (NoSuchFieldException e) {
// no such field
}
}
private void parseMultipartFormData() throws ServletException {
if(parsedFormData!=null) return;
parsedFormData = new HashMap<String,FileItem>();
ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
try {
for( FileItem fi : (List<FileItem>)upload.parseRequest(this) )
parsedFormData.put(fi.getFieldName(),fi);
} catch (FileUploadException e) {
throw new ServletException(e);
}
}
public JSONObject getSubmittedForm() throws ServletException {
if(structuredForm==null) {
String ct = getContentType();
String p = null;
boolean isSubmission; // for error diagnosis, if something is submitted, set to true
if(ct!=null && ct.startsWith("multipart/")) {
isSubmission=true;
parseMultipartFormData();
FileItem item = parsedFormData.get("json");
if(item!=null)
p = item.getString();
} else {
p = getParameter("json");
isSubmission = !getParameterMap().isEmpty();
}
if(p==null) {
// no data submitted
try {
StaplerResponse rsp = Stapler.getCurrentResponse();
if(isSubmission)
rsp.sendError(SC_BAD_REQUEST,"This page expects a form submission");
else
rsp.sendError(SC_BAD_REQUEST,"Nothing is submitted");
rsp.getWriter().close();
throw new Error("This page expects a form submission");
} catch (IOException e) {
throw new Error(e);
}
}
structuredForm = JSONObject.fromObject(p);
}
return structuredForm;
}
public FileItem getFileItem(String name) throws ServletException, IOException {
parseMultipartFormData();
if(parsedFormData==null) return null;
FileItem item = parsedFormData.get(name);
if(item==null || item.isFormField()) return null;
return item;
}
}
|
package org.mindtrails.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.mindtrails.domain.RestExceptions.WaitException;
import org.mindtrails.domain.tracking.TaskLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.*;
import java.util.*;
/**
* You can use this class to get some basic features
* rather than implement everything in the Study interface.
*/
@Data
@Entity
@Table(name = "study")
@DiscriminatorColumn(name="studyType")
@EqualsAndHashCode(exclude={"taskLogs"})
public abstract class BaseStudy implements Study {
private static final Logger LOG = LoggerFactory.getLogger(BaseStudy.class);
private static final Session NOT_STARTED = new Session("NOT_STARTED", "Not Started", 0, 0, new ArrayList<Task>());
private static final Session COMPLETE = new Session("COMPLETE", "Complete", 0, 0, new ArrayList<Task>());
@Id
@TableGenerator(name = "STUDY_GEN", table = "ID_GEN", pkColumnName = "GEN_NAME", valueColumnName = "GEN_VAL", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.TABLE, generator = "STUDY_GEN")
protected long id;
protected String currentSession;
protected int currentTaskIndex = 0;
protected Date lastSessionDate;
protected boolean receiveGiftCards;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "study")
@JsonIgnore
@OrderBy("dateCompleted")
protected List<TaskLog> taskLogs = new ArrayList<>();
public BaseStudy() {}
public BaseStudy(String currentName, int taskIndex, Date lastSessionDate, List<TaskLog> taskLogs, boolean receiveGiftCards) {
this.currentSession = currentName;
this.currentTaskIndex = taskIndex;
this.lastSessionDate = lastSessionDate;
this.taskLogs = taskLogs;
this.receiveGiftCards = receiveGiftCards;
}
@Override
@JsonIgnore
public List<Session> getSessions() {
List<Session> sessions = getStatelessSessions();
sessions.add(COMPLETE);
// Add state to the sessions
boolean complete = true;
for(Session s : sessions) {
if (s.getName().equals(currentSession)) {
s.setCurrent(true);
complete = false;
}
s.setComplete(complete);
setTaskStates(s.getName(), s.getTasks(), currentTaskIndex);
}
return sessions;
}
/**
* This should return a full list of sessions that define the study, but
* does not need to mark them correctly with regards to being completed,
* or inprogress.
* @return
*/
@JsonIgnore
public abstract List<Session> getStatelessSessions();
@Override
public Session nextGiftSession() {
boolean toCurrent = false;
for (Session s : getSessions()) {
if (toCurrent && s.getGiftAmount() > 0) return s;
if (s.isCurrent()) toCurrent = true;
}
return null;
}
@Override
public boolean isReceiveGiftCards() {
return receiveGiftCards;
}
@Override
public void setReceiveGiftCards(boolean value) {
receiveGiftCards = value;
}
/**
* @return Number of days since the last completed session.
*/
public int daysSinceLastSession() {
DateTime last;
DateTime now;
last = new DateTime(lastSessionDate);
now = new DateTime();
return Days.daysBetween(last, now).getDays();
}
@Override
public void completeCurrentTask(double timeOnTask) {
// Log the completion of the task
this.taskLogs.add(new TaskLog(this, timeOnTask));
if (getState().equals(STUDY_STATE.WAIT)){
throw new WaitException();
}
// If this is the last task in a session, then we move to the next session.
if(currentTaskIndex +1 >= getCurrentSession().getTasks().size()) {
this.taskLogs.add(TaskLog.completedSession(this));
completeSession();
} else { // otherwise we just increment the task index.
this.currentTaskIndex = currentTaskIndex + 1;
}
}
@Override
public Date getLastTaskDate() {
if(this.taskLogs == null || this.taskLogs.size() == 0) {
return new Date();
} else {
return taskLogs.get(taskLogs.size()-1).getDateCompleted();
}
}
protected void completeSession() {
List<Session> sessions = getSessions();
boolean next = false;
Session nextSession = getCurrentSession();
for(Session s: sessions) {
if(next == true) { nextSession = s; break; }
if(s.isCurrent()) next = true;
}
this.currentTaskIndex = 0;
this.currentSession = nextSession.getName();
this.lastSessionDate = new Date();
}
@Override
public Session getCurrentSession() {
List<Session> sessions = getSessions();
for(Session s : getSessions()) {
if (s.isCurrent()) {
return s;
}
}
// If there is no current session, return the first session.
sessions.get(0).setCurrent(true);
return sessions.get(0);
}
@Override
public Session getSession(String sessionName) {
for(Session s : getSessions()) {
if (s.getName().equals(sessionName)) {
return s;
}
}
return null;
}
/**
* Returns true if the session is completed, false otherwise.
* @param session
* @return
*/
public boolean completed(String session) {
Session currentSession = getCurrentSession();
if(session == currentSession.getName()) return false;
for(Session s : getSessions()) {
String strName = s.getName();
if (strName.equals(session)) return true;
if (strName.equals(currentSession.getName())) return false;
}
// You can't really get here, since we have looped through all
// the possible values of session.
return false;
}
/**
* This method churns through the list of tasks, setting the "current" and "complete" flags based on the
* current task index. It also uses the task logs to determine the completion date.
*/
protected void setTaskStates(String sessionName, List<Task> tasks, int taskIndex) {
int index = 0;
for (Task t : tasks) {
t.setCurrent(taskIndex == index);
t.setComplete(taskIndex > index);
for(TaskLog log : taskLogs) {
if (log.getSessionName().equals(sessionName) && log.getTaskName().equals(t.getName())
&& (log.getTag()== null || log.getTag().equals(t.getTag()))) {
t.setDateCompleted(log.getDateCompleted());
t.setComplete(true);
t.setTimeOnTask(log.getTimeOnTask());
break;
}
}
index++;
}
}
/**
* May return null if there is no previous session.
*/
@Override
@JsonIgnore
public Session getLastSession() {
List<Session> sessions = getSessions();
Session last = NOT_STARTED;
for(Session s: sessions) {
if (s.getName().equals(currentSession)) break;
last = s;
}
return last;
}
@Override
public void forceToSession(String sessionName) {
this.currentSession = sessionName;
this.currentTaskIndex = 0;
this.lastSessionDate = null;
}
@Override
public STUDY_STATE getState() {
if (currentTaskIndex != 0) return STUDY_STATE.IN_PROGRESS;
if (this.currentSession.equals(COMPLETE.getName())) {
return STUDY_STATE.ALL_DONE;
}
if(daysSinceLastSession() < getCurrentSession().getDaysToWait()) {
return STUDY_STATE.WAIT;
}
return STUDY_STATE.READY;
}
@Override
public String toString() {
return "BaseStudy{" +
"id=" + id +
", currentSession='" + currentSession + '\'' +
", currentTaskIndex=" + currentTaskIndex +
", lastSessionDate=" + lastSessionDate +
", receiveGiftCards=" + receiveGiftCards +
", taskLogs=" + taskLogs +
'}';
}
@Override
public Map<String,Object> getPiPlayerParameters(){
Map<String,Object> params = new HashMap<>();
return params;
}
@Override
/**
* We have a one to one relationship to participant,
* we can just return the unique id of the Study, and
* it is the unique id of the participant.
*/
public long getParticipantId() {
return this.id;
}
}
|
package step.attachments;
import org.bson.types.ObjectId;
public class AttachmentMeta {
ObjectId _id;
String name;
public AttachmentMeta(ObjectId id) {
super();
_id = id;
}
public AttachmentMeta() {
super();
_id = new ObjectId();
}
public ObjectId getId() {
return _id;
}
public void setId(ObjectId id) {
this._id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package world;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import command.Command;
import command.DoTimesCommand;
import command.ForCommand;
import command.IfCommand;
import command.LoopCommand;
import command.RepeatCommand;
import javafx.scene.paint.Color;
import parser.Parser;
import turtle.Turtle;
public abstract class World {
protected int height;
protected int width;
protected Turtle myTurtle;
private Map<Double, String> loopMap;
private List<Class> loopList;
private Parser myParser;
private static final int DEFAULT_HEIGHT = 100;
private static final int DEFAULT_WIDTH = 100;
private static final Color TURTLE_DEFAULT = Color.BLACK;
public World() throws IOException {
height = DEFAULT_HEIGHT;
width = DEFAULT_WIDTH;
myTurtle = new Turtle(TURTLE_DEFAULT);
myParser = new Parser("English");
makeLoops();
}
public World(int h, int w) throws IOException{
height = h;
width = w;
myTurtle = new Turtle(TURTLE_DEFAULT);
myParser = new Parser("English");
makeLoops();
}
public World(int h, int w, Turtle t, String language) throws IOException{
height = h;
width = w;
myTurtle = t;
myParser = new Parser(language);
makeLoops();
}
private void makeLoops(){
makeLoopMap();
makeLoopList();
}
private void makeLoopMap(){
loopMap = new HashMap<>();
loopMap.put(0., "Loop");
loopMap.put(1., "Done");
}
private void makeLoopList(){
loopList = new ArrayList<>();
loopList.add(new LoopCommand().getClass());
loopList.add(new IfCommand().getClass());
}
public abstract void fixPosition();
public void listen(String s) {
int numCmds = myParser.initializeCommands(s);
String param = "";
for (int i = 0; i < numCmds; i++)
param = runCommand(param);
}
private String runCommand(String s){
Command c = myParser.parse(s);
if(isLoop(c)){
return loopMap.get(myTurtle.act(c));
}
return myTurtle.act(c);
}
private boolean isLoop(Command c){
if(loopList.contains(c.getClass()))
return true;
return false;
}
public void setHeight(int h){
height = h;
}
public int getHeight() {
return height;
}
public void setWidth(int w){
width = w;
}
public int getWidth() {
return width;
}
}
|
package ch.openech.dm.person;
import java.util.ArrayList;
import java.util.List;
import org.joda.time.LocalDate;
import ch.openech.dm.EchFormats;
import ch.openech.dm.Event;
import ch.openech.dm.code.NationalityStatus;
import ch.openech.dm.common.Address;
import ch.openech.dm.common.DwellingAddress;
import ch.openech.dm.common.Place;
import ch.openech.dm.contact.Contact;
import ch.openech.dm.person.types.PartnerShipAbolition;
import ch.openech.dm.person.types.Religion;
import ch.openech.dm.person.types.TypeOfRelationship;
import ch.openech.dm.types.Language;
import ch.openech.dm.types.TypeOfResidence;
import ch.openech.dm.types.YesNo;
import ch.openech.mj.edit.validation.Validation;
import ch.openech.mj.edit.validation.ValidationMessage;
import ch.openech.mj.model.EmptyValidator;
import ch.openech.mj.model.Keys;
import ch.openech.mj.model.annotation.Changes;
import ch.openech.mj.model.annotation.Code;
import ch.openech.mj.model.annotation.Enabled;
import ch.openech.mj.model.annotation.OnChange;
import ch.openech.mj.model.annotation.Reference;
import ch.openech.mj.model.annotation.Required;
import ch.openech.mj.model.annotation.Size;
import ch.openech.mj.resources.Resources;
import ch.openech.mj.util.BusinessRule;
import ch.openech.mj.util.DateUtils;
import ch.openech.mj.util.StringUtils;
public class Person implements Validation {
public static final Person PERSON = Keys.of(Person.class);
public transient PersonEditMode editMode;
// Der eCH - Event, mit dem die aktuelle Version der Person erstellt oder
public Event event;
@Reference
public final PersonIdentification personIdentification = new PersonIdentification();
@Size(EchFormats.baseName)
public String originalName, alliancePartnershipName, aliasName, otherName, callName;
public Place placeOfBirth;
public LocalDate dateOfDeath;
public final MaritalStatus maritalStatus = new MaritalStatus();
public final Separation separation = new Separation();
@Enabled("isMaritalStatusCanceled")
public PartnerShipAbolition cancelationReason;
public final Nationality nationality = new Nationality();
public final ContactPerson contactPerson = new ContactPerson();
public Language languageOfCorrespondance = Language.de;
@Required
public Religion religion = Religion.unbekannt;
@Enabled("!isSwiss")
public final Foreign foreign = new Foreign();
@OnChange("updateResidence")
public TypeOfResidence typeOfResidence = TypeOfResidence.hasMainResidence;
public final Residence residence = new Residence();
public LocalDate arrivalDate, departureDate;
public Place comesFrom, goesTo;
public Address comesFromAddress, goesToAddress;
public DwellingAddress dwellingAddress = new DwellingAddress(); // Fast immer required, aber nicht bei Birth
public final List<Occupation> occupation = new ArrayList<Occupation>();
public final List<Relation> relation = new ArrayList<Relation>();
public final NameOfParents nameOfParents = new NameOfParents();
@Enabled("isSwiss")
public final List<PlaceOfOrigin> placeOfOrigin = new ArrayList<PlaceOfOrigin>();
@Code
public String dataLock = "0";
@Code
public String paperLock = "0";
public PersonExtendedInformation personExtendedInformation;
public Contact contact;
@Changes("residence")
public void updateResidence() {
if (typeOfResidence == TypeOfResidence.hasOtherResidence) {
residence.reportingMunicipality = null;
}
}
public Relation getFather() {
if (Keys.isKeyObject(this)) return Keys.methodOf(this, "father", Relation.class);
return getRelation(TypeOfRelationship.Vater);
}
public void setFather(Relation relation) {
setRelation(TypeOfRelationship.Vater, relation);
}
public Relation getMother() {
if (Keys.isKeyObject(this)) return Keys.methodOf(this, "mother", Relation.class);
return getRelation(TypeOfRelationship.Mutter);
}
public void setMother(Relation relation) {
setRelation(TypeOfRelationship.Mutter, relation);
}
private void setRelation(TypeOfRelationship typeOfRelationship, Relation relation) {
for (Relation r : Person.this.relation) {
if (r.typeOfRelationship == relation.typeOfRelationship) {
Person.this.relation.remove(r);
break;
}
}
Person.this.relation.add(relation);
}
public String getId() {
return personIdentification.getId();
}
public boolean isPersisent() {
return personIdentification != null;
}
public boolean isMale() {
return personIdentification.isMale();
}
public boolean isFemale() {
return personIdentification.isFemale();
}
public boolean isAlive() {
return dateOfDeath == null;
}
public boolean isMarried() {
return maritalStatus.isVerheiratet();
}
public boolean hasPartner() {
return maritalStatus.isPartnerschaft();
}
public boolean isSeparated() {
return separation.separation != null;
}
public boolean hasGardianMeasure() {
return getGardian() != null;
}
// Ehepartner oder Partner in eingetragener Partnerschaft
public Relation getPartner() {
for (Relation r : relation) {
if (r.isPartnerType()) return r;
}
return null;
}
// Beistand / Beirat oder Vormund
public Relation getGardian() {
for (Relation r : relation) {
if (r.isCareRelation()) return r;
}
return null;
}
public Relation getRelation(TypeOfRelationship type) {
for (Relation r : relation) {
if (type == r.typeOfRelationship) return r;
}
Relation newRelation = new Relation();
newRelation.typeOfRelationship = type;
if (newRelation.isParent()) newRelation.care = YesNo.Yes;
relation.add(newRelation);
return newRelation;
}
public boolean isSwiss() {
if (nationality.nationalityStatus != NationalityStatus.with) return false;
return nationality.nationalityCountry.isSwiss();
}
public boolean isMaritalStatusCanceled() {
return maritalStatus.isPartnerschaftAufgeloest() || maritalStatus.isGeschieden();
}
public boolean isMainResidence() {
return typeOfResidence == TypeOfResidence.hasMainResidence;
}
public String getStreet() {
if (Keys.isKeyObject(this)) return Keys.methodOf(this, "street", String.class);
if (dwellingAddress != null && dwellingAddress.mailAddress != null) {
return dwellingAddress.mailAddress.street;
} else {
return null;
}
}
public String getStreetNumber() {
if (Keys.isKeyObject(this)) return Keys.methodOf(this, "streetNumber", String.class);
if (dwellingAddress != null && dwellingAddress.mailAddress != null) {
return dwellingAddress.mailAddress.houseNumber.houseNumber;
} else {
return null;
}
}
public String getTown() {
if (Keys.isKeyObject(this)) return Keys.methodOf(this, "town", String.class);
if (dwellingAddress != null && dwellingAddress.mailAddress != null) {
return dwellingAddress.mailAddress.town;
} else {
return null;
}
}
// used in ComboBox
@Override
public String toString() {
return personIdentification.firstName + " " + personIdentification.officialName + ", " + DateUtils.formatPartialCH(personIdentification.dateOfBirth);
}
public String toHtmlMultiLine() {
StringBuilder s = new StringBuilder();
s.append("<HTML>");
toHtmlMultiLine(s);
s.append("</HTML>");
return s.toString();
}
private void toHtmlMultiLine(StringBuilder s) {
append(s, "Person.officialName", personIdentification.officialName);
append(s, "Person.firstName", personIdentification.firstName);
if (personIdentification.dateOfBirth != null) {
append(s, "Person.dateOfBirth", DateUtils.formatPartial(personIdentification.dateOfBirth));
}
s.append("<BR> ");
}
private void append(StringBuilder s, String resourceName, String text) {
String labelText = Resources.getString(resourceName);
s.append(labelText);
s.append(": ");
if (!StringUtils.isBlank(text)) {
s.append(text);
} else {
s.append("-");
}
s.append("<BR>");
}
// validation
public void validate(List<ValidationMessage> resultList) {
validateBirthAfterParents(resultList);
validateRelations(resultList);
validateDeathNotBeforeBirth(resultList);
if (editMode == PersonEditMode.MOVE_IN) {
EmptyValidator.validate(resultList, this, PERSON.arrivalDate);
}
if (editMode != PersonEditMode.BIRTH) {
validateForeign(resultList);
}
validatePlaceOfOrigin(resultList);
if (editMode != PersonEditMode.BIRTH) {
validateResidence(resultList);
}
}
private void validateForeign(List<ValidationMessage> resultList) {
if (!nationality.isSwiss()) {
if (foreign.isEmpty()) {
resultList.add(new ValidationMessage(PERSON.foreign, "Ausländerkategorie erforderlich"));
}
}
}
private void validatePlaceOfOrigin(List<ValidationMessage> resultList) {
if (nationality.isSwiss()) {
if (placeOfOrigin.isEmpty()) {
resultList.add(new ValidationMessage(PERSON.placeOfOrigin, "Heimatort erforderlich"));
}
}
}
@BusinessRule("Die Geburt einer Person muss nach derjenigen seiner Eltern sein")
public void validateBirthAfterParents(List<ValidationMessage> resultList) {
Relation relation = getMother();
if (!isBirthAfterRelation(relation)) {
resultList.add(new ValidationMessage(PERSON.personIdentification.dateOfBirth, "Geburtsdatum muss nach demjenigen der Mutter sein"));
}
relation = getFather();
if (!isBirthAfterRelation(relation)) {
resultList.add(new ValidationMessage(PERSON.personIdentification.dateOfBirth, "Geburtsdatum muss nach demjenigen des Vaters sein"));
}
};
private boolean isBirthAfterRelation(Relation relation) {
LocalDate dateOfBirth = DateUtils.convertToLocalDate(personIdentification.dateOfBirth);
if (dateOfBirth == null) return true;
if (relation == null) return true;
PersonIdentification partner = relation.partner;
if (partner == null) return true;
if (partner.dateOfBirth == null) return true;
// strange: isAfter can compare with PartialDate, but is not on PartialDate
return dateOfBirth.isAfter(partner.dateOfBirth);
}
private void validateRelations(List<ValidationMessage> resultList) {
validateMotherIsFemale(resultList);
validateFatherIsMale(resultList);
}
@BusinessRule("Mutter muss weiblich sein")
private void validateMotherIsFemale(List<ValidationMessage> resultList) {
Relation relation = getMother();
if (relation == null || relation.partner == null || relation.partner.sex == null) return;
if (!relation.partner.isFemale()) {
resultList.add(new ValidationMessage(Person.PERSON.getMother(), "Mutter muss weiblich sein"));
}
}
@BusinessRule("Vater muss männlich sein")
private void validateFatherIsMale(List<ValidationMessage> resultList) {
Relation relation = getFather();
if (relation == null || relation.partner == null || relation.partner.sex == null) return;
if (!relation.partner.isMale()) {
resultList.add(new ValidationMessage(Person.PERSON.getFather(), "Vater muss männlich sein"));
}
}
@BusinessRule("Todesdatum darf nicht vor Geburtsdatum sein")
private void validateDeathNotBeforeBirth(List<ValidationMessage> resultList) {
if (personIdentification.dateOfBirth == null || dateOfDeath == null) return;
if (dateOfDeath.isBefore(personIdentification.dateOfBirth)) {
resultList.add(new ValidationMessage(PERSON.dateOfDeath, "Todesdatum darf nicht vor Geburtsdatum sein"));
}
}
@BusinessRule("Ereignis darf nicht vor Geburt der Person stattfinden")
public static void validateEventNotBeforeBirth(List<ValidationMessage> validationMessages, PersonIdentification personIdentification, LocalDate date, Object key) {
if (personIdentification != null && personIdentification.dateOfBirth != null && date != null) {
if (date.isBefore(personIdentification.dateOfBirth)) {
validationMessages.add(new ValidationMessage(key, "Datum darf nicht vor Geburt der Person sein"));
}
}
}
@BusinessRule("Die Anzahl von Haupt- und Nebenorten muss dem gewählten Meldeverhältnis entsprechen")
private void validateResidence(List<ValidationMessage> resultList) {
String validationMessage = residence.validate(typeOfResidence);
if (validationMessage != null) {
resultList.add(new ValidationMessage(PERSON.residence, validationMessage));
}
}
}
|
package io.spine.server.delivery;
import io.spine.server.event.DuplicateEventException;
import io.spine.server.type.EventEnvelope;
import java.util.Collection;
import java.util.function.Predicate;
/**
* The part of {@link Inbox} responsible for processing incoming
* {@link io.spine.server.type.EventEnvelope events}.
*
* @param <I>
* the type of identifier or inbox target entities
*/
final class InboxOfEvents<I> extends InboxPart<I, EventEnvelope> {
InboxOfEvents(Inbox.Builder<I> builder) {
super(builder, builder.getEventEndpoints());
}
@Override
protected void setRecordPayload(EventEnvelope envelope, InboxMessage.Builder builder) {
builder.setEvent(envelope.outerObject());
}
@Override
protected String extractUuidFrom(EventEnvelope envelope) {
return envelope.id()
.getValue();
}
@Override
protected EventEnvelope asEnvelope(InboxMessage message) {
return EventEnvelope.of(message.getEvent());
}
@Override
protected Dispatcher dispatcherWith(Collection<InboxMessage> deduplicationSource) {
return new EventDispatcher(deduplicationSource);
}
/**
* A strategy of event delivery from this {@code Inbox} to the event targets.
*/
class EventDispatcher extends Dispatcher {
private EventDispatcher(Collection<InboxMessage> deduplicationSource) {
super(deduplicationSource);
}
@Override
protected Predicate<? super InboxMessage> filterByType() {
return (Predicate<InboxMessage>) InboxMessage::hasEvent;
}
@Override
protected RuntimeException onDuplicateFound(InboxMessage duplicate) {
return new DuplicateEventException(duplicate.getEvent());
}
}
}
|
package com.uw.android310.lesson5;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
|
// This file is part of Serleena.
// Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle.
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
package com.kyloth.serleena.sensors;
public interface IHeadingManager {
public void attachObserver(IHeadingObserver observer);
public void detachObserver(IHeadingObserver observer)
throws IllegalArgumentException;
/**
* Metodo "notify" basato sull'omonimo metodo della classe "Subject" del
* Design Pattern "Observer".
*/
public void notifyObservers();
}
|
package com.thoughtworks.fam.web;
import com.thoughtworks.fam.service.UserAssetService;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.mockito.Mockito.mock;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class UserAssetControllerTest {
private MockMvc mockMvc;
@InjectMocks
private UserAssetController userAssetController;
private UserAssetService userAssetService;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(userAssetController).build();
userAssetService = mock(UserAssetService.class);
ReflectionTestUtils.setField(userAssetController, "userAssetService", userAssetService);
}
@Test
public void should_access_to_get_user_assets() throws Exception {
this.mockMvc.perform(get("/asset/sqlin@thoughtworks.com/list"))
.andExpect(status().isOk());
}
@Test(expected = RuntimeException.class)
public void should_get_runtime_exception() throws Exception {
this.mockMvc.perform(get("/user//assets", null));
}
}
|
package com.witchworks.common.crafting.cauldron;
import com.witchworks.api.BrewRegistry;
import com.witchworks.api.CauldronRegistry;
import com.witchworks.api.RitualRegistry;
import com.witchworks.api.brew.BrewEffect;
import com.witchworks.api.brew.BrewUtils;
import com.witchworks.api.recipe.BrewModifier;
import com.witchworks.api.recipe.BrewSimpleModifier;
import com.witchworks.api.ritual.IRitual;
import com.witchworks.common.block.ModBlocks;
import com.witchworks.common.block.natural.fluid.Fluids;
import com.witchworks.common.brew.ModBrews;
import com.witchworks.common.item.ModItems;
import com.witchworks.common.lib.LibMod;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.init.MobEffects;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
@SuppressWarnings("WeakerAccess")
public final class CauldronCrafting {
private CauldronCrafting() {
}
public static void init() {
//Some recipes that return the non-dyed version of an Item
registerItemProcess(FluidRegistry.WATER, Items.LEATHER_HELMET, Items.LEATHER_HELMET, false);
registerItemProcess(FluidRegistry.WATER, Items.LEATHER_CHESTPLATE, Items.LEATHER_CHESTPLATE, false);
registerItemProcess(FluidRegistry.WATER, Items.LEATHER_LEGGINGS, Items.LEATHER_LEGGINGS, false);
registerItemProcess(FluidRegistry.WATER, Items.LEATHER_BOOTS, Items.LEATHER_BOOTS, false);
registerItemProcess(FluidRegistry.WATER, Items.SHIELD, Items.SHIELD, false);
//Cooking with Oil
registerItemProcess(Fluids.MUNDANE_OIL, Items.PORKCHOP, Items.COOKED_PORKCHOP, true);
registerItemProcess(Fluids.MUNDANE_OIL, Items.MUTTON, Items.COOKED_MUTTON, true);
registerItemProcess(Fluids.MUNDANE_OIL, Items.RABBIT, Items.COOKED_RABBIT, true);
registerItemProcess(Fluids.MUNDANE_OIL, Items.CHICKEN, Items.COOKED_CHICKEN, true);
registerItemProcess(Fluids.MUNDANE_OIL, Items.BEEF, Items.COOKED_BEEF, true);
registerItemProcess(Fluids.MUNDANE_OIL, Items.FISH, Items.COOKED_FISH, true);
registerItemProcess(Fluids.MUNDANE_OIL, Items.POTATO, Items.BAKED_POTATO, true);
registerItemProcess(Fluids.MUNDANE_OIL, getStack(Items.FISH, 1, 1), getStack(Items.COOKED_FISH, 1, 1), true);
//Cooking and Processing with Water
registerItemProcess(FluidRegistry.WATER, ModItems.empty_honeycomb, ModItems.wax, true);
registerItemProcess(FluidRegistry.WATER, ModItems.honeycomb, ModItems.honey, true);
registerItemProcess(FluidRegistry.WATER, ModItems.hoof, Items.SLIME_BALL, true);
registerItemProcess(FluidRegistry.WATER, getStack(Blocks.LOG2, 1, 0), getStack(ModItems.catechu, 6, 0), true);
registerItemProcess(FluidRegistry.WATER, getStack(ModItems.wormwood, 1, 0), getStack(ModItems.absinthe_green), true);
//Banner pattern removal
for (int i = 0; i < 16; i++) {
registerItemProcess(FluidRegistry.WATER, getStack(Items.BANNER, 1, i), getStack(Items.BANNER, 1, i), true);
}
CauldronRegistry.registerFluidIngredient(ModItems.honey, new FluidStack(Fluids.HONEY, 1000));
CauldronRegistry.registerFluidIngredient(Items.POTATO, new FluidStack(Fluids.MUNDANE_OIL, 1000));
//Todo: Better recipe for kelp seeds.
registerItemRitual("seed_kelp", getStack(ModItems.seed_kelp, 2), 5
, getStack(Items.WHEAT_SEEDS, 1), Blocks.WATERLILY);
registerItemRitual("golden_apple", getStack(Items.GOLDEN_APPLE, 1, 1), 8
, getStack(Blocks.GOLD_BLOCK, 8), Items.APPLE);
registerItemRitual("cobweb", getStack(Blocks.WEB), 2
, getStack(Items.STRING, 4), Items.SLIME_BALL);
registerItemRitual("string", getStack(Items.STRING, 6), 2
, getStack(ModItems.kenaf, 2));
registerItemRitual("leather", getStack(Items.LEATHER, 2), 2
, getStack(Items.ROTTEN_FLESH, 2), ModItems.salt);
registerItemRitual("wax_from_leather", getStack(ModItems.wax, 2), 2
, getStack(Items.LEATHER, 2), ModItems.salt);
registerItemRitual("slime", getStack(Items.SLIME_BALL, 4), 2
, getStack(Items.DYE, 1, 2), Items.ROTTEN_FLESH, Items.WHEAT, ModItems.salt);
registerItemRitual("extra_bonemeal", getStack(Items.DYE, 6, 15), 3
, getStack(Items.BONE));
registerItemRitual("mycelia", getStack(Blocks.MYCELIUM, 4), 6
, getStack(Blocks.DIRT, 4), Blocks.RED_MUSHROOM, Blocks.BROWN_MUSHROOM, Items.SUGAR, Items.FERMENTED_SPIDER_EYE);
registerItemRitual("prismarine", getStack(Items.PRISMARINE_SHARD, 4), 6
, getStack(Items.DYE, 8, 4), Blocks.STONE, ModBlocks.coquina);
registerItemRitual("prismarine_crystals", getStack(Items.PRISMARINE_CRYSTALS, 4), 6
, getStack(Items.DYE, 8, 4), ModBlocks.coquina, Items.GLOWSTONE_DUST);
registerItemRitual("vines", getStack(Blocks.VINE, 4), 4
, getStack(Items.STRING, 4), ModItems.wormwood);
registerItemRitual("chorus_fruit", getStack(Items.CHORUS_FRUIT, 1), 8
, getStack(Items.ENDER_EYE, 4), getStack(ModItems.gem, 1, 1), ModItems.mandrake_root, Items.ENDER_PEARL);
registerItemRitual("grass", getStack(Blocks.GRASS, 4), 4
, getStack(Blocks.DIRT, 4), Items.WHEAT_SEEDS, ModItems.seed_garlic);
registerItemRitual("coarse_dirt", getStack(Blocks.DIRT, 4, 1), 2
, getStack(Blocks.DIRT, 4), ModItems.salt);
registerItemRitual("podzol", getStack(Blocks.DIRT, 4, 2), 2
, getStack(Blocks.DIRT, 4), Blocks.LEAVES);
registerItemRitual("red_sand", getStack(Blocks.SAND, 4, 1), 2
, getStack(Blocks.SAND, 4));
registerItemRitual("gemstone_amalgam", getStack(ModItems.gemstone_amalgam, 1, 0), 4
, getStack(Items.EMERALD, 1, 0), getStack(ModItems.gem, 1, 9), getStack(ModItems.gem, 1, 1));
registerItemRitual("moldavite", getStack(ModItems.gem, 1, 1), 8
, getStack(Items.DYE, 1, 2), Blocks.SAND);
registerItemRitual("alexandrite", getStack(ModItems.gem, 1, 9), 8
, getStack(Items.DYE, 1, 6), Blocks.SAND);
registerItemRitual("bloodstone", getStack(ModItems.gem, 1, 5), 8
, getStack(Items.DYE, 1, 1), Blocks.SAND);
registerItemRitual("nuummite", getStack(ModItems.gem, 1, 2), 8
, getStack(Items.DYE, 1, 0), Blocks.SAND);
registerItemRitual("malachite", getStack(ModItems.gem, 1, 7), 8
, getStack(Items.DYE, 1, 12), Blocks.SAND);
registerItemRitual("quartz", getStack(Items.QUARTZ), 8
, getStack(Items.DYE, 4, 15), Blocks.SAND, Items.GHAST_TEAR);
registerItemRitual("albedo", getStack(ModItems.albedo, 4, 0), 4
, getStack(Blocks.STONE, 4), ModItems.white_sage);
registerBrewRecipe(BrewRegistry.Brew.LINGER, new BrewEffect(ModBrews.MARS_WATER, 500, 0)
, getStack(Items.IRON_NUGGET, 6), Items.POISONOUS_POTATO, Items.ROTTEN_FLESH, ModItems.salt, getStack(ModItems.gem, 1, 6));
registerBrewRecipe(BrewRegistry.Brew.DRINK, new BrewEffect(ModBrews.SKIN_TINT, 500, 0)
, getStack(Items.DYE, 1, 0), Items.NETHER_WART);
registerBrewRecipe(BrewRegistry.Brew.DRINK, new BrewEffect(ModBrews.SKIN_TINT, 500, 1)
, getStack(Items.DYE, 1, 1), Items.NETHER_WART);
registerBrewRecipe(BrewRegistry.Brew.DRINK, new BrewEffect(ModBrews.SKIN_TINT, 500, 2)
, getStack(Items.DYE, 1, 2), Items.NETHER_WART);
registerBrewRecipe(BrewRegistry.Brew.DRINK, new BrewEffect(ModBrews.SKIN_TINT, 500, 3)
, getStack(Items.DYE, 1, 3), Items.NETHER_WART);
registerBrewRecipe(BrewRegistry.Brew.DRINK, new BrewEffect(ModBrews.SKIN_TINT, 500, 4)
, getStack(Items.DYE, 1, 4), Items.NETHER_WART);
registerBrewRecipe(BrewRegistry.Brew.DRINK, new BrewEffect(ModBrews.SKIN_TINT, 500, 5)
, getStack(Items.DYE, 1, 5), Items.NETHER_WART);
registerBrewRecipe(BrewRegistry.Brew.DRINK, new BrewEffect(ModBrews.SKIN_TINT, 500, 6)
, getStack(Items.DYE, 1, 6), Items.NETHER_WART);
registerBrewRecipe(BrewRegistry.Brew.DRINK, new BrewEffect(ModBrews.SKIN_TINT, 500, 7)
, getStack(Items.DYE, 1, 7), Items.NETHER_WART);
registerBrewRecipe(BrewRegistry.Brew.DRINK, new BrewEffect(ModBrews.SKIN_TINT, 500, 8)
, getStack(Items.DYE, 1, 8), Items.NETHER_WART);
registerBrewRecipe(BrewRegistry.Brew.DRINK, new BrewEffect(ModBrews.SKIN_TINT, 500, 9)
, getStack(Items.DYE, 1, 9), Items.NETHER_WART);
registerBrewRecipe(BrewRegistry.Brew.DRINK, new BrewEffect(ModBrews.SKIN_TINT, 500, 10)
, getStack(Items.DYE, 1, 10), Items.NETHER_WART);
registerBrewRecipe(BrewRegistry.Brew.DRINK, new BrewEffect(ModBrews.SKIN_TINT, 500, 11)
, getStack(Items.DYE, 1, 11), Items.NETHER_WART);
registerBrewRecipe(BrewRegistry.Brew.DRINK, new BrewEffect(ModBrews.SKIN_TINT, 500, 12)
, getStack(Items.DYE, 1, 12), Items.NETHER_WART);
registerBrewRecipe(BrewRegistry.Brew.DRINK, new BrewEffect(ModBrews.SKIN_TINT, 500, 13)
, getStack(Items.DYE, 1, 13), Items.NETHER_WART);
registerBrewRecipe(BrewRegistry.Brew.DRINK, new BrewEffect(ModBrews.SKIN_TINT, 500, 14)
, getStack(Items.DYE, 1, 14), Items.NETHER_WART);
registerBrewRecipe(BrewRegistry.Brew.DRINK, new BrewEffect(ModBrews.SKIN_TINT, 500, 15)
, getStack(Items.DYE, 1, 15), Items.NETHER_WART);
registerBrewRecipe(BrewRegistry.Brew.DRINK, new BrewEffect(ModBrews.SKIN_TINT, 500, 3)
, getStack(ModItems.catechu, 1, 0), Items.NETHER_WART);
registerBrewRecipe(BrewRegistry.Brew.DRINK, new BrewEffect(ModBrews.OVERCOAT, 2500, 0)
, getStack(ModItems.wool_of_bat, 1, 0), ModItems.tongue_of_dog, ModItems.silver_scales, ModItems.tulsi, ModItems.dimensional_sand, Items.IRON_NUGGET, Items.NETHER_WART);
registerBrewRecipe(BrewRegistry.Brew.DRINK, new BrewEffect(ModBrews.ABSENCE, 1, 0)
, getStack(ModItems.salt, 1, 0), Items.BONE, Items.IRON_NUGGET, Items.NETHER_WART);
registerBrewRecipe(BrewRegistry.Brew.SPLASH, new BrewEffect(ModBrews.ABSENCE, 1, 0)
, getStack(ModItems.salt, 1, 0), Items.BONE, Items.IRON_NUGGET, Items.NETHER_WART, Items.GUNPOWDER);
registerBrewRecipe(BrewRegistry.Brew.LINGER, new BrewEffect(ModBrews.ABSENCE, 50, 0)
, getStack(ModItems.salt, 1, 0), Items.BONE, Items.IRON_NUGGET, Items.NETHER_WART, Items.DRAGON_BREATH);
registerEffect(getStack(Items.DYE, 1, 0)
, new PotionEffect(MobEffects.BLINDNESS, 500), true);
registerEffect(getStack(Items.ROTTEN_FLESH)
, new PotionEffect(MobEffects.HUNGER, 500), false);
registerEffect(getStack(Blocks.END_STONE)
, new PotionEffect(MobEffects.SLOWNESS, 500), false);
registerEffect(getStack(Items.SPIDER_EYE)
, new PotionEffect(MobEffects.POISON, 500), false);
registerEffect(getStack(Items.GHAST_TEAR)
, new PotionEffect(MobEffects.REGENERATION, 500), false);
registerEffect(getStack(Items.GOLDEN_CARROT)
, new PotionEffect(MobEffects.NIGHT_VISION, 500), false);
registerEffect(getStack(Items.SUGAR)
, new PotionEffect(MobEffects.SPEED, 500), false);
registerEffect(getStack(Items.MAGMA_CREAM)
, new PotionEffect(MobEffects.FIRE_RESISTANCE, 500), false);
registerEffect(getStack(Items.BLAZE_POWDER)
, new PotionEffect(MobEffects.STRENGTH, 500), false);
registerEffect(getStack(Items.RABBIT_FOOT)
, new PotionEffect(MobEffects.JUMP_BOOST, 500), false);
registerEffect(getStack(Items.SPECKLED_MELON)
, new PotionEffect(MobEffects.INSTANT_HEALTH, 1), false);
registerEffect(getStack(Items.FISH, 1, 3)
, new PotionEffect(MobEffects.WATER_BREATHING, 500), true);
registerEffect(getStack(Blocks.RED_FLOWER, 1, 1)
, new PotionEffect(MobEffects.LUCK, 500), true);
registerEffect(getStack(ModItems.wax)
, new PotionEffect(MobEffects.SLOWNESS, 500), false);
registerEffect(getStack(Items.FERMENTED_SPIDER_EYE)
, new PotionEffect(MobEffects.WEAKNESS, 500), false);
registerEffect(getStack(Items.POISONOUS_POTATO)
, new PotionEffect(MobEffects.NAUSEA, 500), false);
registerEffect(getStack(ModItems.belladonna)
, new PotionEffect(MobEffects.WITHER, 500), false);
registerEffect(getStack(ModItems.asphodel)
, new PotionEffect(MobEffects.UNLUCK, 500), false);
registerEffect(getStack(ModItems.lavender)
, new PotionEffect(MobEffects.HASTE, 500), false);
registerEffect(getStack(Items.PRISMARINE_CRYSTALS)
, new PotionEffect(MobEffects.GLOWING, 500), false);
registerEffect(getStack(Items.PRISMARINE_SHARD)
, new PotionEffect(MobEffects.MINING_FATIGUE, 500), false);
registerEffect(getStack(Items.SHULKER_SHELL)
, new PotionEffect(MobEffects.LEVITATION, 500), false);
registerEffect(getStack(Items.NETHER_STAR)
, new PotionEffect(MobEffects.RESISTANCE, 500), false);
registerEffect(getStack(ModBlocks.coquina)
, BrewRegistry.getDefault(ModBrews.SHELL_ARMOR), false);
registerEffect(getStack(ModItems.thistle)
, new PotionEffect(MobEffects.HEALTH_BOOST, 200), false);
registerEffect(getStack(Items.GOLDEN_APPLE)
, new PotionEffect(MobEffects.ABSORPTION, 200), true);
registerEffect(getStack(ModItems.heart)
, new PotionEffect(MobEffects.RESISTANCE, 200), false);
registerEffect(getStack(ModItems.mint)
, BrewRegistry.getDefault(ModBrews.EXTINGUISH_FIRES), false);
registerEffect(getStack(ModItems.white_sage)
, BrewRegistry.getDefault(ModBrews.HOLY_WATER), false);
registerEffect(getStack(Blocks.WEB)
, BrewRegistry.getDefault(ModBrews.SPIDER_NIGHTMARE), false);
registerEffect(getStack(Items.SNOWBALL)
, BrewRegistry.getDefault(ModBrews.FROSTBITE), false);
registerEffect(getStack(Blocks.TNT)
, BrewRegistry.getDefault(ModBrews.VOLATILE), false);
registerEffect(getStack(ModItems.aconitum)
, BrewRegistry.getDefault(ModBrews.WOLFSBANE), false);
registerEffect(getStack(ModItems.wormwood)
, BrewRegistry.getDefault(ModBrews.BANE_ARTHROPODS), false);
registerEffect(getStack(ModItems.kelp)
, BrewRegistry.getDefault(ModBrews.PATH_OF_THE_DEEP), false);
registerEffect(getStack(ModItems.silphium)
, BrewRegistry.getDefault(ModBrews.GROW_FLOWER), false);
registerEffect(getStack(ModItems.seed_silphium)
, BrewRegistry.getDefault(ModBrews.HARVEST), false);
registerEffect(getStack(ModItems.dimensional_sand)
, BrewRegistry.getDefault(ModBrews.ENDER_INHIBITION), false);
registerEffect(getStack(ModItems.gem, 1, 8)
, BrewRegistry.getDefault(ModBrews.TILL_LAND), true);
registerEffect(getStack(ModItems.gem, 1, 6)
, BrewRegistry.getDefault(ModBrews.ROCK_PULVERIZE), true);
registerEffect(getStack(Items.DYE, 1, 15)
, BrewRegistry.getDefault(ModBrews.FERTILIZE), false);
registerEffect(getStack(Blocks.PACKED_ICE)
, BrewRegistry.getDefault(ModBrews.SNOW_TRAIL), false);
registerEffect(getStack(Items.IRON_NUGGET)
, BrewRegistry.getDefault(ModBrews.SINKING), false);
registerEffect(getStack(Blocks.BROWN_MUSHROOM)
, BrewRegistry.getDefault(ModBrews.PRUNE_LEAVES), false);
registerEffect(getStack(Blocks.RED_MUSHROOM)
, BrewRegistry.getDefault(ModBrews.AUTO_PLANT), false);
registerEffect(getStack(ModItems.ginger)
, BrewRegistry.getDefault(ModBrews.IGNITION), false);
registerEffect(getStack(ModItems.carnivorous_tooth)
, BrewRegistry.getDefault(ModBrews.OUTCASTS_SHAME), false);
registerEffect(getStack(ModItems.wool_of_bat)
, BrewRegistry.getDefault(ModBrews.GRACE), false);
registerEffect(getStack(ModItems.tulsi)
, BrewRegistry.getDefault(ModBrews.PURIFY), false);
registerEffect(getStack(Items.GOLDEN_APPLE, 1, 1)
, BrewRegistry.getDefault(ModBrews.NOTCHED), true);
registerEffect(getStack(Blocks.MYCELIUM)
, BrewRegistry.getDefault(ModBrews.MYCOLOGICAL_CORRUPTION), false);
registerEffect(getStack(Blocks.GRASS)
, BrewRegistry.getDefault(ModBrews.GROWTH), false);
registerEffect(getStack(Blocks.MOSSY_COBBLESTONE)
, BrewRegistry.getDefault(ModBrews.OZYMANDIAS), false);
registerEffect(getStack(Blocks.RED_NETHER_BRICK)
, BrewRegistry.getDefault(ModBrews.HELLS_WROTH), false);
registerEffect(getStack(Blocks.SAND, 1, 1)
, BrewRegistry.getDefault(ModBrews.SETEHS_WASTES), false);
registerEffect(getStack(ModBlocks.nethersteel)
, BrewRegistry.getDefault(ModBrews.HELL_WORLD), false);
registerEffect(getStack(ModItems.seed_mint)
, BrewRegistry.getDefault(ModBrews.ICE_WORLD), false);
registerEffect(getStack(Items.CHORUS_FRUIT)
, BrewRegistry.getDefault(ModBrews.CURSED_LEAPING), false);
registerEffect(getStack(Items.BONE)
, BrewRegistry.getDefault(ModBrews.CORRUPTION), false);
registerEffect(getStack(ModItems.salt)
, BrewRegistry.getDefault(ModBrews.SALT_LAND), false);
registerEffect(getStack(ModItems.silver_scales)
, BrewRegistry.getDefault(ModBrews.BULLETPROOF), false);
//Time Extenders
registerModifier(getStack(Items.REDSTONE)
, new BrewSimpleModifier(600, 0), true);
registerModifier(getStack(Blocks.REDSTONE_BLOCK)
, new BrewSimpleModifier(1200, 0), true);
registerModifier(getStack(Items.QUARTZ)
, new BrewSimpleModifier(2400, 0), true);
//Amplifiers
registerModifier(getStack(Items.GLOWSTONE_DUST)
, new BrewSimpleModifier(0, 1), true);
registerModifier(getStack(Blocks.GLOWSTONE)
, new BrewSimpleModifier(0, 2), true);
registerModifier(getStack(ModItems.gem, 1, 2)
, new BrewSimpleModifier(0, 3), true);
//Amplitude Decreasers
//Todo: Create gemstone powders, and add tourmaline powder as a tier 1 amplitude decreaser.
registerModifier(getStack(ModItems.gem, 1, 4)
, new BrewSimpleModifier(0, -2), true);
registerModifier(getStack(ModBlocks.tourmaline_block, 1, 0)
, new BrewSimpleModifier(0, -3), true);
//Time Decreasers
registerModifier(getStack(Items.COAL)
, new BrewSimpleModifier(-600, 0), true);
registerModifier(getStack(Items.COAL, 1, 1)
, new BrewSimpleModifier(-1200, 0), true);
registerModifier(getStack(Blocks.COAL_BLOCK)
, new BrewSimpleModifier(-2400, 0), true);
}
private static void registerItemProcess(Fluid fluid, Item in, Item out, boolean perfectMatch) {
CauldronRegistry.registerItemProcessing(fluid, new ItemStack(in), new ItemStack(out), perfectMatch);
}
private static void registerItemProcess(Fluid fluid, ItemStack in, ItemStack out, boolean perfectMatch) {
CauldronRegistry.registerItemProcessing(fluid, in, out, perfectMatch);
}
/**
* Who needs to write the whole thing?
*
* @param item The block to make an ItemStack out of
* @param size Size of ItemStack
* @param meta Meta of ItemStack
* @return An ItemStack
*/
private static ItemStack getStack(Item item, int size, int meta) {
return new ItemStack(item, size, meta);
}
private static void registerItemRitual(String name, ItemStack spawned, int cost, Object... needed) {
IRitual ritual = RitualRegistry.register(new ResourceLocation(LibMod.MOD_ID, name), new ItemRitual(spawned, cost));
CauldronRegistry.registerItemRitual((ItemRitual) ritual, needed);
}
/**
* Who needs to write the whole thing?
*
* @param item The block to make an ItemStack out of
* @param size Size of ItemStack
* @return An ItemStack
*/
private static ItemStack getStack(Item item, int size) {
return new ItemStack(item, size, 0);
}
/**
* Who needs to write the whole thing?
*
* @param block The block to make an ItemStack out of
* @param size Size of ItemStack
* @return An ItemStack
*/
@SuppressWarnings("ConstantConditions")
private static ItemStack getStack(Block block, int size) {
return getStack(Item.getItemFromBlock(block), size, 0);
}
/**
* Who needs to write the whole thing?
*
* @param block The block to make an ItemStack out of
* @return An ItemStack
*/
@SuppressWarnings("ConstantConditions")
private static ItemStack getStack(Block block) {
return getStack(Item.getItemFromBlock(block), 1, 0);
}
/**
* Who needs to write the whole thing?
*
* @param item The item to make an ItemStack out of
* @return An ItemStack
*/
private static ItemStack getStack(Item item) {
return getStack(item, 1, 0);
}
/**
* Who needs to write the whole thing?
*
* @param block The block to make an ItemStack out of
* @param size Size of ItemStack
* @param meta Meta of ItemStack
* @return An ItemStack
*/
@SuppressWarnings("ConstantConditions")
private static ItemStack getStack(Block block, int size, int meta) {
return getStack(Item.getItemFromBlock(block), size, meta);
}
private static void registerBrewRecipe(BrewRegistry.Brew brew, BrewEffect effect, Object... needed) {
CauldronRegistry.registerBrewRecipe(BrewUtils.createBrew(brew, effect), needed);
}
private static <T> void registerEffect(ItemStack key, T brew, boolean perfectMatch) {
CauldronRegistry.registerItemEffect(key, brew, perfectMatch);
}
private static void registerModifier(ItemStack key, BrewModifier modifier, boolean perfectMatch) {
CauldronRegistry.registerItemModifier(key, modifier, perfectMatch);
}
}
|
import java.io.File;
import java.io.IOException;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Vector;
public abstract class BinaryDataFile extends BinaryData{
File file;
BinaryDataFile(String filename, int numInds, MarkerData md, String collection){
super(numInds,md,collection);
this.file = new File(filename);
}
public void checkFile(byte[] headers) throws IOException{
if (file != null){
if (file.length() != (numSNPs*bytesPerRecord) + headers.length){
if (file.length() == (numSNPs*bytesPerRecord) + 8){
//alternate Oxford format
//Change headers byte[] to be a new byte[] of the correct things as specified by numSNPs and numInds.
ByteBuffer buf = ByteBuffer.allocate(8);
buf.order(ByteOrder.LITTLE_ENDIAN);
// in the case of remote data we need to compare the total snps as this is the value in the header
buf.putInt(this.totNumSNPs);
// the inds value in the header is the number of columns two values per ind
buf.putInt(this.numInds*2);
buf.clear();
headers = new byte[8];
buf.get(headers, 0, 8);
bntHeaderOffset = 8;
} else{
throw new IOException(file +
" is not properly formatted.\n(Incorrect length.)");
}
}
} else{
//this is a useless message, but it implies badness 10000
throw new IOException("File is null?!?");
}
//are the headers acceptable for this file?
BufferedInputStream binaryIS = new BufferedInputStream(new FileInputStream(file),8192);
byte[] fromFile = new byte[headers.length];
binaryIS.read(fromFile,0,headers.length);
for (int i = 0; i < headers.length; i++){
if (fromFile[i] != headers[i]){
throw new IOException(file +
" is not properly formatted.\n(Magic number is incorrect.)");
}
}
}
public Vector getRecord(String markerName){
//do some checks on getting the data and handle errors centrally
int snpIndex;
try {
if((snpIndex = md.getIndex(markerName,md.getSampleCollectionIndex(collection))) >= 0) {
return getRecord(snpIndex);
}
}catch(IOException ioe) {
//TODO: handle me
//TODO: I don't know anything about that SNP?
}
return(null);
}
abstract Vector getRecord(int index) throws IOException;
}
|
package org.sbolstandard.core2;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.Writer;
import java.net.URI;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.xml.namespace.QName;
import org.apache.commons.text.StringEscapeUtils;
/**
* This class provides methods for converting GenBank files to and from SBOL 2.0 files.
* @author Chris Myers
* @author Ernst Oberortner
* @version 2.1
*/
class GenBank {
private static SequenceOntology so = null;
public static final String GBPREFIX = "genbank";
public static final String GBNAMESPACE = "http://www.ncbi.nlm.nih.gov/genbank
public static final String LOCUS = "locus";
public static final String MOLECULE = "molecule";
public static final String TOPOLOGY = "topology"; // Only used for backward compatiblity with 2.1.0
public static final String DIVISION = "division";
public static final String DATE = "date";
public static final String GINUMBER = "GInumber";
public static final String KEYWORDS = "keywords";
public static final String SOURCE = "source";
public static final String ORGANISM = "organism";
public static final String REFERENCE = "reference";
public static final String NESTEDREFERENCE = "Reference";
public static final String LABEL = "label";
public static final String AUTHORS = "authors";
public static final String TITLE = "title";
public static final String JOURNAL = "journal";
public static final String MEDLINE = "medline";
public static final String PUBMED = "pubmed";
public static final String COMMENT = "comment";
public static final String BASECOUNT = "baseCount";
public static final String GBCONVPREFIX = "gbConv";
public static final String GBCONVNAMESPACE = "http://sbols.org/genBankConversion
public static final String POSITION = "position";
public static final String STRADLESORIGIN = "stradlesOrigin";
public static final String STARTLESSTHAN = "startLessThan";
public static final String ENDGREATERTHAN = "endGreaterThan";
public static final String SINGLEBASERANGE = "singleBaseRange";
public static final String MULTIRANGETYPE = "multiRangeType";
static boolean isGenBankFile(String fileName) throws IOException {
File file = new File(fileName);
FileInputStream stream = new FileInputStream(file);
BufferedInputStream buffer = new BufferedInputStream(stream);
String strLine;
BufferedReader br = new BufferedReader(new InputStreamReader(buffer));
strLine = br.readLine();
br.close();
return isGenBankString(strLine);
}
static boolean isGenBankString(String inputString) {
if (inputString!=null && inputString.startsWith("LOCUS")) return true;
return false;
}
private static void writeGenBankLine(Writer w, String line, int margin, int indent) throws IOException {
if (line.length() < margin) {
w.write(line+"\n");
} else {
String spaces = "";
for (int i = 0 ; i < indent ; i++) spaces += " ";
int breakPos = line.substring(0,margin-1).lastIndexOf(" ")+1;
if (breakPos==0 || breakPos < 0.75*margin) breakPos = margin-1;
w.write(line.substring(0, breakPos)+"\n");
int i = breakPos;
while (i < line.length()) {
if ((i+(margin-indent)) < line.length()) {
breakPos = line.substring(i,i+(margin-indent)-1).lastIndexOf(" ")+1;
if (breakPos==0 || breakPos < 0.65*margin) breakPos = (margin-indent)-1;
w.write(spaces+line.substring(i,i+breakPos)+"\n");
} else {
w.write(spaces+line.substring(i)+"\n");
breakPos = (margin-indent)-1;
}
i+=breakPos;
}
}
}
private static void writeComponentDefinition(ComponentDefinition componentDefinition, Writer w) throws IOException, SBOLConversionException {
so = new SequenceOntology();
Sequence seq = null;
for (Sequence sequence : componentDefinition.getSequences()) {
if (sequence.getEncoding().equals(Sequence.IUPAC_DNA)||
sequence.getEncoding().equals(Sequence.IUPAC_RNA)) {
seq = sequence;
break;
}
}
if (seq == null) {
throw new SBOLConversionException("ComponentDefinition " + componentDefinition.getIdentity() +
" does not have an IUPAC sequence.");
}
int size = seq.getElements().length();
writeHeader(w,componentDefinition,size);
writeReferences(w,componentDefinition);
writeComment(w,componentDefinition);
w.write("FEATURES Location/Qualifiers\n");
recurseComponentDefinition(componentDefinition,w,0,true,0);
w.write("ORIGIN\n");
writeSequence(w,seq,size);
w.write("
}
/**
* Serializes a given ComponentDefinition and outputs the data from the serialization to the given output stream
* in GenBank format.
* @param componentDefinition a given ComponentDefinition
* @param out the given output file name in GenBank format
* @throws IOException input/output operation failed
* @throws SBOLConversionException violates conversion limitations
*/
private static void write(ComponentDefinition componentDefinition, Writer w) throws IOException, SBOLConversionException {
writeComponentDefinition(componentDefinition,w);
}
/**
* Serializes a given SBOLDocument and outputs the data from the serialization to the given output stream
* in GenBank format.
* @param sbolDocument a given SBOLDocument
* @param out the given output file name in GenBank format
* @throws IOException input/output operation failed
* @throws SBOLConversionException violates conversion limitations
*/
static void write(SBOLDocument sbolDocument, OutputStream out) throws IOException, SBOLConversionException {
Writer w = new OutputStreamWriter(out, "UTF-8");
for (ComponentDefinition componentDefinition : sbolDocument.getRootComponentDefinitions()) {
write(componentDefinition,w);
}
w.close();
}
private static String convertSOtoGenBank(String soTerm) {
if (soTerm.equals("SO:0001023")) {return String.format("%-15s", "allele");}
if (soTerm.equals("SO:0000140")) {return String.format("%-15s", "attenuator");}
if (soTerm.equals("SO:0001834")) {return String.format("%-15s", "C_region");}
if (soTerm.equals("SO:0000172")) {return String.format("%-15s", "CAAT_signal");}
if (soTerm.equals("SO:0000316")) {return String.format("%-15s", "CDS");}
//if (soTerm.equals("SO:")) {return String.format("%-15s", "conflict");}
if (soTerm.equals("SO:0000297")) {return String.format("%-15s", "D-loop");}
if (soTerm.equals("SO:0000458")) {return String.format("%-15s", "D_segment");}
if (soTerm.equals("SO:0000165")) {return String.format("%-15s", "enhancer");}
if (soTerm.equals("SO:0000147")) {return String.format("%-15s", "exon");}
if (soTerm.equals("SO:0000704")) {return String.format("%-15s", "gene");}
if (soTerm.equals("SO:0000173")) {return String.format("%-15s", "GC_signal");}
if (soTerm.equals("SO:0000723")) {return String.format("%-15s", "iDNA");}
if (soTerm.equals("SO:0000188")) {return String.format("%-15s", "intron");}
if (soTerm.equals("SO:0000470")) {return String.format("%-15s", "J_region");}
if (soTerm.equals("SO:0000286")) {return String.format("%-15s", "LTR");}
if (soTerm.equals("SO:0000419")) {return String.format("%-15s", "mat_peptide");}
if (soTerm.equals("SO:0000409")) {return String.format("%-15s", "misc_binding");}
if (soTerm.equals("SO:0000413")) {return String.format("%-15s", "misc_difference");}
if (soTerm.equals("SO:0000001")) {return String.format("%-15s", "misc_feature");}
if (soTerm.equals("SO:0001645")) {return String.format("%-15s", "misc_marker");}
if (soTerm.equals("SO:0000298")) {return String.format("%-15s", "misc_recomb");}
if (soTerm.equals("SO:0000233")) {return String.format("%-15s", "misc_RNA");}
if (soTerm.equals("SO:0001411")) {return String.format("%-15s", "misc_signal");}
if (soTerm.equals("SO:0005836")) {return String.format("%-15s", "regulatory");}
if (soTerm.equals("SO:0000002")) {return String.format("%-15s", "misc_structure");}
if (soTerm.equals("SO:0000305")) {return String.format("%-15s", "modified_base");}
if (soTerm.equals("SO:0000234")) {return String.format("%-15s", "mRNA");}
//if (soTerm.equals("SO:")) {return String.format("%-15s", "mutation");}
if (soTerm.equals("SO:0001835")) {return String.format("%-15s", "N_region");}
//if (soTerm.equals("SO:")) {return String.format("%-15s", "old_sequence");}
if (soTerm.equals("SO:0000551")) {return String.format("%-15s", "polyA_signal");}
if (soTerm.equals("SO:0000553")) {return String.format("%-15s", "polyA_site");}
if (soTerm.equals("SO:0000185")) {return String.format("%-15s", "precursor_RNA");}
if (soTerm.equals("SO:0000185")) {return String.format("%-15s", "prim_transcript");}
// NOTE: redundant with line above
if (soTerm.equals("SO:0000112")) {return String.format("%-15s", "primer");}
if (soTerm.equals("SO:0005850")) {return String.format("%-15s", "primer_bind");}
if (soTerm.equals("SO:0000167")) {return String.format("%-15s", "promoter");}
if (soTerm.equals("SO:0000410")) {return String.format("%-15s", "protein_bind");}
if (soTerm.equals("SO:0000139") || soTerm.equals("SO:0000552")) {return String.format("%-15s", "RBS");}
if (soTerm.equals("SO:0000296")) {return String.format("%-15s", "rep_origin");}
if (soTerm.equals("SO:0000657")) {return String.format("%-15s", "repeat_region");}
if (soTerm.equals("SO:0000726")) {return String.format("%-15s", "repeat_unit");}
if (soTerm.equals("SO:0000252")) {return String.format("%-15s", "rRNA");}
if (soTerm.equals("SO:0001836")) {return String.format("%-15s", "S_region");}
if (soTerm.equals("SO:0000005")) {return String.format("%-15s", "satellite");}
if (soTerm.equals("SO:0000013")) {return String.format("%-15s", "scRNA");}
if (soTerm.equals("SO:0000418")) {return String.format("%-15s", "sig_peptide");}
if (soTerm.equals("SO:0000274")) {return String.format("%-15s", "snRNA");}
if (soTerm.equals("SO:0000149")) {return String.format("%-15s", "source");}
if (soTerm.equals("SO:0000019")) {return String.format("%-15s", "stem_loop");}
if (soTerm.equals("SO:0000313")) {return String.format("%-15s", "stem_loop");}
if (soTerm.equals("SO:0000331")) {return String.format("%-15s", "STS");}
if (soTerm.equals("SO:0000174")) {return String.format("%-15s", "TATA_signal");}
if (soTerm.equals("SO:0000141")) {return String.format("%-15s", "terminator");}
if (soTerm.equals("SO:0000725")) {return String.format("%-15s", "transit_peptide");}
if (soTerm.equals("SO:0001054")) {return String.format("%-15s", "transposon");}
if (soTerm.equals("SO:0000253")) {return String.format("%-15s", "tRNA");}
// if (soTerm.equals("SO:")) {return String.format("%-15s", "unsure");}
if (soTerm.equals("SO:0001833")) {return String.format("%-15s", "V_region");}
if (soTerm.equals("SO:0001060")) {return String.format("%-15s", "variation");}
if (soTerm.equals("SO:0000175")) {return String.format("%-15s", "-10_signal");}
if (soTerm.equals("SO:0000176")) {return String.format("%-15s", "-35_signal");}
if (soTerm.equals("SO:0000557")) {return String.format("%-15s", "3'clip");}
if (soTerm.equals("SO:0000205")) {return String.format("%-15s", "3'UTR");}
if (soTerm.equals("SO:0000555")) {return String.format("%-15s", "5'clip");}
if (soTerm.equals("SO:0000204")) {return String.format("%-15s", "5'UTR");}
/*
if (soTerm.equals("CDS") || soTerm.equals("promoter") || soTerm.equals("terminator"))
return String.format("%-15s", soTerm);
else if (soTerm.equals("ribosome_entry_site"))
return "RBS ";
*/
return "misc_feature ";
}
private static URI convertGenBanktoSO(String genBankTerm) {
if (genBankTerm.equals("allele")) {
return so.getURIbyId("SO:0001023");}
if (genBankTerm.equals("attenuator")) {
return so.getURIbyId("SO:0000140");}
if (genBankTerm.equals("C_region")) {
return so.getURIbyId("SO:0001834");}
if (genBankTerm.equals("CAAT_signal")) {
return so.getURIbyId("SO:0000172");}
if (genBankTerm.equals("CDS")) {
return so.getURIbyId("SO:0000316");}
/* if (genBankTerm.equals("conflict")) {
return so.getURIbyId("SO_");} */
if (genBankTerm.equals("D-loop")) {
return so.getURIbyId("SO:0000297");}
if (genBankTerm.equals("D_segment")) {
return so.getURIbyId("SO:0000458");}
if (genBankTerm.equals("enhancer")) {
return so.getURIbyId("SO:0000165");}
if (genBankTerm.equals("exon")) {
return so.getURIbyId("SO:0000147");}
if (genBankTerm.equals("gene")) {
return so.getURIbyId("SO:0000704");}
if (genBankTerm.equals("GC_signal")) {
return so.getURIbyId("SO:0000173");}
if (genBankTerm.equals("iDNA")) {
return so.getURIbyId("SO:0000723");}
if (genBankTerm.equals("intron")) {
return so.getURIbyId("SO:0000188");}
if (genBankTerm.equals("J_region")) {
return so.getURIbyId("SO:0000470");}
if (genBankTerm.equals("LTR")) {
return so.getURIbyId("SO:0000286");}
if (genBankTerm.equals("mat_peptide")) {
return so.getURIbyId("SO:0000419");}
if (genBankTerm.equals("misc_binding")) {
return so.getURIbyId("SO:0000409");}
if (genBankTerm.equals("misc_difference")) {
return so.getURIbyId("SO:0000413");}
if (genBankTerm.equals("misc_feature")) {
return so.getURIbyId("SO:0000001");}
if (genBankTerm.equals("misc_marker")) {
return so.getURIbyId("SO:0001645");}
if (genBankTerm.equals("misc_recomb")) {
return so.getURIbyId("SO:0000298");}
if (genBankTerm.equals("misc_RNA")) {
return so.getURIbyId("SO:0000233");}
if (genBankTerm.equals("misc_signal")) {
return so.getURIbyId("SO:0001411");}
if (genBankTerm.equals("misc_structure")) {
return so.getURIbyId("SO:0000002");}
if (genBankTerm.equals("modified_base")) {
return so.getURIbyId("SO:0000305");}
if (genBankTerm.equals("mRNA")) {
return so.getURIbyId("SO:0000234");}
/* if (genBankTerm.equals("mutation")) {
return so.getURIbyId("SO_");} */
if (genBankTerm.equals("N_region")) {
return so.getURIbyId("SO:0001835");}
/* if (genBankTerm.equals("old_sequence")) {
return so.getURIbyId("SO_");} */
if (genBankTerm.equals("polyA_signal")) {
return so.getURIbyId("SO:0000551");}
if (genBankTerm.equals("polyA_site")) {
return so.getURIbyId("SO:0000553");}
if (genBankTerm.equals("precursor_RNA")) {
return so.getURIbyId("SO:0000185");}
if (genBankTerm.equals("prim_transcript")) {
return so.getURIbyId("SO:0000185");}
if (genBankTerm.equals("primer")) {
return so.getURIbyId("SO:0000112");}
if (genBankTerm.equals("primer_bind")) {
return so.getURIbyId("SO:0005850");}
if (genBankTerm.equals("promoter")) {
return so.getURIbyId("SO:0000167");}
if (genBankTerm.equals("protein_bind")) {
return so.getURIbyId("SO:0000410");}
if (genBankTerm.equals("RBS")) {
return so.getURIbyId("SO:0000139");}
if (genBankTerm.equals("rep_origin")) {
return so.getURIbyId("SO:0000296");}
if (genBankTerm.equals("repeat_region")) {
return so.getURIbyId("SO:0000657");}
if (genBankTerm.equals("repeat_unit")) {
return so.getURIbyId("SO:0000726");}
if (genBankTerm.equals("rRNA")) {
return so.getURIbyId("SO:0000252");}
if (genBankTerm.equals("S_region")) {
return so.getURIbyId("SO:0001836");}
if (genBankTerm.equals("satellite")) {
return so.getURIbyId("SO:0000005");}
if (genBankTerm.equals("scRNA")) {
return so.getURIbyId("SO:0000013");}
if (genBankTerm.equals("sig_peptide")) {
return so.getURIbyId("SO:0000418");}
if (genBankTerm.equals("snRNA")) {
return so.getURIbyId("SO:0000274");}
if (genBankTerm.equals("source")) {
return so.getURIbyId("SO:0000149");}
if (genBankTerm.equals("stem_loop")) {
return so.getURIbyId("SO:0000313");}
if (genBankTerm.equals("STS")) {
return so.getURIbyId("SO:0000331");}
if (genBankTerm.equals("TATA_signal")) {
return so.getURIbyId("SO:0000174");}
if (genBankTerm.equals("terminator")) {
return so.getURIbyId("SO:0000141");}
if (genBankTerm.equals("transit_peptide")) {
return so.getURIbyId("SO:0000725");}
if (genBankTerm.equals("transposon")) {
return so.getURIbyId("SO:0001054");}
if (genBankTerm.equals("tRNA")) {
return so.getURIbyId("SO:0000253");}
/* if (genBankTerm.equals("unsure")) {
return so.getURIbyId("SO_");} */
if (genBankTerm.equals("V_region")) {
return so.getURIbyId("SO:0001833");}
if (genBankTerm.equals("variation")) {
return so.getURIbyId("SO:0001060");}
if (genBankTerm.equals("-10_signal")) {
return so.getURIbyId("SO:0000175");}
if (genBankTerm.equals("-35_signal")) {
return so.getURIbyId("SO:0000176");}
if (genBankTerm.equals("3'clip")) {
return so.getURIbyId("SO:0000557");}
if (genBankTerm.equals("3'UTR")) {
return so.getURIbyId("SO:0000205");}
if (genBankTerm.equals("5'clip")) {
return so.getURIbyId("SO:0000555");}
if (genBankTerm.equals("5'UTR")) {
return so.getURIbyId("SO:0000204");}
if (genBankTerm.equals("regulatory")) {
return so.getURIbyId("SO:0005836");}
if (genBankTerm.equals("snoRNA")) {
return so.getURIbyId("SO:0000275");
}
//return so.getURIbyId("SO:0000001");
return null;
/*
URI soTerm = so.getURIbyName(genBankTerm);
if (soTerm==null && genBankTerm.equals("misc_feature")) {
soTerm = SequenceOntology.ENGINEERED_REGION;
}
return soTerm;
*/
}
private static void writeHeader(Writer w,ComponentDefinition componentDefinition,int size) throws SBOLConversionException, IOException {
String locus = componentDefinition.getDisplayId().substring(0,
componentDefinition.getDisplayId().length()>15?15:componentDefinition.getDisplayId().length());
Annotation annotation = componentDefinition.getAnnotation(new QName(GBNAMESPACE,LOCUS,GBPREFIX));
if (annotation!=null) {
locus = annotation.getStringValue();
}
String type = null;
for (URI typeURI : componentDefinition.getTypes()) {
if (typeURI.equals(ComponentDefinition.RNA)) {
type = "RNA";
break;
} else if (typeURI.equals(ComponentDefinition.DNA)) {
type = "DNA";
}
}
if (type == null) {
throw new SBOLConversionException("ComponentDefinition " + componentDefinition.getIdentity() +
" is not DNA or RNA type.");
}
annotation = componentDefinition.getAnnotation(new QName(GBNAMESPACE,MOLECULE,GBPREFIX));
if (annotation!=null) {
type = annotation.getStringValue();
}
String linCirc = "linear";
// Below only needed for backwards compatibility with 2.1.0 converter.
annotation = componentDefinition.getAnnotation(new QName(GBNAMESPACE,TOPOLOGY,GBPREFIX));
if (annotation!=null) {
linCirc = annotation.getStringValue();
}
if (componentDefinition.containsType(SequenceOntology.CIRCULAR)) {
linCirc = "circular";
}
if (componentDefinition.containsType(SequenceOntology.LINEAR)) {
linCirc = "linear";
}
String division = "UNK";
annotation = componentDefinition.getAnnotation(new QName(GBNAMESPACE,DIVISION,GBPREFIX));
if (annotation!=null) {
division = annotation.getStringValue();
}
DateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
Date dateobj = new Date();
String date = df.format(dateobj);
annotation = componentDefinition.getAnnotation(new QName(GBNAMESPACE,DATE,GBPREFIX));
if (annotation!=null) {
date = annotation.getStringValue();
}
String locusLine = "LOCUS " + String.format("%-16s", locus) + " " +
String.format("%11s", ""+size) + " bp " + " " + String.format("%-6s", type) + " " +
String.format("%-8s", linCirc) + " " + division + " " + date + "\n";
w.write(locusLine);
if (componentDefinition.isSetDescription()) {
writeGenBankLine(w,"DEFINITION " + componentDefinition.getDescription(),80,12);
}
w.write("ACCESSION " + componentDefinition.getDisplayId() + "\n");
if (componentDefinition.isSetVersion()) {
String giNumber = "";
annotation = componentDefinition.getAnnotation(new QName(GBNAMESPACE,GINUMBER,GBPREFIX));
if (annotation!=null) {
giNumber = annotation.getStringValue();
}
w.write("VERSION " + componentDefinition.getDisplayId() + "." +
componentDefinition.getVersion() + " " + giNumber + "\n");
}
annotation = componentDefinition.getAnnotation(new QName(GBNAMESPACE,KEYWORDS,GBPREFIX));
if (annotation!=null) {
w.write("KEYWORDS " + annotation.getStringValue() + "\n");
}
annotation = componentDefinition.getAnnotation(new QName(GBNAMESPACE,SOURCE,GBPREFIX));
if (annotation!=null) {
w.write("SOURCE " + annotation.getStringValue() + "\n");
}
annotation = componentDefinition.getAnnotation(new QName(GBNAMESPACE,ORGANISM,GBPREFIX));
if (annotation!=null) {
writeGenBankLine(w," ORGANISM " + annotation.getStringValue(),80,12);
}
}
private static void writeReferences(Writer w,ComponentDefinition componentDefinition) throws IOException {
for (Annotation a : componentDefinition.getAnnotations()) {
if (a.getQName().equals(new QName(GBNAMESPACE,REFERENCE,GBPREFIX))) {
String label = null;
String authors = null;
String title = null;
String journal = null;
String medline = null;
String pubmed = null;
for (Annotation ref : a.getAnnotations()) {
if (ref.getQName().equals(new QName(GBNAMESPACE,LABEL,GBPREFIX))) {
label = ref.getStringValue();
} else if (ref.getQName().equals(new QName(GBNAMESPACE,AUTHORS,GBPREFIX))) {
authors = ref.getStringValue();
} else if (ref.getQName().equals(new QName(GBNAMESPACE,TITLE,GBPREFIX))) {
title = ref.getStringValue();
} else if (ref.getQName().equals(new QName(GBNAMESPACE,JOURNAL,GBPREFIX))) {
journal = ref.getStringValue();
} else if (ref.getQName().equals(new QName(GBNAMESPACE,MEDLINE,GBPREFIX))) {
medline = ref.getStringValue();
} else if (ref.getQName().equals(new QName(GBNAMESPACE,PUBMED,GBPREFIX))) {
pubmed = ref.getStringValue();
}
}
if (label != null) {
writeGenBankLine(w,"REFERENCE " + label,80,12);
if (authors != null) {
writeGenBankLine(w," AUTHORS " + authors,80,12);
}
if (title != null) {
writeGenBankLine(w," TITLE " + title,80,12);
}
if (journal != null) {
writeGenBankLine(w," JOURNAL " + journal,80,12);
}
if (medline != null) {
writeGenBankLine(w," MEDLINE " + medline,80,12);
}
if (pubmed != null) {
writeGenBankLine(w," PUBMED " + pubmed,80,12);
}
}
}
}
}
private static void writeComment(Writer w,ComponentDefinition componentDefinition) throws IOException {
Annotation annotation = componentDefinition.getAnnotation(new QName(GBNAMESPACE,COMMENT,GBPREFIX));
if (annotation!=null) {
writeGenBankLine(w,"COMMENT " + annotation.getStringValue(),80,12);
}
}
// private static String startStr(Range range,int offset) {
// if (range.getAnnotation(new QName(GBNAMESPACE,STARTLESSTHAN,GBPREFIX))!=null) {
// return "<"+(offset+range.getStart());
// return ""+(offset+range.getStart());
// private static String rangeType(Range range) {
// if (range.getAnnotation(new QName(GBNAMESPACE,SINGLEBASERANGE,GBPREFIX))!=null) {
// return ".";
// return "..";
// private static String endStr(Range range,int offset) {
// if (range.getAnnotation(new QName(GBNAMESPACE,ENDGREATERTHAN,GBPREFIX))!=null) {
// return ">"+(offset+range.getEnd());
// return ""+(offset+range.getEnd());
private static String locationStr(Location location,int offset,boolean complement,Location location2) throws SBOLConversionException {
int start;
int end;
String locationStr = "";
boolean isCut = false;
if (location instanceof Range) {
Range range = (Range)location;
start = offset+range.getStart();
end = offset+range.getEnd();
} else if (location instanceof Cut) {
Cut cut = (Cut)location;
start = offset+cut.getAt();
end = offset+cut.getAt()+1;
isCut = true;
} else {
throw new SBOLConversionException("Location "+location.getIdentity()+" is not range or cut.");
}
if (location2!=null) {
if (location2 instanceof Range) {
Range range = (Range)location2;
end = offset+range.getEnd();
} else if (location2 instanceof Cut) {
Cut cut = (Cut)location2;
end = offset+cut.getAt()+1;
}
}
if (complement) {
locationStr += "complement(";
}
if (location.getAnnotation(new QName(GBCONVNAMESPACE,STARTLESSTHAN,GBCONVPREFIX))!=null) {
locationStr += "<";
}
locationStr += start;
if (isCut) {
locationStr += "^";
} else if (location.getAnnotation(new QName(GBCONVNAMESPACE,SINGLEBASERANGE,GBCONVPREFIX))!=null) {
locationStr += ".";
} else {
locationStr += "..";
}
if (location.getAnnotation(new QName(GBCONVNAMESPACE,ENDGREATERTHAN,GBCONVPREFIX))!=null) {
locationStr += ">";
}
locationStr += end;
if (complement) {
locationStr += ")";
}
return locationStr;
}
private static boolean stradlesOrigin(SequenceAnnotation sa) {
Annotation annotation = sa.getAnnotation(new QName(GBCONVNAMESPACE,STRADLESORIGIN,GBCONVPREFIX));
if (annotation!=null) {
return true;
}
return false;
}
private static void writeFeature(Writer w,SequenceAnnotation sa,String role,int offset,boolean inline)
throws IOException, SBOLConversionException {
if (sa.getPreciseLocations().size()==0) {
throw new SBOLConversionException("SequenceAnnotation "+sa.getIdentity()+" has no range/cut locations.");
} else if (sa.getPreciseLocations().size()==1) {
Location loc = sa.getPreciseLocations().iterator().next();
boolean locReverse = false;
if (loc.isSetOrientation()) {
locReverse = loc.getOrientation().equals(OrientationType.REVERSECOMPLEMENT);
}
w.write(" " + role + " " + locationStr(loc,offset,
((inline && locReverse)||
(!inline && !locReverse)),null)+"\n");
} else if (stradlesOrigin(sa)) {
Location loc = sa.getLocation("range0");
Location loc2 = sa.getLocation("range1");
boolean locReverse = false;
if (loc.isSetOrientation()) {
locReverse = loc.getOrientation().equals(OrientationType.REVERSECOMPLEMENT);
}
w.write(" " + role + " " + locationStr(loc,offset,
((inline && locReverse)||
(!inline && !locReverse)),loc2)+"\n");
} else {
String multiType = "join";
Annotation annotation = sa.getAnnotation(new QName(GBNAMESPACE,MULTIRANGETYPE,GBCONVPREFIX));
if (annotation!=null) {
multiType = annotation.getStringValue();
}
String rangeStr = " " + role + " " + multiType + "(";
boolean first = true;
for (Location loc : sa.getSortedLocations()) {
if (!first) rangeStr += ",";
else first = false;
boolean locReverse = false;
if (loc.isSetOrientation()) {
locReverse = loc.getOrientation().equals(OrientationType.REVERSECOMPLEMENT);
}
rangeStr += locationStr(loc,offset,
((inline && locReverse)||(!inline && !locReverse)),null);
}
rangeStr += ")";
writeGenBankLine(w,rangeStr,80,21);
}
for (Annotation a : sa.getAnnotations()) {
if (a.getQName().getLocalPart().equals("multiRangeType")) continue;
if (a.isStringValue()) {
try {
int aInt = Integer.parseInt(a.getStringValue());
writeGenBankLine(w," /"+
StringEscapeUtils.unescapeXml(a.getQName().getLocalPart())+"="+
aInt,80,21);
} catch (NumberFormatException e) {
writeGenBankLine(w," /"+
StringEscapeUtils.unescapeXml(a.getQName().getLocalPart())+"="+
"\"" + a.getStringValue() + "\"",80,21);
}
} else if (a.isIntegerValue()) {
writeGenBankLine(w," /"+
StringEscapeUtils.unescapeXml(a.getQName().getLocalPart())+"="+
a.getIntegerValue(),80,21);
}
}
}
private static void writeSequence(Writer w,Sequence sequence,int size) throws IOException {
for (int i = 0; i < size; i+=60) {
String padded = String.format("%9s", "" + (i+1));
w.write(padded);
for (int j = i; j < size && j < i + 60; j+=10) {
if (j+10 < size) {
w.write(" " + sequence.getElements().substring(j,j+10));
} else {
w.write(" " + sequence.getElements().substring(j));
}
}
w.write("\n");
}
}
private static int getFeatureStart(SequenceAnnotation sa) {
int featureStart = Integer.MAX_VALUE;
for (Location location : sa.getPreciseLocations()) {
if (location instanceof Range) {
Range range = (Range)location;
if (range.getStart() < featureStart) {
featureStart = range.getStart();
}
} else if (location instanceof Cut) {
Cut cut = (Cut)location;
if (cut.getAt() < featureStart) {
featureStart = cut.getAt();
}
}
}
if (featureStart==Integer.MAX_VALUE) return 1;
return featureStart;
}
private static int getFeatureEnd(SequenceAnnotation sa) {
int featureEnd = 0;
for (Location location : sa.getPreciseLocations()) {
if (location instanceof Range) {
Range range = (Range)location;
if (range.getEnd() > featureEnd) {
featureEnd = range.getEnd();
}
} else if (location instanceof Cut) {
Cut cut = (Cut)location;
if (cut.getAt() < featureEnd) {
featureEnd = cut.getAt();
}
}
}
//if (featureEnd==Integer.MAX_VALUE) return 1;
return featureEnd;
}
// TODO: assumes any complement then entirely complemented, need to fix
private static boolean isInlineFeature(SequenceAnnotation sa) {
boolean inlineFeature = true;
for (Location location : sa.getPreciseLocations()) {
if (location.isSetOrientation() && location.getOrientation().equals(OrientationType.REVERSECOMPLEMENT)) {
inlineFeature = false;
}
}
return inlineFeature;
}
private static void recurseComponentDefinition(ComponentDefinition componentDefinition, Writer w, int offset,
boolean inline, int featureEnd) throws IOException, SBOLConversionException {
for (SequenceAnnotation sa : componentDefinition.getSortedSequenceAnnotationsByDisplayId()) {
String role = "misc_feature ";
Component comp = sa.getComponent();
if (comp != null) {
ComponentDefinition compDef = comp.getDefinition();
if (compDef != null) {
for (URI roleURI : compDef.getRoles()) {
String soRole = so.getId(roleURI);
if (soRole != null) {
role = convertSOtoGenBank(so.getId(roleURI));
break;
}
}
int newFeatureEnd = featureEnd;
if (!isInlineFeature(sa)) {
newFeatureEnd = getFeatureEnd(sa);
}
recurseComponentDefinition(compDef, w, offset + getFeatureStart(sa)-1,
!(inline^isInlineFeature(sa)),newFeatureEnd);
}
} else {
for (URI roleURI : sa.getRoles()) {
String soRole = so.getId(roleURI);
if (soRole != null) {
role = convertSOtoGenBank(so.getId(roleURI));
break;
}
}
}
if (!inline) {
writeFeature(w,sa,role,(featureEnd - (getFeatureEnd(sa)+getFeatureStart(sa)-1) - offset),inline);
} else {
writeFeature(w,sa,role,offset,inline);
}
}
}
// "look-ahead" line
private static String nextLine = null;
private static boolean featureMode = false;
private static boolean originMode = false;
//private static int lineCounter = 0;
private static String readGenBankLine(BufferedReader br) throws IOException {
String newLine = "";
if (nextLine == null) {
newLine = br.readLine();
//lineCounter ++;
if (newLine == null) return null;
newLine = newLine.trim();
} else {
newLine = nextLine;
}
while (true) {
nextLine = br.readLine();
if (nextLine==null) return newLine;
nextLine = nextLine.trim();
if (featureMode) {
if (nextLine.startsWith("/")) {
return newLine;
}
String[] strSplit = nextLine.split("\\s+");
URI role = convertGenBanktoSO(strSplit[0]);
if (role!=null) return newLine;
}
if (originMode) return newLine;
if (nextLine.startsWith("DEFINITION")) return newLine;
if (nextLine.startsWith("ACCESSION")) return newLine;
if (nextLine.startsWith("VERSION")) return newLine;
if (nextLine.startsWith("KEYWORDS")) return newLine;
if (nextLine.startsWith("SOURCE")) return newLine;
if (nextLine.startsWith("ORGANISM")) return newLine;
if (nextLine.startsWith("REFERENCE")) return newLine;
if (nextLine.startsWith("COMMENT")) return newLine;
if (nextLine.startsWith("AUTHORS")) return newLine;
if (nextLine.startsWith("TITLE")) return newLine;
if (nextLine.startsWith("JOURNAL")) return newLine;
if (nextLine.startsWith("MEDLINE")) return newLine;
if (nextLine.startsWith("PUBMED")) return newLine;
if (nextLine.startsWith("BASE COUNT")) return newLine;
if (nextLine.startsWith("FEATURES")) {
featureMode = true;
return newLine;
}
if (nextLine.startsWith("ORIGIN")) {
originMode = true;
return newLine;
}
if (featureMode) {
if (newLine.contains(" ") || nextLine.contains(" ")) {
newLine += " " + nextLine;
} else {
newLine += nextLine;
}
} else {
newLine += " " + nextLine;
}
//lineCounter++;
}
}
/**
* @param doc
* @param topCD
* @param type
* @param elements
* @param version
* @throws SBOLValidationException if an SBOL validation rule violation occurred in any of the following methods:
* <ul>
* <li>{@link SBOLDocument#createSequence(String, String, String, URI)}, or</li>
* <li>{@link ComponentDefinition#addSequence(Sequence)}.</li>
* </ul>
*/
private static void createSubComponentDefinitions(SBOLDocument doc,ComponentDefinition topCD,URI type,String elements,String version) throws SBOLValidationException {
for (SequenceAnnotation sa : topCD.getSequenceAnnotations()) {
if (!sa.isSetComponent()) continue;
Range range = (Range)sa.getLocation("range");
if (range!=null) {
String subElements = elements.substring(range.getStart()-1,range.getEnd()).toLowerCase();
if (range.getOrientation().equals(OrientationType.REVERSECOMPLEMENT)) {
subElements = Sequence.reverseComplement(subElements,type);
}
ComponentDefinition subCompDef = sa.getComponent().getDefinition();
String compDefId = subCompDef.getDisplayId();
Sequence subSequence = doc.createSequence(compDefId+"_seq", version, subElements, Sequence.IUPAC_DNA);
subCompDef.addSequence(subSequence);
}
}
}
private static String fixTag(String tag) {
tag = tag.replaceAll("[^a-zA-Z0-9_\\-]", "_");
tag = tag.replace(" ", "_");
if (Character.isDigit(tag.charAt(0))|| tag.charAt(0)=='-') {
tag = "_" + tag;
}
return tag;
}
/**
* @param doc
* @param stringBuffer
* @param URIPrefix
* @throws IOException
* @throws SBOLConversionException
* @throws SBOLValidationException if an SBOL validation rule violation occurred in any of the following methods:
* <ul>
* <li>{@link SBOLDocument#createComponentDefinition(String, String, URI)},</li>
* <li>{@link Identified#setAnnotations(List)},</li>
* <li>{@link SequenceAnnotation#addAnnotation(Annotation)},</li>
* <li>{@link ComponentDefinition#createSequenceAnnotation(String, String, int, int, OrientationType)},</li>
* <li>{@link SequenceAnnotation#setComponent(String)},</li>
* <li>{@link SequenceAnnotation#addRange(String, int, int, OrientationType)},</li>
* <li>{@link Range#addAnnotation(Annotation)},</li>
* <li>{@link ComponentDefinition#createSequenceAnnotation(String, String, int, OrientationType)},</li>
* <li>{@link SBOLDocument#createSequence(String, String, String, URI)}, </li>
* <li>{@link ComponentDefinition#addSequence(Sequence)}, or </li>
* <li>{@link #createSubComponentDefinitions(SBOLDocument, ComponentDefinition, URI, String, String)}.</li>
* </ul>
*/
static void read(SBOLDocument doc,String stringBuffer,String URIPrefix,String defaultVersion) throws IOException, SBOLConversionException, SBOLValidationException {
so = new SequenceOntology();
// reset the global static variables needed for parsing
//lineCounter = 0;
doc.addNamespace(URI.create(GBNAMESPACE), GBPREFIX);
doc.addNamespace(URI.create(GBCONVNAMESPACE), GBCONVPREFIX);
BufferedReader br = new BufferedReader(new StringReader(stringBuffer));
String strLine;
int featureCnt = 0;
int refCnt = 0;
nextLine = null;
String labelType = "";
URI lastRole = null;
while (true) {
boolean cont = false;
String id = "";
String accession = "";
String version = defaultVersion;
featureMode = false;
originMode = false;
StringBuilder sbSequence = new StringBuilder();
String elements = null;
String description = "";
URI type = ComponentDefinition.DNA;
ComponentDefinition topCD = null;
List<Annotation> annotations = new ArrayList<Annotation>();
List<Annotation> nestedAnnotations = null;
Annotation annotation = null;
boolean circular = false;
int baseCount = 0;
while ((strLine = readGenBankLine(br)) != null) {
strLine = strLine.trim();
// LOCUS line
// Example:
// LOCUS AF123456 1510 bp mRNA linear VRT 12-APR-2012
if (strLine.startsWith("LOCUS")) {
//String[] strSplit = strLine.split("\\s+");
// ID of the sequence
id = strLine.substring(12, 28).trim();
annotation = new Annotation(new QName(GBNAMESPACE, LOCUS, GBPREFIX), id);
id = URIcompliance.fixDisplayId(id);
annotations.add(annotation);
// Base count of the sequence
int startBaseCount = strLine.substring(29,40).lastIndexOf(" ");
baseCount = Integer.parseInt(strLine.substring(29+startBaseCount,40).trim());
// type of sequence
String seqType = strLine.substring(44,53).trim();
if (seqType.toUpperCase().contains("RNA")) {
type = ComponentDefinition.RNA;
}
annotation = new Annotation(new QName(GBNAMESPACE, MOLECULE, GBPREFIX), seqType);
annotations.add(annotation);
String topology = strLine.substring(55,63).trim();
// linear vs. circular construct
if (topology.startsWith("linear") || topology.startsWith("circular")) {
if (topology.startsWith("circular")) circular = true;
//annotation = new Annotation(new QName(GBNAMESPACE, TOPOLOGY, GBPREFIX), strSplit[i]);
}
String division = strLine.substring(64,67).trim();
annotation = new Annotation(new QName(GBNAMESPACE, DIVISION, GBPREFIX), division);
annotations.add(annotation);
// date
String date = strLine.substring(68,79).trim();
annotation = new Annotation(new QName(GBNAMESPACE, DATE, GBPREFIX), date);
annotations.add(annotation);
} else if (strLine.startsWith("DEFINITION")) {
description = strLine.replaceFirst("DEFINITION ", "");
} else if (strLine.startsWith("ACCESSION")) {
String[] strSplit = strLine.split("\\s+");
if (strSplit.length > 1) {
accession = strSplit[1];
if (accession.length()>1) {
id = accession;
id = URIcompliance.fixDisplayId(id);
}
}
} else if (strLine.startsWith("VERSION")) {
String[] strSplit = strLine.split("\\s+");
//id = URIcompliance.fixDisplayId(id);
if (strSplit.length > 1) {
if (!accession.equals(strSplit[1])) {
if (strSplit[1].split("\\.").length > 1) {
version = strSplit[1].split("\\.")[strSplit[1].split("\\.").length-1];
}
String vId = strSplit[1].split("\\.")[0];
if (!accession.equals(vId)) {
throw new SBOLConversionException("Warning: id in version does not match id in accession");
}
}
}
//id = id.replaceAll("\\.", "_");
if (strSplit.length > 2) {
annotation = new Annotation(new QName(GBNAMESPACE,GINUMBER,GBPREFIX),strSplit[2]);
annotations.add(annotation);
}
} else if (strLine.startsWith("KEYWORDS")) {
String annotationStr = strLine.replace("KEYWORDS", "").trim();
annotation = new Annotation(new QName(GBNAMESPACE,KEYWORDS,GBPREFIX), annotationStr);
annotations.add(annotation);
} else if (strLine.startsWith("SOURCE")) {
String annotationStr = strLine.replace("SOURCE", "").trim();
annotation = new Annotation(new QName(GBNAMESPACE,SOURCE,GBPREFIX), annotationStr);
annotations.add(annotation);
} else if (strLine.startsWith("ORGANISM")) {
String annotationStr = strLine.replace("ORGANISM", "").trim();
annotation = new Annotation(new QName(GBNAMESPACE,ORGANISM,GBPREFIX), annotationStr);
annotations.add(annotation);
} else if (strLine.startsWith("REFERENCE")) {
String annotationStr = strLine.replace("REFERENCE", "").trim();
nestedAnnotations = new ArrayList<Annotation>();
Annotation labelAnnotation = new Annotation(new QName(GBNAMESPACE,LABEL,GBPREFIX), annotationStr);
nestedAnnotations.add(labelAnnotation);
URI nestedURI = URI.create(URIPrefix+id+"/reference"+refCnt);
refCnt++;
annotation = new Annotation(new QName(GBNAMESPACE,REFERENCE,GBPREFIX),
new QName(GBNAMESPACE,NESTEDREFERENCE,GBPREFIX),nestedURI,nestedAnnotations);
annotations.add(annotation);
} else if (strLine.startsWith("AUTHORS")) {
String annotationStr = strLine.replace("AUTHORS", "").trim();
Annotation nestedAnnotation = new Annotation(new QName(GBNAMESPACE,AUTHORS,GBPREFIX), annotationStr);
nestedAnnotations.add(nestedAnnotation);
annotation.setAnnotations(nestedAnnotations);
} else if (strLine.startsWith("TITLE")) {
String annotationStr = strLine.replace("TITLE", "").trim();
Annotation nestedAnnotation = new Annotation(new QName(GBNAMESPACE,TITLE,GBPREFIX), annotationStr);
nestedAnnotations.add(nestedAnnotation);
annotation.setAnnotations(nestedAnnotations);
} else if (strLine.startsWith("JOURNAL")) {
String annotationStr = strLine.replace("JOURNAL", "").trim();
Annotation nestedAnnotation = new Annotation(new QName(GBNAMESPACE,JOURNAL,GBPREFIX), annotationStr);
nestedAnnotations.add(nestedAnnotation);
annotation.setAnnotations(nestedAnnotations);
} else if (strLine.startsWith("MEDLINE")) {
String annotationStr = strLine.replace("MEDLINE", "").trim();
Annotation nestedAnnotation = new Annotation(new QName(GBNAMESPACE,MEDLINE,GBPREFIX), annotationStr);
nestedAnnotations.add(nestedAnnotation);
annotation.setAnnotations(nestedAnnotations);
} else if (strLine.startsWith("PUBMED")) {
String annotationStr = strLine.replace("PUBMED", "").trim();
Annotation nestedAnnotation = new Annotation(new QName(GBNAMESPACE,PUBMED,GBPREFIX), annotationStr);
nestedAnnotations.add(nestedAnnotation);
annotation.setAnnotations(nestedAnnotations);
Annotation pubMedAnnotation = new Annotation(new QName("http://purl.obolibrary.org/obo/", "OBI_0001617", "obo"), annotationStr);
annotations.add(pubMedAnnotation);
} else if (strLine.startsWith("COMMENT")) {
String annotationStr = strLine.replace("COMMENT", "").trim();
annotation = new Annotation(new QName(GBNAMESPACE,COMMENT,GBPREFIX), annotationStr);
annotations.add(annotation);
} else if (strLine.startsWith("BASE COUNT")) {
String annotationStr = strLine.replace("BASE COUNT", "").trim();
annotation = new Annotation(new QName(GBNAMESPACE,BASECOUNT,GBPREFIX), annotationStr);
annotations.add(annotation);
// sequence features
} else if (strLine.startsWith("FEATURE")) {
topCD = doc.createComponentDefinition(id, version, type);
if (circular) {
topCD.addType(SequenceOntology.CIRCULAR);
} else {
topCD.addType(SequenceOntology.LINEAR);
}
topCD.addRole(SequenceOntology.ENGINEERED_REGION);
if (!"".equals(description)) {
topCD.setDescription(description);
}
topCD.setAnnotations(annotations);
// tell the parser that we're in the "FEATURE" section
featureMode = true;
} else if (strLine.startsWith("ORIGIN")) {
// switch from feature to origin mode
originMode = true;
featureMode = false;
} else {
if (featureMode) {
// parse the labels of a feature
if (strLine.startsWith("/")) {
// per default, we assume that every label
// has a key only
String tag = strLine.replace("/","").trim();
String value = "";
// now, we check if the key has a value too
// i.e. /<key>=<value>
if((-1) != strLine.indexOf('=')) {
String[] splitStr = strLine.split("=");
tag = splitStr[0].replace("/","");
value = splitStr[1];
}
// here, we just read the next lines until we find the closing double-quota
StringBuilder sbValue = new StringBuilder();
sbValue.append(value);
// multi-line string value
if(value.startsWith("\"") && !value.endsWith("\"")) {
while(true) {
strLine = readGenBankLine(br).trim();
sbValue.append(strLine);
if(strLine.endsWith("\"")) {
break;
}
}
}
// a Genbank feature label is mapped to an SBOL SequenceAnnotation
SequenceAnnotation sa = topCD.getSequenceAnnotation("annotation" + (featureCnt - 1));
if(sa != null) {
if (tag.equals("Apeinfo_label")) {
sa.setName(value.replace("\"", ""));
labelType = "Apeinfo_label";
} else if (tag.equals("label")) {
if (!labelType.equals("Apeinfo_label")) {
sa.setName(value.replace("\"", ""));
labelType = "label";
}
} else if (tag.equals("product")) {
if (!labelType.equals("Apeinfo_label")&&
!labelType.equals("label")) {
sa.setName(value.replace("\"", ""));
labelType = "product";
}
} else if (tag.equals("gene")) {
if (!labelType.equals("Apeinfo_label")&&
!labelType.equals("label")&&
!labelType.equals("product")) {
sa.setName(value.replace("\"", ""));
labelType = "gene";
}
} else if (tag.equals("note")) {
if (!labelType.equals("Apeinfo_label")&&
!labelType.equals("label")&&
!labelType.equals("product")&&
!labelType.equals("gene")) {
sa.setName(value.replace("\"", ""));
labelType = "note";
}
} else if (tag.equals("organism")) {
if (!labelType.equals("Apeinfo_label")&&
!labelType.equals("label")&&
!labelType.equals("product")&&
!labelType.equals("gene")&&
!labelType.equals("note")) {
sa.setName(value.replace("\"", ""));
labelType = "organism";
}
}
String oldTag = tag;
tag = fixTag(tag);
if (!tag.equals(oldTag)) {
System.out.println("tag="+tag+" oldTag="+oldTag);
}
if (value.startsWith("\"")) {
value = value.replaceAll("\"", "");
annotation = new Annotation(new QName(GBCONVNAMESPACE,tag,GBCONVPREFIX),value);
} else {
annotation = new Annotation(new QName(GBCONVNAMESPACE,tag,GBCONVPREFIX),value);
// TODO: does not work because integer type of annotation is lost on serialization
//annotation = new Annotation(new QName(GBNAMESPACE,tag,GBPREFIX),Integer.parseInt(value));
}
sa.addAnnotation(annotation);
}
// start of a new feature
} else {
strLine = strLine.replace(", ",",");
String[] strSplit = strLine.split("\\s+");
String featureType = strSplit[0];
// a Genbank feature is mapped to a SBOL role
// documented by an SO term
URI role = convertGenBanktoSO(featureType);
// ComponentDefinition feature =
// doc.createComponentDefinition("feature"+featureCnt, version, type);
// feature.addRole(role);
String range = strSplit[1];
boolean outerComplement = false;
OrientationType orientation = OrientationType.INLINE;
if (range.startsWith("complement")) {
outerComplement = true;
orientation = OrientationType.REVERSECOMPLEMENT;
range = range.replace("complement(", "").replace(")","");
}
if (range.startsWith("join")||range.startsWith("order")) {
String multiType = "join";
if (range.startsWith("order")) {
multiType = "order";
}
range = range.replace("join(", "").replace(")","");
range = range.replace("order(", "").replace(")","");
String[] ranges = range.split(",");
int rangeCnt = 0;
SequenceAnnotation sa = null;
for (String r : ranges) {
orientation = OrientationType.INLINE;
if (r.startsWith("complement")||outerComplement) {
orientation = OrientationType.REVERSECOMPLEMENT;
r = r.replace("complement(", "").replace(")","");
}
boolean startLessThan=false;
boolean endGreaterThan=false;
if (r.contains("<")) {
startLessThan=true;
r = r.replace("<","");
}
if (r.contains(">")) {
endGreaterThan=true;
r = r.replace(">", "");
}
boolean singleBaseRange = false;
String[] rangeSplit = null;
if (range.contains(".") && !range.contains("..")) {
rangeSplit = r.split("\\.");
singleBaseRange = true;
} else {
rangeSplit = r.split("\\.\\.");
}
int start = Integer.parseInt(rangeSplit[0]);
int end = Integer.parseInt(rangeSplit[1]);
Range newRange = null;
if (rangeCnt==0) {
sa = topCD.createSequenceAnnotation("annotation"+featureCnt,"range"+rangeCnt,
start,end,orientation);
//sa.setComponent("feature"+featureCnt);
sa.setName(featureType);
sa.addRole(role);
annotation = new Annotation(new QName(GBCONVNAMESPACE,MULTIRANGETYPE,GBCONVPREFIX),multiType);
sa.addAnnotation(annotation);
newRange = (Range)sa.getLocation("range"+rangeCnt);
} else if (sa != null) {
newRange = sa.addRange("range"+rangeCnt, start, end, orientation);
}
if (outerComplement) {
annotation = new Annotation(new QName(GBCONVNAMESPACE,POSITION,GBCONVPREFIX),"position"+((ranges.length-1)-rangeCnt));
} else {
annotation = new Annotation(new QName(GBCONVNAMESPACE,POSITION,GBCONVPREFIX),"position"+rangeCnt);
}
newRange.addAnnotation(annotation);
if (startLessThan) {
annotation = new Annotation(new QName(GBCONVNAMESPACE,STARTLESSTHAN,GBCONVPREFIX),"true");
newRange.addAnnotation(annotation);
}
if (endGreaterThan) {
annotation = new Annotation(new QName(GBCONVNAMESPACE,ENDGREATERTHAN,GBCONVPREFIX),"true");
newRange.addAnnotation(annotation);
}
if (singleBaseRange) {
annotation = new Annotation(new QName(GBCONVNAMESPACE,SINGLEBASERANGE,GBCONVPREFIX),"true");
newRange.addAnnotation(annotation);
}
rangeCnt++;
}
} else if (range.contains("^")) {
String[] rangeSplit = range.split("\\^");
int at = Integer.parseInt(rangeSplit[0]);
SequenceAnnotation sa =
topCD.createSequenceAnnotation("annotation"+featureCnt,"cut",at,orientation);
//sa.setComponent("feature"+featureCnt);
sa.addRole(role);
sa.setName(featureType);
} else {
boolean startLessThan=false;
boolean endGreaterThan=false;
if (range.contains("<")) {
startLessThan=true;
range = range.replace("<","");
}
if (range.contains(">")) {
endGreaterThan=true;
range = range.replace(">", "");
}
boolean singleBaseRange = false;
String[] rangeSplit = null;
if (range.contains(".") && !range.contains("..")) {
rangeSplit = range.split("\\.");
singleBaseRange = true;
} else {
rangeSplit = range.split("\\.\\.");
}
int start = Integer.parseInt(rangeSplit[0]);
int end = Integer.parseInt(rangeSplit[0]);
if (rangeSplit.length > 1) {
end = Integer.parseInt(rangeSplit[1]);
}
if (start > end && circular) {
SequenceAnnotation sa =
topCD.createSequenceAnnotation("annotation"+featureCnt,"range0",start,baseCount,orientation);
//sa.setComponent("feature"+featureCnt);
sa.addRole(role);
sa.setName(featureType);
annotation = new Annotation(new QName(GBCONVNAMESPACE,STRADLESORIGIN,GBCONVPREFIX),"true");
sa.addAnnotation(annotation);
Range newRange = (Range)sa.getLocation("range0");
if (startLessThan) {
annotation = new Annotation(new QName(GBCONVNAMESPACE,STARTLESSTHAN,GBCONVPREFIX),"true");
newRange.addAnnotation(annotation);
}
if (singleBaseRange) {
annotation = new Annotation(new QName(GBCONVNAMESPACE,SINGLEBASERANGE,GBCONVPREFIX),"true");
newRange.addAnnotation(annotation);
}
newRange = sa.addRange("range1", 1, end, orientation);
if (singleBaseRange) {
annotation = new Annotation(new QName(GBCONVNAMESPACE,SINGLEBASERANGE,GBCONVPREFIX),"true");
newRange.addAnnotation(annotation);
}
if (endGreaterThan) {
annotation = new Annotation(new QName(GBCONVNAMESPACE,ENDGREATERTHAN,GBCONVPREFIX),"true");
newRange.addAnnotation(annotation);
}
} else {
SequenceAnnotation sa =
topCD.createSequenceAnnotation("annotation"+featureCnt,"range",start,end,orientation);
//sa.setComponent("feature"+featureCnt);
sa.addRole(role);
sa.setName(featureType);
Range newRange = (Range)sa.getLocation("range");
if (startLessThan) {
annotation = new Annotation(new QName(GBCONVNAMESPACE,STARTLESSTHAN,GBCONVPREFIX),"true");
newRange.addAnnotation(annotation);
}
if (endGreaterThan) {
annotation = new Annotation(new QName(GBCONVNAMESPACE,ENDGREATERTHAN,GBCONVPREFIX),"true");
newRange.addAnnotation(annotation);
}
if (singleBaseRange) {
annotation = new Annotation(new QName(GBCONVNAMESPACE,SINGLEBASERANGE,GBCONVPREFIX),"true");
newRange.addAnnotation(annotation);
}
}
}
labelType = "";
lastRole = role;
featureCnt++;
}
} else if (originMode) {
if (featureCnt==1) {
topCD.clearRoles();
topCD.addRole(lastRole);
}
if(elements == null) { elements = new String(""); }
if (strLine.startsWith("
cont = true;
break;
}
String[] strSplit = strLine.split(" ");
for (int i = 1; i < strSplit.length; i++) {
sbSequence.append(strSplit[i]);
}
}
cont = false;
}
}
if (topCD!=null) {
//throw new SBOLConversionException("Invalid GenBank file.");
Sequence sequence = doc.createSequence(id+"_seq", version, sbSequence.toString(), Sequence.IUPAC_DNA);
topCD.addSequence(sequence);
createSubComponentDefinitions(doc,topCD,type,sbSequence.toString(),version);
}
if (!cont) break;
}
br.close();
}
}
|
package org.languagetool.rules.spelling.morfologik;
import ml.dmlc.xgboost4j.java.*;
import org.apache.commons.lang3.tuple.Pair;
import org.jetbrains.annotations.Nullable;
import org.languagetool.*;
import org.languagetool.languagemodel.LanguageModel;
import org.languagetool.rules.Categories;
import org.languagetool.rules.ITSIssueType;
import org.languagetool.rules.RuleMatch;
import org.languagetool.rules.spelling.SpellingCheckRule;
import org.languagetool.rules.ngrams.GoogleTokenUtil;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class MorfologikSpellerRule extends SpellingCheckRule {
private static final Integer DEFAULT_CONTEXT_LENGTH = 2;
protected MorfologikMultiSpeller speller1;
protected MorfologikMultiSpeller speller2;
protected MorfologikMultiSpeller speller3;
protected Locale conversionLocale;
private boolean ignoreTaggedWords = false;
private boolean checkCompound = false;
private Pattern compoundRegex = Pattern.compile("-");
private final UserConfig userConfig;
private static final String XGBOOST_MODEL_BASE_PATH = "org/languagetool/resource/speller_rule/models/";
private static final String DEFAULT_PATH_TO_NGRAMS = "/home/ec2-user/ngram"; //TODO
private static NGramUtil nGramUtil;
private static Booster booster;
/**
* Get the filename, e.g., <tt>/resource/pl/spelling.dict</tt>.
*/
public abstract String getFileName();
@Override
public abstract String getId();
public MorfologikSpellerRule(ResourceBundle messages, Language language) throws IOException {
this(messages, language, null);
}
public MorfologikSpellerRule(ResourceBundle messages, Language language, UserConfig userConfig) throws IOException {
super(messages, language, userConfig);
this.userConfig = userConfig;
super.setCategory(Categories.TYPOS.getCategory(messages));
this.conversionLocale = conversionLocale != null ? conversionLocale : Locale.getDefault();
init();
setLocQualityIssueType(ITSIssueType.Misspelling);
nGramUtil = new NGramUtil(language);
try (InputStream models_path = this.getClass().getClassLoader().getResourceAsStream(XGBOOST_MODEL_BASE_PATH + this.getId() + "/spc.model")) {
booster = XGBoost.loadModel(models_path);
} catch (XGBoostError xgBoostError) {
throw new RuntimeException("error when loading xgboost model for " + this.getId());
}
}
@Override
public String getDescription() {
return messages.getString("desc_spelling");
}
public void setLocale(Locale locale) {
conversionLocale = locale;
}
/**
* Skip words that are known in the POS tagging dictionary, assuming they
* cannot be incorrect.
*/
public void setIgnoreTaggedWords() {
ignoreTaggedWords = true;
}
@Override
public RuleMatch[] match(AnalyzedSentence sentence) throws IOException {
List<RuleMatch> ruleMatches = new ArrayList<>();
AnalyzedTokenReadings[] tokens = getSentenceWithImmunization(sentence).getTokensWithoutWhitespace();
//lazy init
if (speller1 == null) {
String binaryDict = null;
if (JLanguageTool.getDataBroker().resourceExists(getFileName())) {
binaryDict = getFileName();
}
if (binaryDict != null) {
initSpeller(binaryDict);
} else {
// should not happen, as we only configure this rule (or rather its subclasses)
// when we have the resources:
return toRuleMatchArray(ruleMatches);
}
}
int idx = -1;
for (AnalyzedTokenReadings token : tokens) {
idx++;
if (canBeIgnored(tokens, idx, token)) {
continue;
}
// if we use token.getToken() we'll get ignored characters inside and speller will choke
String word = token.getAnalyzedToken(0).getToken();
if (tokenizingPattern() == null) {
ruleMatches.addAll(getRuleMatches(word, token.getStartPos(), sentence));
} else {
int index = 0;
Matcher m = tokenizingPattern().matcher(word);
while (m.find()) {
String match = word.subSequence(index, m.start()).toString();
ruleMatches.addAll(getRuleMatches(match, token.getStartPos() + index, sentence));
index = m.end();
}
if (index == 0) { // tokenizing char not found
ruleMatches.addAll(getRuleMatches(word, token.getStartPos(), sentence));
} else {
ruleMatches.addAll(getRuleMatches(word.subSequence(
index, word.length()).toString(), token.getStartPos() + index, sentence));
}
}
}
return toRuleMatchArray(ruleMatches);
}
private void initSpeller(String binaryDict) throws IOException {
String plainTextDict = null;
if (JLanguageTool.getDataBroker().resourceExists(getSpellingFileName())) {
plainTextDict = getSpellingFileName();
}
if (plainTextDict != null) {
speller1 = new MorfologikMultiSpeller(binaryDict, plainTextDict, userConfig, 1);
speller2 = new MorfologikMultiSpeller(binaryDict, plainTextDict, userConfig, 2);
speller3 = new MorfologikMultiSpeller(binaryDict, plainTextDict, userConfig, 3);
setConvertsCase(speller1.convertsCase());
} else {
throw new RuntimeException("Could not find ignore spell file in path: " + getSpellingFileName());
}
}
private boolean canBeIgnored(AnalyzedTokenReadings[] tokens, int idx, AnalyzedTokenReadings token) throws IOException {
return token.isSentenceStart() ||
token.isImmunized() ||
token.isIgnoredBySpeller() ||
isUrl(token.getToken()) ||
isEMail(token.getToken()) ||
(ignoreTaggedWords && token.isTagged()) ||
ignoreToken(tokens, idx);
}
/**
* @return true if the word is misspelled
* @since 2.4
*/
protected boolean isMisspelled(MorfologikMultiSpeller speller, String word) {
if (!speller.isMisspelled(word)) {
return false;
}
if (checkCompound) {
if (compoundRegex.matcher(word).find()) {
String[] words = compoundRegex.split(word);
for (String singleWord: words) {
if (speller.isMisspelled(singleWord)) {
return true;
}
}
return false;
}
}
return true;
}
protected List<RuleMatch> getRuleMatches(String word, int startPos, AnalyzedSentence sentence) throws IOException {
List<RuleMatch> ruleMatches = new ArrayList<>();
if (isMisspelled(speller1, word) || isProhibited(word)) {
RuleMatch ruleMatch = new RuleMatch(this, sentence, startPos, startPos
+ word.length(), messages.getString("spelling"),
messages.getString("desc_spelling_short"));
List<String> suggestions = speller1.getSuggestions(word);
if (suggestions.isEmpty() && word.length() >= 5) {
// speller1 uses a maximum edit distance of 1, it won't find suggestion for "garentee", "greatful" etc.
suggestions.addAll(speller2.getSuggestions(word));
if (suggestions.isEmpty()) {
suggestions.addAll(speller3.getSuggestions(word));
}
}
suggestions.addAll(0, getAdditionalTopSuggestions(suggestions, word));
suggestions.addAll(getAdditionalSuggestions(suggestions, word));
if (!suggestions.isEmpty()) {
filterSuggestions(suggestions);
ruleMatch.setSuggestedReplacements(orderSuggestions(suggestions, word, sentence, startPos, word.length()));
}
ruleMatches.add(ruleMatch);
}
return ruleMatches;
}
/**
* Get the regular expression pattern used to tokenize
* the words as in the source dictionary. For example,
* it may contain a hyphen, if the words with hyphens are
* not included in the dictionary
* @return A compiled {@link Pattern} that is used to tokenize words or {@code null}.
*/
@Nullable
public Pattern tokenizingPattern() {
return null;
}
protected List<String> orderSuggestions(List<String> suggestions, String word) {
return suggestions;
}
protected List<String> orderSuggestions(List<String> suggestions, String word, AnalyzedSentence sentence, int startPos, int wordLength) {
List<Pair<String, Float>> suggestionsProbs = new LinkedList<>();
for (int i = 0; i < suggestions.size(); i++) {
String suggestion = suggestions.get(i);
String text = sentence.getText();
String correctedSentence = text.substring(0, startPos) + suggestion + sentence.getText().substring(startPos + wordLength);
float score = 0;
try {
score = processRow(text, correctedSentence, word, suggestion, startPos, DEFAULT_CONTEXT_LENGTH);
} catch (IOException e) {
e.printStackTrace();
}
suggestionsProbs.add(Pair.of(suggestion, score));
}
Comparator<Pair<String, Float>> comparing = Comparator.comparing(Pair::getValue);
suggestionsProbs.sort(comparing.reversed());
List<String> result = new LinkedList<>();
suggestionsProbs.iterator().forEachRemaining((Pair<String, Float> p) -> result.add(p.getKey()));
return result;
}
private static float processRow(String sentence, String correctedSentence, String covered, String replacement,
Integer suggestionPos, Integer contextLength) throws IOException {
Pair<String, String> context = Pair.of("", "");
int errorStartIdx;
int sentencesDifferenceCharIdx = Utils.firstDifferencePosition(sentence, correctedSentence);
if (sentencesDifferenceCharIdx != -1) {
errorStartIdx = Utils.startOfErrorString(sentence, covered, sentencesDifferenceCharIdx);
if (errorStartIdx != -1) {
context = Utils.extractContext(sentence, covered, errorStartIdx, contextLength);
}
}
String leftContextCovered = context.getKey();
String rightContextCovered = context.getValue();
// String covered = covered;
String correction = replacement;
String leftContextCorrection = leftContextCovered.isEmpty() ? "" : leftContextCovered.substring(0, leftContextCovered.length() - covered.length()) + correction;
String rightContextCorrection = rightContextCovered.isEmpty() ? "" : correction + rightContextCovered.substring(covered.length());
boolean firstLetterMatches = Utils.longestCommonPrefix(new String[]{correction, covered}).length() != 0;
Integer editDistance = Utils.editDisctance(covered, correction);
List<String> leftContextCoveredTokenized = nGramUtil.tokenizeString(leftContextCovered.isEmpty() ? covered : leftContextCovered);
double leftContextCoveredProba = nGramUtil.stringProbability(leftContextCoveredTokenized, 3);
List<String> rightContextCoveredTokenized = nGramUtil.tokenizeString(rightContextCovered.isEmpty() ? covered : rightContextCovered);
double rightContextCoveredProba = nGramUtil.stringProbability(rightContextCoveredTokenized, 3);
List<String> leftContextCorrectionTokenized = nGramUtil.tokenizeString(leftContextCorrection.isEmpty() ? correction : leftContextCorrection);
double leftContextCorrectionProba = nGramUtil.stringProbability(leftContextCorrectionTokenized, 3);
List<String> rightContextCorrectionTokenized = nGramUtil.tokenizeString(rightContextCorrection.isEmpty() ? correction : rightContextCorrection);
double rightContextCorrectionProba = nGramUtil.stringProbability(rightContextCorrectionTokenized, 3);
float left_context_covered_length = leftContextCoveredTokenized.size();
float left_context_covered_proba = (float) leftContextCoveredProba;
float right_context_covered_length = rightContextCoveredTokenized.size();
float right_context_covered_proba = (float) rightContextCoveredProba;
float left_context_correction_length = leftContextCorrectionTokenized.size();
float left_context_correction_proba = (float) leftContextCorrectionProba;
float right_context_correction_length = rightContextCorrectionTokenized.size();
float right_context_correction_proba = (float) rightContextCorrectionProba;
float first_letter_matches = firstLetterMatches ? 1f : 0f;
float edit_distance = editDistance;
float[] data = {left_context_covered_length, left_context_covered_proba,
right_context_covered_length, right_context_covered_proba,
left_context_correction_length, left_context_correction_proba,
right_context_correction_length, right_context_correction_proba, first_letter_matches, edit_distance};
float res = -1;
try {
res = booster.predict(new DMatrix(data, 1, data.length))[0][0];
} catch (XGBoostError xgBoostError) {
xgBoostError.printStackTrace();
}
return res;
}
/**
* @param checkCompound If true and the word is not in the dictionary
* it will be split (see {@link #setCompoundRegex(String)})
* and each component will be checked separately
* @since 2.4
*/
protected void setCheckCompound(boolean checkCompound) {
this.checkCompound = checkCompound;
}
/**
* @param compoundRegex see {@link #setCheckCompound(boolean)}
* @since 2.4
*/
protected void setCompoundRegex(String compoundRegex) {
this.compoundRegex = Pattern.compile(compoundRegex);
}
/**
* Checks whether a given String consists only of surrogate pairs.
* @param word to be checked
* @since 4.2
*/
protected boolean isSurrogatePairCombination (String word) {
if (word.length() > 1 && word.length() % 2 == 0 && word.codePointCount(0, word.length()) != word.length()) {
// some symbols such as emojis () have a string length that equals 2
boolean isSurrogatePairCombination = true;
for (int i = 0; i < word.length() && isSurrogatePairCombination; i += 2) {
isSurrogatePairCombination &= Character.isSurrogatePair(word.charAt(i), word.charAt(i + 1));
}
if (isSurrogatePairCombination) {
return isSurrogatePairCombination;
}
}
return false;
}
}
class Utils {
public static String leftContext(String originalSentence, int errorStartIdx, String errorString, int contextLength) {
String regex = repeat(contextLength, "\\w+\\W+") + errorString + "$";
String stringToSearch = originalSentence.substring(0, errorStartIdx + errorString.length());
return findFirstRegexMatch(regex, stringToSearch);
}
public static String rightContext(String originalSentence, int errorStartIdx, String errorString, int contextLength) {
String regex = "^" + errorString + repeat(contextLength, "\\W+\\w+");
String stringToSearch = originalSentence.substring(errorStartIdx);
return findFirstRegexMatch(regex, stringToSearch);
}
public static int firstDifferencePosition(String sentence1, String sentence2) {
int result = -1;
for (int i = 0; i < sentence1.length(); i++) {
if (i >= sentence2.length() || sentence1.charAt(i) != sentence2.charAt(i)) {
result = i;
break;
}
}
return result;
}
public static int startOfErrorString(String sentence, String errorString, int sentencesDifferenceCharIdx) {
int result = -1;
List<Integer> possibleIntersections = allIndexesOf(sentence.charAt(sentencesDifferenceCharIdx), errorString);
for (int i : possibleIntersections) {
if (sentencesDifferenceCharIdx - i < 0 || sentencesDifferenceCharIdx - i + errorString.length() > sentence.length())
continue;
String possibleErrorString = sentence.substring(sentencesDifferenceCharIdx - i,
sentencesDifferenceCharIdx - i + errorString.length());
if (possibleErrorString.equals(errorString)) {
result = sentencesDifferenceCharIdx - i;
break;
}
}
return result;
}
public static String getMaximalPossibleRightContext(String sentence, int errorStartIdx, String errorString,
int startingContextLength) {
String rightContext = "";
for (int contextLength = startingContextLength; contextLength > 0; contextLength
rightContext = rightContext(sentence, errorStartIdx, errorString, contextLength);
if (!rightContext.isEmpty()) {
break;
}
}
return rightContext;
}
public static String getMaximalPossibleLeftContext(String sentence, int errorStartIdx, String errorString,
int startingContextLength) {
String leftContext = "";
for (int contextLength = startingContextLength; contextLength > 0; contextLength
leftContext = leftContext(sentence, errorStartIdx, errorString, contextLength);
if (!leftContext.isEmpty()) {
break;
}
}
return leftContext;
}
public static Pair<String, String> extractContext(String sentence, String covered, int errorStartIdx, int contextLength) {
int errorEndIdx = errorStartIdx + covered.length();
String errorString = sentence.substring(errorStartIdx, errorEndIdx);
String leftContext = getMaximalPossibleLeftContext(sentence, errorStartIdx, errorString, contextLength);
String rightContext = getMaximalPossibleRightContext(sentence, errorStartIdx, errorString, contextLength);
return Pair.of(leftContext, rightContext);
}
public static String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
if (strs.length == 1)
return strs[0];
int minLen = strs.length + 1;
for (String str : strs) {
if (minLen > str.length()) {
minLen = str.length();
}
}
for (int i = 0; i < minLen; i++) {
for (int j = 0; j < strs.length - 1; j++) {
String s1 = strs[j];
String s2 = strs[j + 1];
if (s1.charAt(i) != s2.charAt(i)) {
return s1.substring(0, i);
}
}
}
return strs[0].substring(0, minLen);
}
public static int editDisctance(String x, String y) {
int[][] dp = new int[x.length() + 1][y.length() + 1];
for (int i = 0; i <= x.length(); i++) {
for (int j = 0; j <= y.length(); j++) {
if (i == 0) {
dp[i][j] = j;
} else if (j == 0) {
dp[i][j] = i;
} else {
dp[i][j] = min(dp[i - 1][j - 1] + costOfSubstitution(x.charAt(i - 1), y.charAt(j - 1)),
dp[i - 1][j] + 1,
dp[i][j - 1] + 1);
}
}
}
return dp[x.length()][y.length()];
}
private static int costOfSubstitution(char a, char b) {
return a == b ? 0 : 1;
}
private static int min(int... numbers) {
return Arrays.stream(numbers)
.min().orElse(Integer.MAX_VALUE);
}
private static String findFirstRegexMatch(String regex, String stringToSearch) {
String result = "";
Pattern pattern = Pattern.compile(regex);
Matcher stringToSearchMatcher = pattern.matcher(stringToSearch);
if (stringToSearchMatcher.find()) {
result = stringToSearch.substring(stringToSearchMatcher.start(), stringToSearchMatcher.end());
}
return result;
}
private static String repeat(int count, String with) {
return new String(new char[count]).replace("\0", with);
}
private static List<Integer> allIndexesOf(char character, String string) {
List<Integer> indexes = new ArrayList<>();
for (int index = string.indexOf(character); index >= 0; index = string.indexOf(character, index + 1)) {
indexes.add(index);
}
return indexes;
}
}
class NGramUtil {
// private static final JLanguageTool lt = new JLanguageTool(new AmericanEnglish());
private static Language language;
private static LanguageModel languageModel;
public NGramUtil(Language language) {
try {
NGramUtil.language = language;
System.out.println("in ngram utils: " + System.getProperty("ngram.path"));
languageModel = language.getLanguageModel(Paths.get(System.getProperty("ngram.path")).toFile());
} catch (IOException e) {
throw new RuntimeException("NGram file not found");
}
}
public List<String> tokenizeString(String s) {
return GoogleTokenUtil.getGoogleTokensForString(s, false, language);
}
public Double stringProbability(List<String> sTokenized, int length) {
if (sTokenized.size() > length) {
sTokenized = sTokenized.subList(sTokenized.size() - length, sTokenized.size());
}
return sTokenized.isEmpty() ? null : languageModel.getPseudoProbability(sTokenized).getProb();
}
}
|
package edu.kit.ipd.crowdcontrol.objectservice.database.transformers;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import edu.kit.ipd.crowdcontrol.objectservice.database.model.tables.records.ConstraintRecord;
import edu.kit.ipd.crowdcontrol.objectservice.database.model.tables.records.ExperimentRecord;
import edu.kit.ipd.crowdcontrol.objectservice.database.model.tables.records.RatingOptionExperimentRecord;
import edu.kit.ipd.crowdcontrol.objectservice.database.model.tables.records.TagRecord;
import edu.kit.ipd.crowdcontrol.objectservice.proto.AlgorithmOption;
import edu.kit.ipd.crowdcontrol.objectservice.proto.AnswerType;
import edu.kit.ipd.crowdcontrol.objectservice.proto.Constraint;
import edu.kit.ipd.crowdcontrol.objectservice.proto.Experiment;
import org.jooq.tools.json.JSONObject;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Handles transformations of experiments from and to the protocol buffer messages.
*
* @author Leander K.
* @author Marcel Hollderbach
* @author Niklas Keller
*/
public class ExperimentTransformer extends AbstractTransformer {
/**
* Convert a experiment record to a proto object with the given additional information.
*
* @param record The Database record to use
* @param state state of the experiment
*
* @return the experiment object with the given data
*/
public static Experiment toProto(ExperimentRecord record, Experiment.State state) {
Type type = new TypeToken<Map<String, String>>() {
}.getType();
Function<String, AlgorithmOption> algo = name -> AlgorithmOption.newBuilder().setName(name).build();
return builder(Experiment.newBuilder())
.set(record.getIdExperiment(), Experiment.Builder::setId)
.set(record.getTitle(), Experiment.Builder::setTitle)
.set(record.getDescription(), Experiment.Builder::setDescription)
.set(state, Experiment.Builder::setState)
.set(record.getAnswerType(), (builder, x) -> builder.setAnswerType(AnswerType.valueOf(x)))
.set(record.getAlgorithmTaskChooser(), (builder, x) -> builder.setAlgorithmTaskChooser(algo.apply(x)))
.set(record.getAlgorithmQualityAnswer(), (builder, x) -> builder.setAlgorithmQualityAnswer(algo.apply(x)))
.set(record.getAlgorithmQualityRating(), (builder, x) -> builder.setAlgorithmQualityRating(algo.apply(x)))
.set(toInteger(record.getAnwersPerWorker()), Experiment.Builder::setAnswersPerWorker)
.set(toInteger(record.getRatingsPerWorker()), Experiment.Builder::setRatingsPerWorker)
.set(toInteger(record.getRatingsPerAnswer()), Experiment.Builder::setRatingsPerAnswer)
.set(toInteger(record.getNeededAnswers()), Experiment.Builder::setNeededAnswers)
.set(toInteger(record.getBasePayment()), Experiment.Builder::setPaymentBase)
.set(toInteger(record.getBonusAnswer()), Experiment.Builder::setPaymentAnswer)
.set(toInteger(record.getBonusRating()), Experiment.Builder::setPaymentRating)
.set(record.getTemplateData(), ((builder, s) -> builder.putAllPlaceholders(new Gson().fromJson(s, type))))
.set(toInteger(record.getWorkerQualityThreshold()), Experiment.Builder::setWorkerQualityThreshold)
.set(toInteger(record.getTemplate()), Experiment.Builder::setTemplateId)
.set(toInteger(record.getPaymentQualityThreshold()), Experiment.Builder::setPaymentQualityThreshold)
.getBuilder()
.build();
}
/**
* Convert a experiment record to a proto object with the given additional infos
*
* @param record The Database record to use
* @param state state of the experiment
* @param constraintRecords constraints of a experiment
* @param platforms calibrations on the platform to use
* @param tagRecords tags which are saved for a experiment
*
* @return the experiment object with the given data
*/
public static Experiment toProto(ExperimentRecord record, Experiment.State state,
List<ConstraintRecord> constraintRecords,
List<Experiment.Population> platforms,
List<TagRecord> tagRecords,
List<RatingOptionExperimentRecord> ratingOptions,
AlgorithmOption taskChooser,
AlgorithmOption answerQuality,
AlgorithmOption ratingQuality) {
List<Constraint> constraints = constraintRecords.stream()
.map(TagConstraintTransformer::toConstraintsProto)
.collect(Collectors.toList());
return builder(toProto(record, state).toBuilder())
.set(taskChooser, Experiment.Builder::setAlgorithmTaskChooser)
.set(answerQuality, Experiment.Builder::setAlgorithmQualityAnswer)
.set(ratingQuality, Experiment.Builder::setAlgorithmQualityRating)
.getBuilder()
.addAllConstraints(constraints)
.addAllPopulations(platforms)
.addAllTags(tagRecords.stream().map(TagConstraintTransformer::toTagProto).collect(Collectors.toList()))
.addAllRatingOptions(ratingOptions.stream().map(ExperimentTransformer::transform).collect(Collectors.toList()))
.build();
}
private static String transform(AnswerType answerType) {
if (answerType == AnswerType.INVALID) return null;
return answerType.name();
}
private static Experiment.RatingOption transform(RatingOptionExperimentRecord record) {
return Experiment.RatingOption.newBuilder()
.setName(record.getName())
.setValue(record.getValue())
.build();
}
/**
* Merge the data from a experiment proto object into a existing record
*
* @param record_ The original record to merge into
* @param experiment the experiment to merge
*
* @return A merged experiment record
*/
public static ExperimentRecord mergeProto(ExperimentRecord record_, Experiment experiment) {
return merge(record_, experiment, (integer, record) -> {
switch (integer) {
case Experiment.ALGORITHM_QUALITY_ANSWER_FIELD_NUMBER:
//the parameters have to be done with the AlgorithmOptionTransform
record.setAlgorithmQualityAnswer(experiment.getAlgorithmQualityAnswer().getName());
break;
case Experiment.ALGORITHM_QUALITY_RATING_FIELD_NUMBER:
//the parameters have to be done with the AlgorithmOptionTransform
record.setAlgorithmQualityRating(experiment.getAlgorithmQualityRating().getName());
break;
case Experiment.ALGORITHM_TASK_CHOOSER_FIELD_NUMBER:
//the parameters have to be done with the AlgorithmOptionTransform
record.setAlgorithmTaskChooser(experiment.getAlgorithmTaskChooser().getName());
break;
case Experiment.ANSWER_TYPE_FIELD_NUMBER:
record.setAnswerType(transform(experiment.getAnswerType()));
break;
case Experiment.ANSWERS_PER_WORKER_FIELD_NUMBER:
record.setAnwersPerWorker(experiment.getAnswersPerWorker().getValue());
break;
case Experiment.CONSTRAINTS_FIELD_NUMBER:
// has to be done manual with Constraints Transformer
break;
case Experiment.DESCRIPTION_FIELD_NUMBER:
record.setDescription(experiment.getDescription());
break;
case Experiment.PAYMENT_ANSWER_FIELD_NUMBER:
record.setBonusAnswer(experiment.getPaymentAnswer().getValue());
break;
case Experiment.PAYMENT_BASE_FIELD_NUMBER:
record.setBasePayment(experiment.getPaymentBase().getValue());
break;
case Experiment.PAYMENT_RATING_FIELD_NUMBER:
record.setBonusRating(experiment.getPaymentRating().getValue());
break;
case Experiment.PLACEHOLDERS_FIELD_NUMBER:
if (experiment.getPlaceholders().size() == 0) {
break;
}
record.setTemplateData(new JSONObject(experiment.getPlaceholders()).toString());
break;
case Experiment.POPULATIONS_FIELD_NUMBER:
// has to be done manual with CalibrationsTransformer
break;
case Experiment.RATINGS_PER_ANSWER_FIELD_NUMBER:
record.setRatingsPerAnswer(experiment.getRatingsPerAnswer().getValue());
break;
case Experiment.STATE_FIELD_NUMBER:
// this is not merged into the database this event will
// start the platforms to populate this experiment
// which results in entries in the database which will mark the experiment as published
break;
case Experiment.TAGS_FIELD_NUMBER:
// has to be done manual with TagConstraintTransform
break;
case Experiment.TEMPLATE_ID_FIELD_NUMBER:
record.setTemplate(experiment.getTemplateId().getValue());
break;
case Experiment.TITLE_FIELD_NUMBER:
record.setTitle(experiment.getTitle());
break;
case Experiment.NEEDED_ANSWERS_FIELD_NUMBER:
record.setNeededAnswers(experiment.getNeededAnswers().getValue());
break;
case Experiment.RATINGS_PER_WORKER_FIELD_NUMBER:
record.setRatingsPerWorker(experiment.getRatingsPerWorker().getValue());
break;
case Experiment.WORKER_QUALITY_THRESHOLD_FIELD_NUMBER:
record.setWorkerQualityThreshold(experiment.getWorkerQualityThreshold().getValue());
break;
case Experiment.PAYMENT_QUALITY_THRESHOLD_FIELD_NUMBER:
record.setPaymentQualityThreshold(experiment.getPaymentQualityThreshold().getValue());
break;
}
});
}
/**
* creates a list of RatingOptionExperimentRecords from the passed experiment
*
* @param experiment the Experiment
*
* @return a list of RatingOptionExperimentRecords
*/
public static List<RatingOptionExperimentRecord> toRecord(Experiment experiment) {
return experiment.getRatingOptionsList().stream()
.map(ratingOption -> merge(new RatingOptionExperimentRecord(), ratingOption, (field, record) -> {
switch (field) {
case Experiment.RatingOption.NAME_FIELD_NUMBER:
record.setName(ratingOption.getName());
break;
case Experiment.RatingOption.VALUE_FIELD_NUMBER:
record.setValue(ratingOption.getValue());
break;
}
})
)
.collect(Collectors.toList());
}
}
|
package com.anrisoftware.sscontrol.hostname.service;
import static com.anrisoftware.sscontrol.hostname.service.HostnameFactory.NAME;
import static java.lang.String.format;
import static org.slf4j.LoggerFactory.getLogger;
import groovy.lang.Closure;
import groovy.lang.GroovyObjectSupport;
import groovy.lang.Script;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.lang3.builder.ToStringBuilder;
import com.anrisoftware.resources.templates.api.TemplatesFactory;
import com.anrisoftware.sscontrol.core.api.ProfileService;
import com.anrisoftware.sscontrol.core.api.Service;
import com.anrisoftware.sscontrol.core.api.ServiceException;
import com.anrisoftware.sscontrol.workers.command.script.ScriptCommandWorkerFactory;
import com.anrisoftware.sscontrol.workers.text.tokentemplate.TokensTemplateWorkerFactory;
import com.google.inject.Provider;
class HostnameServiceImpl extends GroovyObjectSupport implements Service {
private static final String WORKER_LOGGING_NAME = "com.anrisoftware.sscontrol.hostname.service.%s";
/**
* @version 0.1
*/
private static final long serialVersionUID = 8026832603525631371L;
private final HostnameServiceImplLogger log;
private final Map<String, Provider<Script>> scripts;
private ProfileService profile;
private String hostname;
private final TemplatesFactory templates;
@Inject
private TokensTemplateWorkerFactory tokensTemplateWorkerFactory;
@Inject
private ScriptCommandWorkerFactory scriptCommandWorkerFactory;
@Inject
HostnameServiceImpl(HostnameServiceImplLogger logger,
Map<String, Provider<Script>> scripts, TemplatesFactory templates,
@Named("hostname-service-properties") Properties properties) {
this.log = logger;
this.scripts = scripts;
this.templates = templates;
}
public Object hostname(Closure<?> closure) {
return this;
}
public Object set_hostname(String name) {
log.checkHostname(this, name);
hostname = name;
log.hostnameSet(this, name);
return this;
}
public String getHostname() {
return hostname;
}
@Override
public String getName() {
return NAME;
}
public void setProfile(ProfileService newProfile) {
profile = newProfile;
log.profileSet(this, newProfile);
}
public ProfileService getProfile() {
return profile;
}
@Override
public Service call() throws ServiceException {
String name = profile.getProfileName();
Script worker = scripts.get(name).get();
Map<Class<?>, Object> workers = getWorkers();
worker.setProperty("workers", workers);
worker.setProperty("templates", templates);
worker.setProperty("system", profile.getEntry("system"));
worker.setProperty("profile", profile.getEntry(NAME));
worker.setProperty("service", this);
worker.setProperty("name", name);
worker.setProperty("log", getLogger(format(WORKER_LOGGING_NAME, name)));
worker.run();
return this;
}
private Map<Class<?>, Object> getWorkers() {
Map<Class<?>, Object> workers = new HashMap<Class<?>, Object>();
workers.put(TokensTemplateWorkerFactory.class,
tokensTemplateWorkerFactory);
workers.put(ScriptCommandWorkerFactory.class,
scriptCommandWorkerFactory);
return workers;
}
@Override
public String toString() {
return new ToStringBuilder(this).toString();
}
}
|
package com.artifex.mupdf;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.RectF;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ViewSwitcher;
class SearchTaskResult {
public final int pageNumber;
public final RectF searchBoxes[];
SearchTaskResult(int _pageNumber, RectF _searchBoxes[]) {
pageNumber = _pageNumber;
searchBoxes = _searchBoxes;
}
}
class ProgressDialogX extends ProgressDialog {
public ProgressDialogX(Context context) {
super(context);
}
private boolean mCancelled = false;
public boolean isCancelled() {
return mCancelled;
}
@Override
public void cancel() {
mCancelled = true;
super.cancel();
}
}
public class MuPDFActivity extends Activity
{
/* The core rendering instance */
private enum LinkState {DEFAULT, HIGHLIGHT, INHIBIT};
private final int TAP_PAGE_MARGIN = 5;
private final int SEARCH_PROGRESS_DELAY = 200;
private MuPDFCore core;
private String mFileName;
private ReaderView mDocView;
private View mButtonsView;
private boolean mButtonsVisible;
private EditText mPasswordView;
private TextView mFilenameView;
private SeekBar mPageSlider;
private TextView mPageNumberView;
private ImageButton mSearchButton;
private ImageButton mCancelButton;
private ImageButton mOutlineButton;
private ViewSwitcher mTopBarSwitcher;
private ImageButton mLinkButton;
private boolean mTopBarIsSearch;
private ImageButton mSearchBack;
private ImageButton mSearchFwd;
private EditText mSearchText;
private AsyncTask<Integer,Integer,SearchTaskResult> mSearchTask;
private SearchTaskResult mSearchTaskResult;
private AlertDialog.Builder mAlertBuilder;
private LinkState mLinkState = LinkState.DEFAULT;
private final Handler mHandler = new Handler();
private MuPDFCore openFile(String path)
{
int lastSlashPos = path.lastIndexOf('/');
mFileName = new String(lastSlashPos == -1
? path
: path.substring(lastSlashPos+1));
System.out.println("Trying to open "+path);
try
{
core = new MuPDFCore(path);
// New file: drop the old outline data
OutlineActivityData.set(null);
}
catch (Exception e)
{
System.out.println(e);
return null;
}
return core;
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mAlertBuilder = new AlertDialog.Builder(this);
if (core == null) {
core = (MuPDFCore)getLastNonConfigurationInstance();
if (savedInstanceState != null && savedInstanceState.containsKey("FileName")) {
mFileName = savedInstanceState.getString("FileName");
}
}
if (core == null) {
Intent intent = getIntent();
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Uri uri = intent.getData();
if (uri.toString().startsWith("content://media/external/file")) {
// Handle view requests from the Transformer Prime's file manager
// Hopefully other file managers will use this same scheme, if not
// using explicit paths.
Cursor cursor = getContentResolver().query(uri, new String[]{"_data"}, null, null, null);
if (cursor.moveToFirst()) {
uri = Uri.parse(cursor.getString(0));
}
}
core = openFile(Uri.decode(uri.getEncodedPath()));
}
if (core != null && core.needsPassword()) {
requestPassword(savedInstanceState);
return;
}
}
if (core == null)
{
AlertDialog alert = mAlertBuilder.create();
alert.setTitle(R.string.open_failed);
alert.setButton(AlertDialog.BUTTON_POSITIVE, "Dismiss",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
return;
}
createUI(savedInstanceState);
}
public void requestPassword(final Bundle savedInstanceState) {
mPasswordView = new EditText(this);
mPasswordView.setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
mPasswordView.setTransformationMethod(new PasswordTransformationMethod());
AlertDialog alert = mAlertBuilder.create();
alert.setTitle(R.string.enter_password);
alert.setView(mPasswordView);
alert.setButton(AlertDialog.BUTTON_POSITIVE, "Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (core.authenticatePassword(mPasswordView.getText().toString())) {
createUI(savedInstanceState);
} else {
requestPassword(savedInstanceState);
}
}
});
alert.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
}
public void createUI(Bundle savedInstanceState) {
// Now create the UI.
// First create the document view making use of the ReaderView's internal
// gesture recognition
mDocView = new ReaderView(this) {
private boolean showButtonsDisabled;
public boolean onSingleTapUp(MotionEvent e) {
if (e.getX() < super.getWidth()/TAP_PAGE_MARGIN) {
super.moveToPrevious();
} else if (e.getX() > super.getWidth()*(TAP_PAGE_MARGIN-1)/TAP_PAGE_MARGIN) {
super.moveToNext();
} else if (!showButtonsDisabled) {
int linkPage = -1;
if (mLinkState != LinkState.INHIBIT) {
MuPDFPageView pageView = (MuPDFPageView) mDocView.getDisplayedView();
if (pageView != null) {
linkPage = pageView.hitLinkPage(e.getX(), e.getY());
}
}
if (linkPage != -1) {
mDocView.setDisplayedViewIndex(linkPage);
} else {
if (!mButtonsVisible) {
showButtons();
} else {
hideButtons();
}
}
}
return super.onSingleTapUp(e);
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (!showButtonsDisabled)
hideButtons();
return super.onScroll(e1, e2, distanceX, distanceY);
}
public boolean onScaleBegin(ScaleGestureDetector d) {
// Disabled showing the buttons until next touch.
// Not sure why this is needed, but without it
// pinch zoom can make the buttons appear
showButtonsDisabled = true;
return super.onScaleBegin(d);
}
public boolean onTouchEvent(MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN)
showButtonsDisabled = false;
return super.onTouchEvent(event);
}
protected void onChildSetup(int i, View v) {
if (mSearchTaskResult != null && mSearchTaskResult.pageNumber == i)
((PageView)v).setSearchBoxes(mSearchTaskResult.searchBoxes);
else
((PageView)v).setSearchBoxes(null);
((PageView)v).setLinkHighlighting(mLinkState == LinkState.HIGHLIGHT);
}
protected void onMoveToChild(int i) {
mPageNumberView.setText(String.format("%d/%d", i+1, core.countPages()));
mPageSlider.setMax(core.countPages()-1);
mPageSlider.setProgress(i);
if (mSearchTaskResult != null && mSearchTaskResult.pageNumber != i) {
mSearchTaskResult = null;
mDocView.resetupChildren();
}
}
protected void onSettle(View v) {
// When the layout has settled ask the page to render
// in HQ
((PageView)v).addHq();
}
protected void onUnsettle(View v) {
// When something changes making the previous settled view
// no longer appropriate, tell the page to remove HQ
((PageView)v).removeHq();
}
};
mDocView.setAdapter(new MuPDFPageAdapter(this, core));
// Make the buttons overlay, and store all its
// controls in variables
makeButtonsView();
// Set the file-name text
mFilenameView.setText(mFileName);
// Activate the seekbar
mPageSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
mDocView.setDisplayedViewIndex(seekBar.getProgress());
}
public void onStartTrackingTouch(SeekBar seekBar) {}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
updatePageNumView(progress);
}
});
// Activate the search-preparing button
mSearchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
searchModeOn();
}
});
mCancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
searchModeOff();
}
});
// Search invoking buttons are disabled while there is no text specified
mSearchBack.setEnabled(false);
mSearchFwd.setEnabled(false);
// React to interaction with the text widget
mSearchText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
boolean haveText = s.toString().length() > 0;
mSearchBack.setEnabled(haveText);
mSearchFwd.setEnabled(haveText);
// Remove any previous search results
if (mSearchTaskResult != null) {
mSearchTaskResult = null;
mDocView.resetupChildren();
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {}
public void onTextChanged(CharSequence s, int start, int before,
int count) {}
});
//React to Done button on keyboard
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE)
search(1);
return false;
}
});
// Activate search invoking buttons
mSearchBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
hideKeyboard();
search(-1);
}
});
mSearchFwd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
hideKeyboard();
search(1);
}
});
mLinkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch(mLinkState) {
case DEFAULT:
mLinkState = LinkState.HIGHLIGHT;
mLinkButton.setImageResource(R.drawable.ic_hl_link);
//Inform pages of the change.
mDocView.resetupChildren();
break;
case HIGHLIGHT:
mLinkState = LinkState.INHIBIT;
mLinkButton.setImageResource(R.drawable.ic_nolink);
//Inform pages of the change.
mDocView.resetupChildren();
break;
case INHIBIT:
mLinkState = LinkState.DEFAULT;
mLinkButton.setImageResource(R.drawable.ic_link);
break;
}
}
});
if (core.hasOutline()) {
mOutlineButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
OutlineItem outline[] = core.getOutline();
if (outline != null) {
OutlineActivityData.get().items = outline;
Intent intent = new Intent(MuPDFActivity.this, OutlineActivity.class);
startActivityForResult(intent, 0);
}
}
});
} else {
mOutlineButton.setVisibility(View.GONE);
}
// Reenstate last state if it was recorded
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
mDocView.setDisplayedViewIndex(prefs.getInt("page"+mFileName, 0));
if (savedInstanceState == null || !savedInstanceState.getBoolean("ButtonsHidden", false))
showButtons();
if(savedInstanceState != null && savedInstanceState.getBoolean("SearchMode", false))
searchModeOn();
// Stick the document view and the buttons overlay into a parent view
RelativeLayout layout = new RelativeLayout(this);
layout.addView(mDocView);
layout.addView(mButtonsView);
layout.setBackgroundResource(R.drawable.tiled_background);
//layout.setBackgroundResource(R.color.canvas);
setContentView(layout);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode >= 0)
mDocView.setDisplayedViewIndex(resultCode);
super.onActivityResult(requestCode, resultCode, data);
}
public Object onRetainNonConfigurationInstance()
{
MuPDFCore mycore = core;
core = null;
return mycore;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mFileName != null && mDocView != null) {
outState.putString("FileName", mFileName);
// Store current page in the prefs against the file name,
// so that we can pick it up each time the file is loaded
// Other info is needed only for screen-orientation change,
// so it can go in the bundle
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putInt("page"+mFileName, mDocView.getDisplayedViewIndex());
edit.commit();
}
if (!mButtonsVisible)
outState.putBoolean("ButtonsHidden", true);
if (mTopBarIsSearch)
outState.putBoolean("SearchMode", true);
}
@Override
protected void onPause() {
super.onPause();
killSearch();
if (mFileName != null && mDocView != null) {
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putInt("page"+mFileName, mDocView.getDisplayedViewIndex());
edit.commit();
}
}
public void onDestroy()
{
if (core != null)
core.onDestroy();
core = null;
super.onDestroy();
}
void showButtons() {
if (!mButtonsVisible) {
mButtonsVisible = true;
// Update page number text and slider
int index = mDocView.getDisplayedViewIndex();
updatePageNumView(index);
mPageSlider.setMax(core.countPages()-1);
mPageSlider.setProgress(index);
if (mTopBarIsSearch) {
mSearchText.requestFocus();
showKeyboard();
}
Animation anim = new TranslateAnimation(0, 0, -mTopBarSwitcher.getHeight(), 0);
anim.setDuration(200);
anim.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {
mTopBarSwitcher.setVisibility(View.VISIBLE);
}
public void onAnimationRepeat(Animation animation) {}
public void onAnimationEnd(Animation animation) {}
});
mTopBarSwitcher.startAnimation(anim);
anim = new TranslateAnimation(0, 0, mPageSlider.getHeight(), 0);
anim.setDuration(200);
anim.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {
mPageSlider.setVisibility(View.VISIBLE);
}
public void onAnimationRepeat(Animation animation) {}
public void onAnimationEnd(Animation animation) {
mPageNumberView.setVisibility(View.VISIBLE);
}
});
mPageSlider.startAnimation(anim);
}
}
void hideButtons() {
if (mButtonsVisible) {
mButtonsVisible = false;
hideKeyboard();
Animation anim = new TranslateAnimation(0, 0, 0, -mTopBarSwitcher.getHeight());
anim.setDuration(200);
anim.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {}
public void onAnimationRepeat(Animation animation) {}
public void onAnimationEnd(Animation animation) {
mTopBarSwitcher.setVisibility(View.INVISIBLE);
}
});
mTopBarSwitcher.startAnimation(anim);
anim = new TranslateAnimation(0, 0, 0, mPageSlider.getHeight());
anim.setDuration(200);
anim.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {
mPageNumberView.setVisibility(View.INVISIBLE);
}
public void onAnimationRepeat(Animation animation) {}
public void onAnimationEnd(Animation animation) {
mPageSlider.setVisibility(View.INVISIBLE);
}
});
mPageSlider.startAnimation(anim);
}
}
void searchModeOn() {
mTopBarIsSearch = true;
//Focus on EditTextWidget
mSearchText.requestFocus();
showKeyboard();
mTopBarSwitcher.showNext();
}
void searchModeOff() {
mTopBarIsSearch = false;
hideKeyboard();
mTopBarSwitcher.showPrevious();
mSearchTaskResult = null;
// Make the ReaderView act on the change to mSearchTaskResult
// via overridden onChildSetup method.
mDocView.resetupChildren();
}
void updatePageNumView(int index) {
mPageNumberView.setText(String.format("%d/%d", index+1, core.countPages()));
}
void makeButtonsView() {
mButtonsView = getLayoutInflater().inflate(R.layout.buttons,null);
mFilenameView = (TextView)mButtonsView.findViewById(R.id.docNameText);
mPageSlider = (SeekBar)mButtonsView.findViewById(R.id.pageSlider);
mPageNumberView = (TextView)mButtonsView.findViewById(R.id.pageNumber);
mSearchButton = (ImageButton)mButtonsView.findViewById(R.id.searchButton);
mCancelButton = (ImageButton)mButtonsView.findViewById(R.id.cancel);
mOutlineButton = (ImageButton)mButtonsView.findViewById(R.id.outlineButton);
mTopBarSwitcher = (ViewSwitcher)mButtonsView.findViewById(R.id.switcher);
mSearchBack = (ImageButton)mButtonsView.findViewById(R.id.searchBack);
mSearchFwd = (ImageButton)mButtonsView.findViewById(R.id.searchForward);
mSearchText = (EditText)mButtonsView.findViewById(R.id.searchText);
mLinkButton = (ImageButton)mButtonsView.findViewById(R.id.linkButton);
mTopBarSwitcher.setVisibility(View.INVISIBLE);
mPageNumberView.setVisibility(View.INVISIBLE);
mPageSlider.setVisibility(View.INVISIBLE);
}
void showKeyboard() {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
imm.showSoftInput(mSearchText, 0);
}
void hideKeyboard() {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
imm.hideSoftInputFromWindow(mSearchText.getWindowToken(), 0);
}
void killSearch() {
if (mSearchTask != null) {
mSearchTask.cancel(true);
mSearchTask = null;
}
}
void search(int direction) {
killSearch();
final ProgressDialogX progressDialog = new ProgressDialogX(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setTitle(getString(R.string.searching_));
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
killSearch();
}
});
progressDialog.setMax(core.countPages());
mSearchTask = new AsyncTask<Integer,Integer,SearchTaskResult>() {
@Override
protected SearchTaskResult doInBackground(Integer... params) {
int index;
if (mSearchTaskResult == null)
index = mDocView.getDisplayedViewIndex();
else
index = mSearchTaskResult.pageNumber + params[0].intValue();
while (0 <= index && index < core.countPages() && !isCancelled()) {
publishProgress(index);
RectF searchHits[] = core.searchPage(index, mSearchText.getText().toString());
if (searchHits != null && searchHits.length > 0)
return new SearchTaskResult(index, searchHits);
index += params[0].intValue();
}
return null;
}
@Override
protected void onPostExecute(SearchTaskResult result) {
progressDialog.cancel();
if (result != null) {
// Ask the ReaderView to move to the resulting page
mDocView.setDisplayedViewIndex(result.pageNumber);
mSearchTaskResult = result;
// Make the ReaderView act on the change to mSearchTaskResult
// via overridden onChildSetup method.
mDocView.resetupChildren();
} else {
mAlertBuilder.setTitle(R.string.text_not_found);
AlertDialog alert = mAlertBuilder.create();
alert.setButton(AlertDialog.BUTTON_POSITIVE, "Dismiss",
(DialogInterface.OnClickListener)null);
alert.show();
}
}
@Override
protected void onCancelled() {
super.onCancelled();
progressDialog.cancel();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialog.setProgress(values[0].intValue());
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mHandler.postDelayed(new Runnable() {
public void run() {
if (!progressDialog.isCancelled())
progressDialog.show();
}
}, SEARCH_PROGRESS_DELAY);
}
};
mSearchTask.execute(new Integer(direction));
}
}
|
package io.jchat.android;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.net.Uri;
import android.text.TextUtils;
import android.widget.Toast;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import cn.jmessage.support.google.gson.JsonObject;
import cn.jpush.im.android.api.ChatRoomManager;
import cn.jpush.im.android.api.ContactManager;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.CreateGroupCallback;
import cn.jpush.im.android.api.callback.DownloadCompletionCallback;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.callback.GetBlacklistCallback;
import cn.jpush.im.android.api.callback.GetGroupIDListCallback;
import cn.jpush.im.android.api.callback.GetGroupInfoCallback;
import cn.jpush.im.android.api.callback.GetGroupInfoListCallback;
import cn.jpush.im.android.api.callback.GetNoDisurbListCallback;
import cn.jpush.im.android.api.callback.GetUserInfoCallback;
import cn.jpush.im.android.api.callback.GetUserInfoListCallback;
import cn.jpush.im.android.api.callback.IntegerCallback;
import cn.jpush.im.android.api.callback.ProgressUpdateCallback;
import cn.jpush.im.android.api.callback.RequestCallback;
import cn.jpush.im.android.api.content.CustomContent;
import cn.jpush.im.android.api.content.FileContent;
import cn.jpush.im.android.api.content.ImageContent;
import cn.jpush.im.android.api.content.LocationContent;
import cn.jpush.im.android.api.content.MessageContent;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.content.VoiceContent;
import cn.jpush.im.android.api.enums.ContentType;
import cn.jpush.im.android.api.event.ChatRoomMessageEvent;
import cn.jpush.im.android.api.event.ContactNotifyEvent;
import cn.jpush.im.android.api.event.ConversationRefreshEvent;
import cn.jpush.im.android.api.event.GroupApprovalEvent;
import cn.jpush.im.android.api.event.GroupApprovalRefuseEvent;
import cn.jpush.im.android.api.event.GroupApprovedNotificationEvent;
import cn.jpush.im.android.api.event.LoginStateChangeEvent;
import cn.jpush.im.android.api.event.MessageEvent;
import cn.jpush.im.android.api.event.MessageReceiptStatusChangeEvent;
import cn.jpush.im.android.api.event.MessageRetractEvent;
import cn.jpush.im.android.api.event.NotificationClickEvent;
import cn.jpush.im.android.api.event.OfflineMessageEvent;
import cn.jpush.im.android.api.model.ChatRoomInfo;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.GroupBasicInfo;
import cn.jpush.im.android.api.model.GroupInfo;
import cn.jpush.im.android.api.model.GroupMemberInfo;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.android.api.options.MessageSendingOptions;
import cn.jpush.im.api.BasicCallback;
import io.jchat.android.utils.EventUtils;
import io.jchat.android.utils.JMessageUtils;
import io.jchat.android.utils.Logger;
import io.jchat.android.utils.ResultUtils;
public class JMessageModule extends ReactContextBaseJavaModule {
private static final String TAG = "JMessageModule";
private static final String RECEIVE_MSG_EVENT = "JMessage.ReceiveMsgEvent";
private static final String RECEIPT_MSG_EVENT = "JMessage.ReceiptMsgEvent";
private static final String LOGIN_STATE_CHANGE_EVENT = "JMessage.LoginStateChanged";
private static final String CLICK_NOTIFICATION_EVENT = "JMessage.ClickMessageNotification"; // Android Only
private static final String SYNC_OFFLINE_EVENT = "JMessage.SyncOfflineMessage";
private static final String SYNC_ROAMING_EVENT = "JMessage.SyncRoamingMessage";
private static final String RETRACT_MESSAGE_EVENT = "JMessage.MessageRetract";
private static final String CONTACT_NOTIFY_EVENT = "JMessage.ContactNotify";
private static final String UPLOAD_PROGRESS_EVENT = "JMessage.UploadProgress";
private static final String RECEIVE_CHAT_ROOM_MSG_EVENT = "JMessage.ReceiveChatRoomMsgEvent";
private static final String RECEIVE_APPLY_JOIN_GROUP_APPROVAL_EVENT = "JMessage.ReceiveApplyJoinGroupApprovalEvent";
private static final String RECEIVE_GROUP_ADMIN_REJECT_EVENT = "JMessage.ReceiveGroupAdminRejectEvent";
private static final String RECEIVE_GROUP_ADMIN_APPROVAL_EVENT = "JMessage.ReceiveGroupAdminApprovalEvent";
private static final int ERR_CODE_PARAMETER = 1;
private static final int ERR_CODE_CONVERSATION = 2;
private static final int ERR_CODE_MESSAGE = 3;
private static final int ERR_CODE_FILE = 4;
private static final int ERR_CODE_EXCEPTION = -1;
private static final String ERR_MSG_PARAMETER = "Parameters error";
private static final String ERR_MSG_CONVERSATION = "Can't get the conversation";
private static final String ERR_MSG_MESSAGE = "No such message";
private Context mContext;
private JMessageUtils mJMessageUtils;
public JMessageModule(ReactApplicationContext reactContext, boolean shutdownToast) {
super(reactContext);
mJMessageUtils = new JMessageUtils(reactContext, shutdownToast);
mContext = reactContext;
}
@Override
public String getName() {
return "JMessageModule";
}
@Override
public boolean canOverrideExistingModule() {
return true;
}
@Override
public void initialize() {
super.initialize();
}
@ReactMethod
public void setup(ReadableMap map) {
try {
boolean isOpenMessageRoaming = map.getBoolean(Constant.IS_OPEN_MESSAGE_ROAMING);
JMessageClient.init(getReactApplicationContext(), isOpenMessageRoaming);
JMessageClient.registerEventReceiver(this);
} catch (Exception e) {
e.printStackTrace();
Logger.d(TAG, "Parameter invalid, please check again");
}
}
@ReactMethod
public void setDebugMode(ReadableMap map) {
try {
boolean enable = map.getBoolean(Constant.ENABLE);
JMessageClient.setDebugMode(enable);
Logger.SHUTDOWNLOG =!enable;
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
*
* @param callback callback
*/
@ReactMethod
public void isLogin(Callback callback) {
boolean flag = SharePreferenceManager.getCachedFixProfileFlag();
UserInfo myInfo = JMessageClient.getMyInfo();
WritableMap map = Arguments.createMap();
String result;
if (myInfo == null) {
if (SharePreferenceManager.getCachedUsername() != null) {
result = "re-login";
map.putString("username", SharePreferenceManager.getCachedUsername());
} else {
result = "login";
}
} else if (TextUtils.isEmpty(JMessageClient.getMyInfo().getNickname()) && flag) {
result = "fillInfo";
} else {
result = "mainActivity";
}
map.putString("result", result);
callback.invoke(map);
}
@ReactMethod
public void login(ReadableMap map, final Callback success, final Callback fail) {
mContext = getCurrentActivity();
String username = map.getString(Constant.USERNAME);
String password = map.getString(Constant.PASSWORD);
Logger.i(TAG, "username: " + username + " is logging in");
JMessageClient.login(username, password, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
}
@ReactMethod
public void userRegister(ReadableMap map, final Callback success, final Callback fail) {
mContext = getCurrentActivity();
String username = map.getString(Constant.USERNAME);
String password = map.getString(Constant.PASSWORD);
Logger.i(TAG, "username: " + username + " password: " + password);
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
Toast.makeText(mContext, "Username or Password null", Toast.LENGTH_SHORT).show();
} else {
JMessageClient.register(username, password, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
}
}
@ReactMethod
public void logout() {
JMessageClient.logout();
}
@ReactMethod
public void getMyInfo(Callback callback) {
UserInfo myInfo = JMessageClient.getMyInfo();
callback.invoke(ResultUtils.toJSObject(myInfo));
}
@ReactMethod
public void getUserInfo(ReadableMap map, final Callback success, final Callback fail) {
String username = map.getString(Constant.USERNAME);
String appKey = map.hasKey(Constant.APP_KEY) ? map.getString(Constant.APP_KEY) : "";
JMessageClient.getUserInfo(username, appKey, new GetUserInfoCallback() {
@Override
public void gotResult(int i, String s, UserInfo userInfo) {
mJMessageUtils.handleCallbackWithObject(i, s, success, fail, ResultUtils.toJSObject(userInfo));
}
});
}
@ReactMethod
public void updateMyPassword(ReadableMap map, final Callback success, final Callback fail) {
String oldPwd = map.getString(Constant.OLD_PWD);
String newPwd = map.getString(Constant.NEW_PWD);
JMessageClient.updateUserPassword(oldPwd, newPwd, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
}
@ReactMethod
public void updateMyAvatar(ReadableMap map, final Callback success, final Callback fail) {
try {
String path = map.getString("imgPath");
File file = new File(path);
if (file.exists() && file.isFile()) {
JMessageClient.updateUserAvatar(file, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
@ReactMethod
public void updateMyInfo(ReadableMap map, final Callback success, final Callback fail) {
UserInfo myInfo = JMessageClient.getMyInfo();
if (map.hasKey(Constant.NICKNAME)) {
myInfo.setNickname(map.getString(Constant.NICKNAME));
}
if (map.hasKey(Constant.BIRTHDAY)) {
myInfo.setBirthday((long) map.getDouble(Constant.BIRTHDAY));
} else {
myInfo.setBirthday(0);
}
if (map.hasKey(Constant.SIGNATURE)) {
myInfo.setSignature(map.getString(Constant.SIGNATURE));
}
if (map.hasKey(Constant.GENDER)) {
if (map.getString(Constant.GENDER).equals("male")) {
myInfo.setGender(UserInfo.Gender.male);
} else if (map.getString(Constant.GENDER).equals("female")) {
myInfo.setGender(UserInfo.Gender.female);
} else {
myInfo.setGender(UserInfo.Gender.unknown);
}
}
if (map.hasKey(Constant.REGION)) {
myInfo.setRegion(map.getString(Constant.REGION));
}
if (map.hasKey(Constant.ADDRESS)) {
myInfo.setAddress(map.getString(Constant.ADDRESS));
}
if (map.hasKey(Constant.EXTRAS)) {
ReadableMap extras = map.getMap(Constant.EXTRAS);
ReadableMapKeySetIterator iterator = extras.keySetIterator();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
myInfo.setUserExtras(key, extras.getString(key));
}
}
JMessageClient.updateMyInfo(UserInfo.Field.all, myInfo, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
}
@ReactMethod
public void createSendMessage(ReadableMap map, Callback callback) {
try {
MessageContent content;
Conversation conversation = mJMessageUtils.getConversation(map);
String type = map.getString(Constant.MESSAGE_TYPE);
switch (type) {
case Constant.TEXT:
content = new TextContent(map.getString(Constant.TEXT));
break;
case Constant.IMAGE:
String path = map.getString(Constant.PATH);
String suffix = path.substring(path.lastIndexOf(".") + 1);
content = new ImageContent(new File(path), suffix);
break;
case Constant.VOICE:
path = map.getString(Constant.PATH);
File file = new File(path);
MediaPlayer mediaPlayer = MediaPlayer.create(mContext, Uri.parse(path));
int duration = mediaPlayer.getDuration() / 1000; // Millisecond to second.
content = new VoiceContent(file, duration);
mediaPlayer.release();
break;
case Constant.FILE:
path = map.getString(Constant.PATH);
file = new File(path);
content = new FileContent(file);
break;
case Constant.LOCATION:
double latitude = map.getDouble(Constant.LATITUDE);
double longitude = map.getDouble(Constant.LONGITUDE);
int scale = map.getInt(Constant.SCALE);
String address = map.getString(Constant.ADDRESS);
content = new LocationContent(latitude, longitude, scale, address);
break;
default:
content = new CustomContent();
}
if (map.hasKey(Constant.EXTRAS)) {
content.setExtras(ResultUtils.fromMap(map.getMap(Constant.EXTRAS)));
}
if (type.equals(Constant.CUSTOM)) {
CustomContent customContent = new CustomContent();
customContent.setAllValues(ResultUtils.fromMap(map.getMap(Constant.CUSTOM_OBJECT)));
Message message = conversation.createSendMessage(customContent);
callback.invoke(ResultUtils.toJSObject(message));
} else {
Message message = conversation.createSendMessage(content);
callback.invoke(ResultUtils.toJSObject(message));
}
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(callback, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void sendMessage(ReadableMap map, final Callback success, final Callback fail) {
try {
Conversation conversation = mJMessageUtils.getConversation(map);
final Message message = conversation.getMessage(Integer.parseInt(map.getString(Constant.ID)));
if (map.hasKey(Constant.SENDING_OPTIONS)) {
MessageSendingOptions options = new MessageSendingOptions();
ReadableMap optionMap = map.getMap(Constant.SENDING_OPTIONS);
options.setShowNotification(optionMap.getBoolean(Constant.IS_SHOW_NOTIFICATION));
options.setRetainOffline(optionMap.getBoolean(Constant.IS_RETAIN_OFFLINE));
if (optionMap.hasKey(Constant.IS_CUSTOM_NOTIFICATION_ENABLED)) {
options.setCustomNotificationEnabled(optionMap.getBoolean(Constant.IS_CUSTOM_NOTIFICATION_ENABLED));
}
if (optionMap.hasKey(Constant.NOTIFICATION_TITLE)) {
options.setNotificationTitle(optionMap.getString(Constant.NOTIFICATION_TITLE));
}
if (optionMap.hasKey(Constant.NOTIFICATION_TEXT)) {
options.setNotificationText(optionMap.getString(Constant.NOTIFICATION_TEXT));
}
if(optionMap.hasKey(Constant.NEED_READ_RECEIPT)){
options.setNeedReadReceipt(optionMap.getBoolean(Constant.NEED_READ_RECEIPT));
}
JMessageClient.sendMessage(message, options);
} else {
JMessageClient.sendMessage(message);
}
if (message.getContentType() == ContentType.image || message.getContentType() == ContentType.file) {
message.setOnContentUploadProgressCallback(new ProgressUpdateCallback() {
@Override
public void onProgressUpdate(double v) {
WritableMap result = Arguments.createMap();
result.putInt(Constant.MESSAGE_ID, message.getId());
result.putDouble(Constant.PROGRESS, v);
getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(UPLOAD_PROGRESS_EVENT, result);
}
});
}
message.setOnSendCompleteCallback(new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallbackWithObject(status, desc, success, fail,
ResultUtils.toJSObject(message));
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void sendTextMessage(ReadableMap map, final Callback success, final Callback fail) {
TextContent content = new TextContent(map.getString(Constant.TEXT));
mJMessageUtils.sendMessage(map, content, success, fail);
}
@ReactMethod
public void sendImageMessage(ReadableMap map, Callback success, Callback fail) {
String path = map.getString(Constant.PATH);
try {
String suffix = path.substring(path.lastIndexOf(".") + 1);
ImageContent content = new ImageContent(new File(path), suffix);
mJMessageUtils.sendMessage(map, content, success, fail);
} catch (FileNotFoundException e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_FILE, "No such file");
}
}
@ReactMethod
public void sendVoiceMessage(ReadableMap map, Callback success, Callback fail) {
String path = map.getString(Constant.PATH);
try {
File file = new File(path);
MediaPlayer mediaPlayer = MediaPlayer.create(mContext, Uri.parse(path));
int duration = mediaPlayer.getDuration() / 1000; // Millisecond to second.
VoiceContent content = new VoiceContent(file, duration);
mediaPlayer.release();
mJMessageUtils.sendMessage(map, content, success, fail);
} catch (FileNotFoundException e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_FILE, "No such file");
}
}
@ReactMethod
public void sendCustomMessage(ReadableMap map, Callback success, Callback fail) {
CustomContent content = new CustomContent();
content.setAllValues(ResultUtils.fromMap(map.getMap(Constant.CUSTOM_OBJECT)));
mJMessageUtils.sendMessage(map, content, success, fail);
}
@ReactMethod
public void sendLocationMessage(ReadableMap map, Callback success, Callback fail) {
try {
double latitude = map.getDouble(Constant.LATITUDE);
double longitude = map.getDouble(Constant.LONGITUDE);
int scale = map.getInt(Constant.SCALE);
String address = map.getString(Constant.ADDRESS);
LocationContent content = new LocationContent(latitude, longitude, scale, address);
mJMessageUtils.sendMessage(map, content, success, fail);
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void sendFileMessage(ReadableMap map, Callback success, Callback fail) {
try {
String path = map.getString(Constant.PATH);
FileContent content = new FileContent(new File(path));
mJMessageUtils.sendMessage(map, content, success, fail);
} catch (FileNotFoundException e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_FILE, "No such file");
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void retractMessage(ReadableMap map, final Callback success, final Callback fail) {
Conversation conversation = mJMessageUtils.getConversation(map);
if (null == conversation) {
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
return;
}
try {
int msgId = Integer.parseInt(map.getString(Constant.MESSAGE_ID));
Message msg = conversation.getMessage(msgId);
conversation.retractMessage(msg, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_MESSAGE);
}
}
@ReactMethod
public void getHistoryMessages(ReadableMap map, Callback success, Callback fail) {
Conversation conversation = mJMessageUtils.getConversation(map);
if (null == conversation) {
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
return;
}
try {
int from = map.getInt(Constant.FROM);
int limit = map.getInt(Constant.LIMIT);
List<Message> messages = conversation.getMessagesFromNewest(from, limit);
// Is descend false2.3.5
boolean isDescend = false;
if (map.hasKey(Constant.IS_DESCEND)) {
isDescend = map.getBoolean(Constant.IS_DESCEND);
}
if (!isDescend) {
Collections.reverse(messages);
}
success.invoke(ResultUtils.toJSArray(messages));
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, "Unexpected error");
}
}
@ReactMethod
public void sendInvitationRequest(ReadableMap map, final Callback success, final Callback fail) {
try {
String username = map.getString(Constant.USERNAME);
String appKey = map.hasKey(Constant.APP_KEY) ? map.getString(Constant.APP_KEY) : "";
String reason = map.getString(Constant.REASON);
ContactManager.sendInvitationRequest(username, appKey, reason, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void acceptInvitation(ReadableMap map, final Callback success, final Callback fail) {
try {
String username = map.getString(Constant.USERNAME);
String appKey = map.hasKey(Constant.APP_KEY) ? map.getString(Constant.APP_KEY) : "";
ContactManager.acceptInvitation(username, appKey, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void declineInvitation(ReadableMap map, final Callback success, final Callback fail) {
try {
String username = map.getString(Constant.USERNAME);
String appKey = map.hasKey(Constant.APP_KEY) ? map.getString(Constant.APP_KEY) : "";
String reason = map.getString(Constant.REASON);
ContactManager.declineInvitation(username, appKey, reason, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void removeFromFriendList(ReadableMap map, final Callback success, final Callback fail) {
try {
String username = map.getString(Constant.USERNAME);
String appKey = map.getString(Constant.APP_KEY);
JMessageClient.getUserInfo(username, appKey, new GetUserInfoCallback() {
@Override
public void gotResult(int status, String desc, UserInfo userInfo) {
if (status == 0) {
userInfo.removeFromFriendList(new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void updateFriendNoteName(ReadableMap map, final Callback success, final Callback fail) {
try {
String username = map.getString(Constant.USERNAME);
String appKey = map.getString(Constant.APP_KEY);
final String noteName = map.getString(Constant.NOTE_NAME);
JMessageClient.getUserInfo(username, appKey, new GetUserInfoCallback() {
@Override
public void gotResult(int status, String desc, UserInfo userInfo) {
if (status == 0) {
userInfo.updateNoteName(noteName, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void updateFriendNoteText(ReadableMap map, final Callback success, final Callback fail) {
try {
String username = map.getString(Constant.USERNAME);
String appKey = map.getString(Constant.APP_KEY);
final String noteText = map.getString(Constant.NOTE_TEXT);
JMessageClient.getUserInfo(username, appKey, new GetUserInfoCallback() {
@Override
public void gotResult(int status, String desc, UserInfo userInfo) {
if (status == 0) {
userInfo.updateNoteText(noteText, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void getFriends(final Callback success, final Callback fail) {
ContactManager.getFriendList(new GetUserInfoListCallback() {
@Override
public void gotResult(int status, String desc, List<UserInfo> list) {
mJMessageUtils.handleCallbackWithArray(status, desc, success, fail, ResultUtils.toJSArray(list));
}
});
}
@ReactMethod
public void createGroup(ReadableMap map, final Callback success, final Callback fail) {
try {
String name = map.getString(Constant.NAME);
String desc = map.getString(Constant.DESC);
String groupType = map.getString(Constant.GROUP_TYPE);
if (groupType.equals("private")) {
JMessageClient.createGroup(name, desc, new CreateGroupCallback() {
@Override
public void gotResult(int status, String desc, long groupId) {
mJMessageUtils.handleCallbackWithValue(status, desc, success, fail, String.valueOf(groupId));
}
});
} else if (groupType.equals("public")) {
JMessageClient.createPublicGroup(name, desc, new CreateGroupCallback() {
@Override
public void gotResult(int status, String desc, long groupId) {
mJMessageUtils.handleCallbackWithValue(status, desc, success, fail, String.valueOf(groupId));
}
});
} else {
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER + " : " + groupType);
}
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void dissolveGroup(final ReadableMap map, final Callback success, final Callback fail) {
try {
long groupId = Long.parseLong(map.getString(Constant.GROUP_ID));
JMessageClient.adminDissolveGroup(groupId, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void getGroupIds(final Callback success, final Callback fail) {
JMessageClient.getGroupIDList(new GetGroupIDListCallback() {
@Override
public void gotResult(int status, String desc, List<Long> list) {
mJMessageUtils.handleCallbackWithArray(status, desc, success, fail, ResultUtils.toJSArray(list));
}
});
}
@ReactMethod
public void getGroupInfo(ReadableMap map, final Callback success, final Callback fail) {
try {
long groupId = Long.parseLong(map.getString(Constant.ID));
JMessageClient.getGroupInfo(groupId, new GetGroupInfoCallback() {
@Override
public void gotResult(int status, String desc, GroupInfo groupInfo) {
mJMessageUtils.handleCallbackWithObject(status, desc, success, fail,
ResultUtils.toJSObject(groupInfo));
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void updateGroupInfo(ReadableMap map, final Callback success, final Callback fail) {
try {
final long groupId = Long.parseLong(map.getString(Constant.ID));
String newName = map.hasKey(Constant.NEW_NAME) ? map.getString(Constant.NEW_NAME) : "";
final String newDesc = map.hasKey(Constant.NEW_DESC) ? map.getString(Constant.NEW_DESC) : "";
if (!TextUtils.isEmpty(newName) && !TextUtils.isEmpty(newDesc)) {
JMessageClient.updateGroupName(groupId, newName, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
if (status == 0) {
JMessageClient.updateGroupDescription(groupId, newDesc, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
return;
}
if (!TextUtils.isEmpty(newName) && TextUtils.isEmpty(newDesc)) {
JMessageClient.updateGroupName(groupId, newName, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
return;
}
if (TextUtils.isEmpty(newName) && !TextUtils.isEmpty(newDesc)) {
JMessageClient.updateGroupDescription(groupId, newDesc, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
}
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void addGroupMembers(ReadableMap map, final Callback success, final Callback fail) {
try {
long groupId = Long.parseLong(map.getString(Constant.ID));
String appKey = map.hasKey(Constant.APP_KEY) ? map.getString(Constant.APP_KEY) : "";
ReadableArray array = map.getArray(Constant.USERNAME_ARRAY);
List<String> usernameList = new ArrayList<String>();
for (int i = 0; i < array.size(); i++) {
usernameList.add(array.getString(i));
}
JMessageClient.addGroupMembers(groupId, appKey, usernameList, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void removeGroupMembers(ReadableMap map, final Callback success, final Callback fail) {
try {
long groupId = Long.parseLong(map.getString(Constant.ID));
String appKey = map.hasKey(Constant.APP_KEY) ? map.getString(Constant.APP_KEY) : "";
ReadableArray array = map.getArray(Constant.USERNAME_ARRAY);
List<String> usernameList = new ArrayList<String>();
for (int i = 0; i < array.size(); i++) {
usernameList.add(array.getString(i));
}
JMessageClient.removeGroupMembers(groupId, appKey, usernameList, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void exitGroup(ReadableMap map, final Callback success, final Callback fail) {
try {
long groupId = Long.parseLong(map.getString(Constant.ID));
JMessageClient.exitGroup(groupId, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void getGroupMembers(ReadableMap map, final Callback success, final Callback fail) {
try {
long groupId = Long.parseLong(map.getString(Constant.ID));
JMessageClient.getGroupMembers(groupId, new RequestCallback<List<GroupMemberInfo>>() {
@Override
public void gotResult(int status, String desc, List<GroupMemberInfo> list) {
mJMessageUtils.handleCallbackWithArray(status, desc, success, fail, ResultUtils.toJSArray(list));
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void addUsersToBlacklist(ReadableMap map, final Callback success, final Callback fail) {
try {
String appKey = map.hasKey(Constant.APP_KEY) ? map.getString(Constant.APP_KEY) : "";
ReadableArray array = map.getArray(Constant.USERNAME_ARRAY);
List<String> usernameList = new ArrayList<String>();
for (int i = 0; i < array.size(); i++) {
usernameList.add(array.getString(i));
}
JMessageClient.addUsersToBlacklist(usernameList, appKey, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void removeUsersFromBlacklist(ReadableMap map, final Callback success, final Callback fail) {
try {
String appKey = map.hasKey(Constant.APP_KEY) ? map.getString(Constant.APP_KEY) : "";
ReadableArray array = map.getArray(Constant.USERNAME_ARRAY);
List<String> usernameList = new ArrayList<String>();
for (int i = 0; i < array.size(); i++) {
usernameList.add(array.getString(i));
}
JMessageClient.delUsersFromBlacklist(usernameList, appKey, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void getBlacklist(final Callback success, final Callback fail) {
try {
JMessageClient.getBlacklist(new GetBlacklistCallback() {
@Override
public void gotResult(int status, String desc, List<UserInfo> list) {
mJMessageUtils.handleCallbackWithArray(status, desc, success, fail, ResultUtils.toJSArray(list));
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void setNoDisturb(ReadableMap map, final Callback success, final Callback fail) {
try {
String type = map.getString(Constant.TYPE);
final int isNoDisturb = map.getBoolean(Constant.IS_NO_DISTURB) ? 1 : 0;
if (type.equals(Constant.TYPE_SINGLE)) {
String username = map.getString(Constant.USERNAME);
String appKey = map.hasKey(Constant.APP_KEY) ? map.getString(Constant.APP_KEY) : "";
JMessageClient.getUserInfo(username, appKey, new GetUserInfoCallback() {
@Override
public void gotResult(int status, String desc, UserInfo userInfo) {
if (status == 0) {
userInfo.setNoDisturb(isNoDisturb, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} else {
long groupId = Long.parseLong(map.getString(Constant.ID));
JMessageClient.getGroupInfo(groupId, new GetGroupInfoCallback() {
@Override
public void gotResult(int status, String desc, GroupInfo groupInfo) {
if (status == 0) {
groupInfo.setNoDisturb(isNoDisturb, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
}
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void getNoDisturbList(final Callback success, final Callback fail) {
JMessageClient.getNoDisturblist(new GetNoDisurbListCallback() {
@Override
public void gotResult(int status, String desc, List<UserInfo> userInfos, List<GroupInfo> groupInfos) {
if (status == 0) {
WritableMap map = Arguments.createMap();
map.putArray(Constant.USER_INFO_ARRAY, ResultUtils.toJSArray(userInfos));
map.putArray(Constant.GROUP_INFO_ARRAY, ResultUtils.toJSArray(groupInfos));
mJMessageUtils.handleCallbackWithObject(status, desc, success, fail, map);
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
}
@ReactMethod
public void setNoDisturbGlobal(ReadableMap map, final Callback success, final Callback fail) {
try {
final int isNoDisturb = map.getBoolean(Constant.IS_NO_DISTURB) ? 1 : 0;
JMessageClient.setNoDisturbGlobal(isNoDisturb, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void isNoDisturbGlobal(final Callback success, final Callback fail) {
JMessageClient.getNoDisturbGlobal(new IntegerCallback() {
@Override
public void gotResult(int status, String desc, Integer integer) {
WritableMap map = Arguments.createMap();
map.putBoolean(Constant.IS_NO_DISTURB, integer == 1);
mJMessageUtils.handleCallbackWithObject(status, desc, success, fail, map);
}
});
}
@ReactMethod
public void downloadOriginalUserAvatar(ReadableMap map, final Callback success, final Callback fail) {
final String username = map.getString(Constant.USERNAME);
final String appKey = map.hasKey(Constant.APP_KEY) ? map.getString(Constant.APP_KEY) : "";
JMessageClient.getUserInfo(username, appKey, new GetUserInfoCallback() {
@Override
public void gotResult(int status, String desc, UserInfo userInfo) {
if (status == 0) {
userInfo.getBigAvatarBitmap(new GetAvatarBitmapCallback() {
@Override
public void gotResult(int status, String desc, Bitmap bitmap) {
if (status == 0) {
String packageName = mContext.getPackageName();
String fileName = username + appKey + "original";
String path = mJMessageUtils.storeImage(bitmap, fileName, packageName);
WritableMap result = Arguments.createMap();
result.putString(Constant.FILE_PATH, path);
mJMessageUtils.handleCallbackWithObject(status, desc, success, fail, result);
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
}
@ReactMethod
public void downloadOriginalImage(ReadableMap map, final Callback success, final Callback fail) {
try {
Conversation conversation = mJMessageUtils.getConversation(map);
if (null == conversation) {
mJMessageUtils.handleError(fail, ERR_CODE_CONVERSATION, ERR_MSG_CONVERSATION);
return;
}
final String messageId = map.getString(Constant.MESSAGE_ID);
Message msg = conversation.getMessage(Integer.parseInt(messageId));
if (null == msg) {
mJMessageUtils.handleError(fail, ERR_CODE_MESSAGE, ERR_MSG_MESSAGE);
return;
}
if (msg.getContentType() != ContentType.image) {
mJMessageUtils.handleError(fail, ERR_CODE_MESSAGE, "Wrong message type");
return;
}
ImageContent content = (ImageContent) msg.getContent();
content.downloadOriginImage(msg, new DownloadCompletionCallback() {
@Override
public void onComplete(int status, String desc, File file) {
if (status == 0) {
WritableMap result = Arguments.createMap();
result.putString(Constant.MESSAGE_ID, messageId);
result.putString(Constant.FILE_PATH, file.getAbsolutePath());
mJMessageUtils.handleCallbackWithObject(status, desc, success, fail, result);
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void downloadThumbImage(ReadableMap map, final Callback success, final Callback fail) {
try {
Conversation conversation = mJMessageUtils.getConversation(map);
if (null == conversation) {
mJMessageUtils.handleError(fail, ERR_CODE_CONVERSATION, ERR_MSG_CONVERSATION);
return;
}
final String messageId = map.getString(Constant.MESSAGE_ID);
Message msg = conversation.getMessage(Integer.parseInt(messageId));
if (null == msg) {
mJMessageUtils.handleError(fail, ERR_CODE_MESSAGE, ERR_MSG_MESSAGE);
return;
}
if (msg.getContentType() != ContentType.image) {
mJMessageUtils.handleError(fail, ERR_CODE_MESSAGE, "Wrong message type");
return;
}
ImageContent content = (ImageContent) msg.getContent();
content.downloadThumbnailImage(msg, new DownloadCompletionCallback() {
@Override
public void onComplete(int status, String desc, File file) {
if (status == 0) {
WritableMap result = Arguments.createMap();
result.putString(Constant.MESSAGE_ID, messageId);
result.putString(Constant.FILE_PATH, file.getAbsolutePath());
mJMessageUtils.handleCallbackWithObject(status, desc, success, fail, result);
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void downloadVoiceFile(ReadableMap map, final Callback success, final Callback fail) {
try {
Conversation conversation = mJMessageUtils.getConversation(map);
if (null == conversation) {
mJMessageUtils.handleError(fail, ERR_CODE_CONVERSATION, ERR_MSG_CONVERSATION);
return;
}
final String messageId = map.getString(Constant.MESSAGE_ID);
Message msg = conversation.getMessage(Integer.parseInt(messageId));
if (null == msg) {
mJMessageUtils.handleError(fail, ERR_CODE_MESSAGE, ERR_MSG_MESSAGE);
return;
}
if (msg.getContentType() != ContentType.voice) {
mJMessageUtils.handleError(fail, ERR_CODE_MESSAGE, "Wrong message type");
return;
}
VoiceContent content = (VoiceContent) msg.getContent();
content.downloadVoiceFile(msg, new DownloadCompletionCallback() {
@Override
public void onComplete(int status, String desc, File file) {
if (status == 0) {
WritableMap result = Arguments.createMap();
result.putString(Constant.MESSAGE_ID, messageId);
result.putString(Constant.FILE_PATH, file.getAbsolutePath());
mJMessageUtils.handleCallbackWithObject(status, desc, success, fail, result);
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void downloadFile(ReadableMap map, final Callback success, final Callback fail) {
try {
Conversation conversation = mJMessageUtils.getConversation(map);
if (null == conversation) {
mJMessageUtils.handleError(fail, ERR_CODE_CONVERSATION, ERR_MSG_CONVERSATION);
return;
}
final String messageId = map.getString(Constant.MESSAGE_ID);
Message msg = conversation.getMessage(Integer.parseInt(messageId));
if (null == msg) {
mJMessageUtils.handleError(fail, ERR_CODE_MESSAGE, ERR_MSG_MESSAGE);
return;
}
FileContent content = (FileContent) msg.getContent();
content.downloadFile(msg, new DownloadCompletionCallback() {
@Override
public void onComplete(int status, String desc, File file) {
if (status == 0) {
WritableMap result = Arguments.createMap();
result.putString(Constant.MESSAGE_ID, messageId);
result.putString(Constant.FILE_PATH, file.getAbsolutePath());
mJMessageUtils.handleCallbackWithObject(status, desc, success, fail, result);
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void createConversation(ReadableMap map, final Callback success, final Callback fail) {
try {
Conversation conversation = mJMessageUtils.getConversation(map);
if (null != conversation) {
mJMessageUtils.handleCallbackWithObject(0, "", success, fail, ResultUtils.toJSObject(conversation));
} else {
mJMessageUtils.handleError(fail, ERR_CODE_CONVERSATION, ERR_MSG_CONVERSATION);
}
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void deleteConversation(ReadableMap map, final Callback success, final Callback fail) {
try {
String type = map.getString(Constant.TYPE);
if (type.equals(Constant.TYPE_SINGLE)) {
String username = map.getString(Constant.USERNAME);
String appKey = map.hasKey(Constant.APP_KEY) ? map.getString(Constant.APP_KEY) : "";
JMessageClient.deleteSingleConversation(username, appKey);
} else if (type.equals(Constant.TYPE_GROUP)) {
long groupId = Long.parseLong(map.getString(Constant.GROUP_ID));
JMessageClient.deleteGroupConversation(groupId);
} else {
String roomId = map.getString(Constant.ROOM_ID);
JMessageClient.deleteChatRoomConversation(Long.parseLong(roomId));
}
mJMessageUtils.handleCallback(0, "", success, fail);
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void enterConversation(ReadableMap map, final Callback success, final Callback fail) {
try {
String type = map.getString(Constant.TYPE);
if (type.equals(Constant.TYPE_SINGLE)) {
String username = map.getString(Constant.USERNAME);
String appKey = map.hasKey(Constant.APP_KEY) ? map.getString(Constant.APP_KEY) : "";
JMessageClient.enterSingleConversation(username, appKey);
} else if (type.equals(Constant.TYPE_GROUP)) {
long groupId = Long.parseLong(map.getString(Constant.GROUP_ID));
JMessageClient.enterGroupConversation(groupId);
}
mJMessageUtils.handleCallback(0, "", success, fail);
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void exitConversation() {
JMessageClient.exitConversation();
}
@ReactMethod
public void getConversation(ReadableMap map, final Callback success, final Callback fail) {
try {
Conversation conversation = mJMessageUtils.getConversation(map);
if (null != conversation) {
mJMessageUtils.handleCallbackWithObject(0, "", success, fail, ResultUtils.toJSObject(conversation));
} else {
mJMessageUtils.handleError(fail, ERR_CODE_CONVERSATION, ERR_MSG_CONVERSATION);
}
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void getConversations(Callback success, Callback fail) {
List<Conversation> list = JMessageClient.getConversationList();
success.invoke(ResultUtils.toJSArray(list));
}
@ReactMethod
public void resetUnreadMessageCount(ReadableMap map, Callback success, Callback fail) {
try {
Conversation conversation = mJMessageUtils.getConversation(map);
if (null != conversation) {
conversation.resetUnreadCount();
success.invoke(0);
} else {
mJMessageUtils.handleError(fail, ERR_CODE_CONVERSATION, ERR_MSG_CONVERSATION);
}
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void downloadThumbUserAvatar(ReadableMap map, final Callback success, final Callback fail) {
try {
final String username = map.getString(Constant.USERNAME);
final String appKey = map.hasKey(Constant.APP_KEY) ? map.getString(Constant.APP_KEY) : "";
JMessageClient.getUserInfo(username, appKey, new GetUserInfoCallback() {
@Override
public void gotResult(int status, String desc, UserInfo userInfo) {
if (status == 0) {
if (userInfo.getAvatar() != null) {
File file = userInfo.getAvatarFile();
WritableMap result = Arguments.createMap();
result.putString(Constant.USERNAME, username);
result.putString(Constant.APP_KEY, appKey);
result.putString(Constant.FILE_PATH, file.getAbsolutePath());
mJMessageUtils.handleCallbackWithObject(status, desc, success, fail, result);
}
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void isGroupBlocked(ReadableMap map, final Callback success, final Callback fail) {
try {
String groupId = map.getString(Constant.GROUP_ID);
JMessageClient.getGroupInfo(Long.parseLong(groupId), new GetGroupInfoCallback() {
@Override
public void gotResult(int status, String desc, GroupInfo groupInfo) {
if (status == 0) {
boolean isBlocked = groupInfo.isGroupBlocked() == 1;
WritableMap result = Arguments.createMap();
result.putBoolean(Constant.IS_BLOCKED, isBlocked);
mJMessageUtils.handleCallbackWithObject(status, desc, success, fail, result);
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void getBlockedGroupList(final Callback success, final Callback fail) {
JMessageClient.getBlockedGroupsList(new GetGroupInfoListCallback() {
@Override
public void gotResult(int status, String desc, List<GroupInfo> list) {
if (status == 0) {
WritableArray array = Arguments.createArray();
for (GroupInfo groupInfo : list) {
array.pushMap(ResultUtils.toJSObject(groupInfo));
}
mJMessageUtils.handleCallbackWithArray(status, desc, success, fail, array);
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
}
@ReactMethod
public void updateGroupAvatar(final ReadableMap map, final Callback success, final Callback fail) {
try {
String groupId = map.getString(Constant.GROUP_ID);
JMessageClient.getGroupInfo(Long.parseLong(groupId), new GetGroupInfoCallback() {
@Override
public void gotResult(int status, String desc, GroupInfo groupInfo) {
if (status == 0) {
String path = map.getString("imgPath");
String format = path.substring(path.lastIndexOf(".") + 1);
File file = new File(path);
if (file.exists()) {
groupInfo.updateAvatar(file, format, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} else {
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, "File is not exist!");
}
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void downloadThumbGroupAvatar(ReadableMap map, final Callback success, final Callback fail) {
try {
final String groupId = map.getString(Constant.GROUP_ID);
JMessageClient.getGroupInfo(Long.parseLong(groupId), new GetGroupInfoCallback() {
@Override
public void gotResult(int status, String desc, final GroupInfo groupInfo) {
if (status == 0) {
if (groupInfo.getAvatar() != null) {
File file = groupInfo.getAvatarFile();
final WritableMap result = Arguments.createMap();
result.putString(Constant.ID, groupId);
if (file.exists()) {
result.putString(Constant.FILE_PATH, file.getAbsolutePath());
mJMessageUtils.handleCallbackWithObject(status, desc, success, fail, result);
} else {
groupInfo.getAvatarBitmap(new GetAvatarBitmapCallback() {
@Override
public void gotResult(int status, String desc, Bitmap bitmap) {
if (status == 0) {
String fileName = groupId + groupInfo.getGroupName();
String path = mJMessageUtils.storeImage(bitmap, fileName,
mContext.getPackageName());
result.putString(Constant.FILE_PATH, path);
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
}
}
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void downloadOriginalGroupAvatar(ReadableMap map, final Callback success, final Callback fail) {
try {
final String groupId = map.getString(Constant.GROUP_ID);
JMessageClient.getGroupInfo(Long.parseLong(groupId), new GetGroupInfoCallback() {
@Override
public void gotResult(int status, String desc, final GroupInfo groupInfo) {
if (status == 0) {
if (groupInfo.getAvatar() != null) {
File file = groupInfo.getBigAvatarFile();
final WritableMap result = Arguments.createMap();
result.putString(Constant.ID, groupId);
if (file.exists()) {
result.putString(Constant.FILE_PATH, file.getAbsolutePath());
mJMessageUtils.handleCallbackWithObject(status, desc, success, fail, result);
} else {
groupInfo.getBigAvatarBitmap(new GetAvatarBitmapCallback() {
@Override
public void gotResult(int status, String desc, Bitmap bitmap) {
if (status == 0) {
String fileName = groupId + groupInfo.getGroupName() + "original";
String path = mJMessageUtils.storeImage(bitmap, fileName,
mContext.getPackageName());
result.putString(Constant.FILE_PATH, path);
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
}
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void setConversationExtras(ReadableMap map, Callback success, Callback fail) {
try {
Conversation conversation = mJMessageUtils.getConversation(map);
ReadableMap extraMap = map.getMap(Constant.EXTRAS);
ReadableMapKeySetIterator iterator = extraMap.keySetIterator();
JsonObject jsonObject = new JsonObject();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
jsonObject.addProperty(key, extraMap.getString(key));
}
conversation.updateConversationExtra(jsonObject.toString());
Logger.i("JMessageModule", "extra : " + jsonObject.toString());
WritableMap result = ResultUtils.toJSObject(conversation);
mJMessageUtils.handleCallbackWithObject(0, "Set extra succeed", success, fail, result);
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void forwardMessage(ReadableMap map, final Callback success, final Callback fail) {
try {
Conversation conversation = mJMessageUtils.getConversation(map);
if (conversation != null) {
Message message = conversation.getMessage(Integer.parseInt(map.getString(Constant.ID)));
MessageSendingOptions options = null;
if (map.hasKey(Constant.SENDING_OPTIONS)) {
options = new MessageSendingOptions();
ReadableMap optionMap = map.getMap(Constant.SENDING_OPTIONS);
options.setShowNotification(optionMap.getBoolean(Constant.IS_SHOW_NOTIFICATION));
options.setRetainOffline(optionMap.getBoolean(Constant.IS_RETAIN_OFFLINE));
if (optionMap.hasKey(Constant.IS_CUSTOM_NOTIFICATION_ENABLED)) {
options.setCustomNotificationEnabled(optionMap.getBoolean(Constant.IS_CUSTOM_NOTIFICATION_ENABLED));
}
if (optionMap.hasKey(Constant.NOTIFICATION_TITLE)) {
options.setNotificationTitle(optionMap.getString(Constant.NOTIFICATION_TITLE));
}
if (optionMap.hasKey(Constant.NOTIFICATION_TEXT)) {
options.setNotificationText(optionMap.getString(Constant.NOTIFICATION_TEXT));
}
if(optionMap.hasKey(Constant.NEED_READ_RECEIPT)){
options.setNeedReadReceipt(optionMap.getBoolean(Constant.NEED_READ_RECEIPT));
}
}
ReadableMap target = map.getMap(Constant.TARGET);
String type = target.getString(Constant.TYPE);
Conversation targetConversation = null;
if (type.equals(Constant.TYPE_USER)) {
String username = map.getString(Constant.USERNAME);
String appKey = "";
if (map.hasKey(Constant.APP_KEY)) {
appKey = map.getString(Constant.APP_KEY);
}
targetConversation = Conversation.createSingleConversation(username, appKey);
} else {
String groupId = map.getString(Constant.GROUP_ID);
targetConversation = Conversation.createGroupConversation(Long.parseLong(groupId));
}
JMessageClient.forwardMessage(message, targetConversation, options, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
}
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
/**
* AppKey
*
* @param param
* @param success
* @param fail
*/
@ReactMethod
public void getChatRoomListByApp(ReadableMap param, final Callback success, final Callback fail) {
try {
int start = param.getInt("start");
int count = param.getInt("count");
ChatRoomManager.getChatRoomListByApp(start, count, new RequestCallback<List<ChatRoomInfo>>() {
@Override
public void gotResult(int status, String desc, List<ChatRoomInfo> chatRoomInfos) {
mJMessageUtils.handleCallbackWithArray(status, desc, success, fail,
ResultUtils.toJSArray(chatRoomInfos));
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
/**
*
*
* @param success
* @param fail
*/
@ReactMethod
public void getChatRoomListByUser(final Callback success, final Callback fail) {
ChatRoomManager.getChatRoomListByUser(new RequestCallback<List<ChatRoomInfo>>() {
@Override
public void gotResult(int status, String desc, List<ChatRoomInfo> list) {
mJMessageUtils.handleCallbackWithArray(status, desc, success, fail, ResultUtils.toJSArray(list));
}
});
}
/**
* roomId
*
* @param map roomId
* @param success
* @param fail
*/
@ReactMethod
public void getChatRoomInfos(ReadableMap map, final Callback success, final Callback fail) {
try {
ReadableArray array = map.getArray(Constant.ROOM_IDS);
Set<Long> idSet = new HashSet<>();
for (int i = 0; i < array.size() - 1; i++) {
long id = Long.parseLong(array.getString(i));
idSet.add(id);
}
ChatRoomManager.getChatRoomInfos(idSet, new RequestCallback<List<ChatRoomInfo>>() {
@Override
public void gotResult(int status, String desc, List<ChatRoomInfo> list) {
mJMessageUtils.handleCallbackWithArray(status, desc, success, fail, ResultUtils.toJSArray(list));
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
/**
* UserInfo
*
* @param map id
* @param success
* @param fail
*/
@ReactMethod
public void getChatRoomOwner(ReadableMap map, final Callback success, final Callback fail) {
try {
long id = Long.parseLong(map.getString(Constant.ROOM_ID));
Set<Long> set = new HashSet<>();
set.add(id);
ChatRoomManager.getChatRoomInfos(set, new RequestCallback<List<ChatRoomInfo>>() {
@Override
public void gotResult(int status, String desc, List<ChatRoomInfo> list) {
list.get(0).getOwnerInfo(new GetUserInfoCallback() {
@Override
public void gotResult(int status, String desc, UserInfo userInfo) {
mJMessageUtils.handleCallbackWithObject(status, desc, success, fail,
ResultUtils.toJSObject(userInfo));
}
});
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
/**
*
*
* @param map id
* @param success
* @param fail
*/
@ReactMethod
public void enterChatRoom(ReadableMap map, final Callback success, final Callback fail) {
ChatRoomManager.enterChatRoom(Long.parseLong(map.getString(Constant.ROOM_ID)),
new RequestCallback<Conversation>() {
@Override
public void gotResult(int status, String desc, Conversation conversation) {
mJMessageUtils.handleCallbackWithObject(status, desc, success, fail,
ResultUtils.toJSObject(conversation));
}
});
}
/**
*
*
* @param map id
* @param success
* @param fail
*/
@ReactMethod
public void leaveChatRoom(ReadableMap map, final Callback success, final Callback fail) {
ChatRoomManager.leaveChatRoom(Long.parseLong(map.getString(Constant.ROOM_ID)), new BasicCallback() {
@Override
public void gotResult(int i, String s) {
mJMessageUtils.handleCallback(i, s, success, fail);
}
});
}
/**
*
*
* @param success
*/
@ReactMethod
public void getChatRoomConversationList(Callback success) {
List<Conversation> list = JMessageClient.getChatRoomConversationList();
success.invoke(ResultUtils.toJSArray(list));
}
/**
* true false
*
* @param roomId id
*/
@ReactMethod
public void deleteChatRoomConversation(String roomId, Callback success) {
success.invoke(JMessageClient.deleteChatRoomConversation(Long.parseLong(roomId)));
}
/**
*
*
* @param roomId id
*/
@ReactMethod
public void createChatRoomConversation(String roomId, Callback success) {
Conversation conversation = Conversation.createChatRoomConversation(Long.parseLong(roomId));
success.invoke(ResultUtils.toJSObject(conversation));
}
/**
*
*
* @param success
*/
@ReactMethod
public void getAllUnreadCount(Callback success) {
// WritableMap map = Arguments.createMap();
int count = JMessageClient.getAllUnReadMsgCount();
// map.putInt("count", count);
success.invoke(count);
}
@ReactMethod
public void addGroupAdmins(final ReadableMap map, final Callback success, final Callback fail) {
try {
long groupId = Long.parseLong(map.getString(Constant.GROUP_ID));
JMessageClient.getGroupInfo(groupId, new GetGroupInfoCallback() {
@Override
public void gotResult(int status, String desc, GroupInfo groupInfo) {
if (status == 0) {
String appKey = map.hasKey(Constant.APP_KEY) ? map.getString(Constant.APP_KEY) : "";
ReadableArray array = map.getArray(Constant.USERNAMES);
final List<UserInfo> userInfos = new ArrayList<>();
for (int i = 0; i < array.size(); i++) {
userInfos.add(groupInfo.getGroupMemberInfo(array.getString(i), appKey));
}
groupInfo.addGroupKeeper(userInfos, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void removeGroupAdmins(final ReadableMap map, final Callback success, final Callback fail) {
try {
long groupId = Long.parseLong(map.getString(Constant.GROUP_ID));
JMessageClient.getGroupInfo(groupId, new GetGroupInfoCallback() {
@Override
public void gotResult(int status, String desc, GroupInfo groupInfo) {
if (status == 0) {
String appKey = map.hasKey(Constant.APP_KEY) ? map.getString(Constant.APP_KEY) : "";
ReadableArray array = map.getArray(Constant.USERNAMES);
final List<UserInfo> userInfos = new ArrayList<>();
for (int i = 0; i < array.size(); i++) {
userInfos.add(groupInfo.getGroupMemberInfo(array.getString(i), appKey));
}
groupInfo.removeGroupKeeper(userInfos, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void changeGroupType(final ReadableMap map, final Callback success, final Callback fail) {
try {
long groupId = Long.parseLong(map.getString(Constant.GROUP_ID));
JMessageClient.getGroupInfo(groupId, new GetGroupInfoCallback() {
@Override
public void gotResult(int status, String desc, GroupInfo groupInfo) {
if (status == 0) {
String type = map.getString(Constant.TYPE);
if (type.equals("private")) {
groupInfo.changeGroupType(GroupInfo.Type.private_group, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} else if (type.equals("public")) {
groupInfo.changeGroupType(GroupInfo.Type.public_group, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} else {
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void getPublicGroupInfos(final ReadableMap map, final Callback success, final Callback fail) {
try {
String appKey = map.hasKey(Constant.APP_KEY) ? map.getString(Constant.APP_KEY) : "";
int start = Integer.parseInt(map.getString(Constant.START));
int count = Integer.parseInt(map.getString(Constant.COUNT));
String reason = map.getString(Constant.REASON);
JMessageClient.getPublicGroupListByApp(appKey, start, count, new RequestCallback<List<GroupBasicInfo>>() {
@Override
public void gotResult(int status, String desc, List<GroupBasicInfo> groupBasicInfos) {
mJMessageUtils.handleCallbackWithArray(status, desc, success, fail,
ResultUtils.toJSArray(groupBasicInfos));
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void applyJoinGroup(final ReadableMap map, final Callback success, final Callback fail) {
try {
long groupId = Long.parseLong(map.getString(Constant.GROUP_ID));
String reason = map.getString(Constant.REASON);
JMessageClient.applyJoinGroup(groupId, reason, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void processApplyJoinGroup(final ReadableMap map, final Callback success, final Callback fail) {
try {
String reason = map.getString(Constant.REASON);
Boolean isAgree = map.getBoolean(Constant.IS_AGREE);
Boolean isRespondInviter = map.getBoolean(Constant.IS_RESPOND_INVITER);
ReadableArray array = map.getArray(Constant.EVENTS);
final List<GroupApprovalEvent> groupApprovalEventList = new ArrayList<>();
for (int i = 0; i < array.size(); i++) {
GroupApprovalEvent groupApprovalEvent = EventUtils.getGroupApprovalEvent(getCurrentActivity(),array.getString(i));
if (groupApprovalEvent == null) {
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER,
ERR_MSG_PARAMETER + ": can't get event through " + array.getString(i));
return;
}
groupApprovalEventList.add(groupApprovalEvent);
}
if (groupApprovalEventList.size() == 0) {
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, "Can not find GroupApprovalEvent by events");
return;
}
if (isAgree) {
GroupApprovalEvent.acceptGroupApprovalInBatch(groupApprovalEventList, isRespondInviter,
new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
EventUtils.removeGroupApprovalEvents(getCurrentActivity(),groupApprovalEventList);
}
});
} else {
for (int i = 0; i < groupApprovalEventList.size(); i++) {
final GroupApprovalEvent groupApprovalEvent = groupApprovalEventList.get(i);
final int finalI = i;
groupApprovalEvent.refuseGroupApproval(groupApprovalEvent.getFromUsername(),
groupApprovalEvent.getfromUserAppKey(),
reason,
new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
if(finalI == groupApprovalEventList.size()-1){
mJMessageUtils.handleCallback(status, desc, success, fail);
}
if(status == 0){
EventUtils.removeGroupApprovalEvent(getCurrentActivity(),groupApprovalEvent.getEventId()+"");
}
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void transferGroupOwner(final ReadableMap map, final Callback success, final Callback fail) {
try {
long groupId = Long.parseLong(map.getString(Constant.GROUP_ID));
final String username = map.getString(Constant.USERNAME);
final String appKey = map.hasKey(Constant.APP_KEY) ? map.getString(Constant.APP_KEY) : "";
JMessageClient.getGroupInfo(groupId, new GetGroupInfoCallback() {
@Override
public void gotResult(int status, String desc, GroupInfo groupInfo) {
if (status == 0) {
groupInfo.changeGroupAdmin(username, appKey, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void setGroupMemberSilence(final ReadableMap map, final Callback success, final Callback fail) {
try {
long groupId = Long.parseLong(map.getString(Constant.GROUP_ID));
final String username = map.getString(Constant.USERNAME);
final String appKey = map.hasKey(Constant.APP_KEY) ? map.getString(Constant.APP_KEY) : "";
final Boolean isSilence =map.getBoolean(Constant.IS_SILENCE);
JMessageClient.getGroupInfo(groupId, new GetGroupInfoCallback() {
@Override
public void gotResult(int status, String desc, GroupInfo groupInfo) {
if (status == 0) {
groupInfo.setGroupMemSilence(username, appKey, isSilence, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void isSilenceMember(final ReadableMap map, final Callback success, final Callback fail) {
try {
long groupId = Long.parseLong(map.getString(Constant.GROUP_ID));
final String username = map.getString(Constant.USERNAME);
final String appKey = map.hasKey(Constant.APP_KEY) ? map.getString(Constant.APP_KEY) : "";
JMessageClient.getGroupInfo(groupId, new GetGroupInfoCallback() {
@Override
public void gotResult(int status, String desc, GroupInfo groupInfo) {
if (status == 0) {
boolean isSilence = groupInfo.isKeepSilence(username, appKey);
WritableMap result = Arguments.createMap();
result.putBoolean(Constant.IS_SILENCE, isSilence);
mJMessageUtils.handleCallbackWithObject(status, desc, success, fail, result);
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void groupSilenceMembers(final ReadableMap map, final Callback success, final Callback fail) {
try {
long groupId = Long.parseLong(map.getString(Constant.GROUP_ID));
JMessageClient.getGroupInfo(groupId, new GetGroupInfoCallback() {
@Override
public void gotResult(int status, String desc, GroupInfo groupInfo) {
if (status == 0) {
List<GroupMemberInfo> groupSilenceMemberInfos = groupInfo.getGroupSilenceMemberInfos();
mJMessageUtils.handleCallbackWithArray(status, desc, success, fail,
ResultUtils.toJSArray(groupSilenceMemberInfos));
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void setGroupNickname(final ReadableMap map, final Callback success, final Callback fail) {
try {
long groupId = Long.parseLong(map.getString(Constant.GROUP_ID));
final String username = map.getString(Constant.USERNAME);
final String appKey = map.hasKey(Constant.APP_KEY) ? map.getString(Constant.APP_KEY) : "";
final String nickname =map.getString("nickName");
JMessageClient.getGroupInfo(groupId, new GetGroupInfoCallback() {
@Override
public void gotResult(int status, String desc, GroupInfo groupInfo) {
if (status == 0) {
groupInfo.setMemNickname(username, appKey, nickname, new BasicCallback() {
@Override
public void gotResult(int status, String desc) {
mJMessageUtils.handleCallback(status, desc, success, fail);
}
});
} else {
mJMessageUtils.handleError(fail, status, desc);
}
}
});
} catch (Exception e) {
e.printStackTrace();
mJMessageUtils.handleError(fail, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
}
@ReactMethod
public void setMsgHaveRead(ReadableMap map, final Callback successCallback, final Callback failCallback) {
try {
String type = map.getString(Constant.TYPE);
if (TextUtils.isEmpty(type)) {
mJMessageUtils.handleError(failCallback, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
Conversation conversation;
switch (type) {
case Constant.TYPE_SINGLE:
String userName = map.getString(Constant.USERNAME);
String appKey = map.getString(Constant.APP_KEY);
//appKeyappKeyuserName
if (TextUtils.isEmpty(userName)) {
mJMessageUtils.handleError(failCallback, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
conversation = JMessageClient.getSingleConversation(userName, appKey);
break;
case Constant.TYPE_GROUP:
String groupId = map.getString(Constant.GROUP_ID);
if (TextUtils.isEmpty(groupId)) {
mJMessageUtils.handleError(failCallback, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
conversation = JMessageClient.getGroupConversation(Long.parseLong(groupId));
break;
case Constant.TYPE_CHAT_ROOM:
String roomId = map.getString(Constant.ROOM_ID);
if (TextUtils.isEmpty(roomId)) {
mJMessageUtils.handleError(failCallback, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
}
conversation = JMessageClient.getChatRoomConversation(Long.parseLong(roomId));
break;
default:
conversation = null;
mJMessageUtils.handleError(failCallback, ERR_CODE_PARAMETER, ERR_MSG_PARAMETER);
break;
}
if (conversation == null) {
mJMessageUtils.handleError(failCallback, ERR_CODE_CONVERSATION, ERR_MSG_CONVERSATION);
return;
}
String messageId = map.getString(Constant.ID);
Message message = conversation.getMessage(Integer.parseInt(messageId));
if (message == null) {
mJMessageUtils.handleError(failCallback, ERR_CODE_MESSAGE, ERR_MSG_MESSAGE);
return;
}
if (message.haveRead()) {
return;
}
message.setHaveRead(new BasicCallback() {
@Override
public void gotResult(int code, String message) {
if (code == 0) {
mJMessageUtils.handleCallback(code, message, successCallback, failCallback);
} else {
mJMessageUtils.handleError(failCallback, code, message);
}
}
});
}catch (Throwable throwable){
mJMessageUtils.handleError(failCallback, ERR_CODE_EXCEPTION, throwable.getMessage());
}
}
public void onEvent(LoginStateChangeEvent event) {
Logger.d(TAG, "event = " + event.toString());
WritableMap map = Arguments.createMap();
map.putString(Constant.TYPE, event.getReason().toString());
getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(LOGIN_STATE_CHANGE_EVENT, map);
}
public void onEvent(MessageEvent event) {
Message msg = event.getMessage();
Logger.d(TAG, "msg = " + msg.toString());
getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(RECEIVE_MSG_EVENT, ResultUtils.toJSObject(msg));
}
public void onEventMainThread(MessageReceiptStatusChangeEvent event) {
WritableMap map = Arguments.createMap();
Conversation conv = event.getConversation();
for (MessageReceiptStatusChangeEvent.MessageReceiptMeta meta : event.getMessageReceiptMetas()) {
WritableMap receiptMap = Arguments.createMap();
receiptMap.putString(Constant.SERVER_ID, String.valueOf(meta.getServerMsgId()));
receiptMap.putInt(Constant.UN_RECEIPT_COUNT, meta.getUnReceiptCnt());
receiptMap.putString(Constant.UN_RECEIPT_M_TIME, String.valueOf(meta.getUnReceiptMtime()));
map.putMap(Constant.RECEIPT_RESULT, receiptMap);
}
getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(RECEIPT_MSG_EVENT, map);
}
/**
*
*
* @param event
*/
public void onEvent(ConversationRefreshEvent event) {
if (event.getReason() == ConversationRefreshEvent.Reason.MSG_ROAMING_COMPLETE) {
WritableMap map = Arguments.createMap();
map.putMap(Constant.CONVERSATION, ResultUtils.toJSObject(event.getConversation()));
getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(SYNC_ROAMING_EVENT, map);
}
}
public void onEvent(ContactNotifyEvent event) {
Logger.d(TAG, "ContactNotifyEvent, event: " + event);
WritableMap map = Arguments.createMap();
map.putString(Constant.TYPE, event.getType().toString());
map.putString(Constant.REASON, event.getReason());
map.putString(Constant.FROM_USERNAME, event.getFromUsername());
map.putString(Constant.FROM_USER_APP_KEY, event.getfromUserAppKey());
getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(CONTACT_NOTIFY_EVENT, map);
}
public void onEvent(MessageRetractEvent event) {
WritableMap map = Arguments.createMap();
map.putMap(Constant.CONVERSATION, ResultUtils.toJSObject(event.getConversation()));
map.putMap(Constant.RETRACT_MESSAGE, ResultUtils.toJSObject(event.getRetractedMessage()));
getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(RETRACT_MESSAGE_EVENT, map);
}
public void onEvent(NotificationClickEvent event) {
try {
Intent launchIntent = mContext.getApplicationContext().getPackageManager()
.getLaunchIntentForPackage(mContext.getPackageName());
launchIntent.setFlags(
Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(launchIntent);
WritableMap map = Arguments.createMap();
map.putMap(Constant.MESSAGE, ResultUtils.toJSObject(event.getMessage()));
getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(CLICK_NOTIFICATION_EVENT, map);
} catch (Exception e) {
e.printStackTrace();
}
}
public void onEvent(OfflineMessageEvent event) {
final List<Message> offlineMsgList = event.getOfflineMessageList();
if (offlineMsgList.size() > 0) {
final WritableMap map = Arguments.createMap();
map.putMap(Constant.CONVERSATION, ResultUtils.toJSObject(event.getConversation()));
int lastMediaMsgIndex = -1;
for (int i = offlineMsgList.size() - 1; i >= 0; i
Message message = offlineMsgList.get(i);
if (message.getContentType() == ContentType.image || message.getContentType() == ContentType.voice) {
lastMediaMsgIndex = i;
break;
}
}
final WritableArray msgArray = Arguments.createArray();
if (lastMediaMsgIndex == -1) {
for (Message msg : offlineMsgList) {
msgArray.pushMap(ResultUtils.toJSObject(msg));
}
map.putArray(Constant.MESSAGE_ARRAY, msgArray);
getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(SYNC_OFFLINE_EVENT, map);
} else {
final int fLastMediaMsgIndex = lastMediaMsgIndex;
for (int i = 0; i < offlineMsgList.size(); i++) {
Message msg = offlineMsgList.get(i);
final int fI = i;
switch (msg.getContentType()) {
case image:
((ImageContent) msg.getContent()).downloadThumbnailImage(msg, new DownloadCompletionCallback() {
@Override
public void onComplete(int status, String desc, File file) {
if (fI == fLastMediaMsgIndex) {
for (Message msg : offlineMsgList) {
msgArray.pushMap(ResultUtils.toJSObject(msg));
}
map.putArray(Constant.MESSAGE_ARRAY, msgArray);
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(SYNC_OFFLINE_EVENT, map);
}
}
});
break;
case voice:
((VoiceContent) msg.getContent()).downloadVoiceFile(msg, new DownloadCompletionCallback() {
@Override
public void onComplete(int status, String desc, File file) {
if (fI == fLastMediaMsgIndex) {
for (Message msg : offlineMsgList) {
msgArray.pushMap(ResultUtils.toJSObject(msg));
}
map.putArray(Constant.MESSAGE_ARRAY, msgArray);
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(SYNC_OFFLINE_EVENT, map);
}
}
});
default:
}
}
}
}
}
/**
*
*
* @param event {@link ChatRoomMessageEvent}
*/
public void onEventMainThread(ChatRoomMessageEvent event) {
List<Message> list = event.getMessages();
Logger.d(TAG, "");
getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(RECEIVE_CHAT_ROOM_MSG_EVENT, ResultUtils.toJSArray(list));
}
public void onEvent(GroupApprovalEvent event) {
Logger.d(TAG, "GroupApprovalEvent, event: " + event);
EventUtils.saveGroupApprovalEvent(getCurrentActivity(),event);
GroupApprovalEvent.Type type = event.getType();
final WritableMap map = Arguments.createMap();
map.putString(Constant.EVENT_ID, event.getEventId() + "");
map.putString(Constant.GROUP_ID, event.getGid() + "");
map.putBoolean(Constant.IS_INITIATIVE_APPLY, type.equals(GroupApprovalEvent.Type.apply_join_group));
event.getFromUserInfo(new GetUserInfoCallback() {
@Override
public void gotResult(int status, String desc, UserInfo userInfo) {
if (status == 0) {
map.putMap(Constant.SEND_APPLY_USER, ResultUtils.toJSObject(userInfo));
}
}
});
event.getApprovalUserInfoList(new GetUserInfoListCallback() {
@Override
public void gotResult(int status, String s, List<UserInfo> list) {
if (status == 0) {
map.putArray(Constant.JOIN_GROUP_USERS, ResultUtils.toJSArray(list));
}
}
});
map.putString(Constant.REASON, event.getReason());
getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(RECEIVE_APPLY_JOIN_GROUP_APPROVAL_EVENT, map);
}
public void onEvent(GroupApprovedNotificationEvent event) {
Logger.d(TAG, "GroupApprovedNotificationEvent, event: " + event);
final WritableMap map = Arguments.createMap();
map.putBoolean(Constant.IS_AGREE, event.getApprovalResult());
map.putString(Constant.APPLY_EVENT_ID, event.getApprovalEventID() + "");
map.putString(Constant.GROUP_ID, event.getGroupID() + "");
event.getOperator(new GetUserInfoCallback() {
@Override
public void gotResult(int status, String desc, UserInfo userInfo) {
if (status == 0) {
map.putMap(Constant.GROUP_ADMIN, ResultUtils.toJSObject(userInfo));
}
}
});
event.getApprovedUserInfoList(new GetUserInfoListCallback() {
@Override
public void gotResult(int status, String s, List<UserInfo> list) {
if (status == 0) {
map.putArray(Constant.USERS, ResultUtils.toJSArray(list));
}
}
});
getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(RECEIVE_GROUP_ADMIN_APPROVAL_EVENT, map);
}
public void onEvent(GroupApprovalRefuseEvent event) {
Logger.d(TAG, "GroupApprovalRefuseEvent, event: " + event);
final WritableMap map = Arguments.createMap();
map.putString(Constant.REASON, event.getReason());
map.putString(Constant.GROUP_ID, event.getGid() + "");
event.getFromUserInfo(new GetUserInfoCallback() {
@Override
public void gotResult(int status, String desc, UserInfo userInfo) {
if (status == 0) {
map.putMap(Constant.GROUP_MANAGER, ResultUtils.toJSObject(userInfo));
}
}
});
getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(RECEIVE_GROUP_ADMIN_REJECT_EVENT, map);
}
}
|
package com.ccentral4j;
import mousio.etcd4j.EtcdClient;
import mousio.etcd4j.requests.EtcdKeyPutRequest;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
public class CCentralTest {
private CCClient cCentral;
@Mock
private EtcdClient client;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
cCentral = new CCEtcdClient("service", client);
when(client.put(anyString(), anyString())).thenReturn(mock(EtcdKeyPutRequest.class));
}
/**
* Schema is sent on first refresh
*/
@Test
public void sendSchema() throws Exception {
cCentral.refresh();
verify(client).put("/ccentral/services/service/schema",
"{\"v\":{\"key\":\"v\",\"title\":\"Version\",\"description\":\"Schema version for tracking instances\",\"type\":\"integer\",\"default\":\"0\"}}");
}
}
|
package com.ikueb.fizzbuzz;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class FiBuTest {
private static final long MAGIC = 23;
private static final String FIZZ = FiBuEnum.THREE.getOutput();
private static final String BUZZ = FiBuEnum.FIVE.getOutput();
/**
* Syntactic sugar to replace lambda's {@link String} representation with something
* more understandable.
*/
private enum SourceWrapper {
CLASS(FiBuMain.CLASS), ENUM(FiBuMain.ENUM), COMBINED(FiBuMain.COMBINED);
private final Supplier<Stream<? extends FiBu>> source;
private SourceWrapper(final Supplier<Stream<? extends FiBu>> source) {
this.source = source;
}
}
@DataProvider(name = "default")
public Iterator<Object[]> getDefaultCases() {
final Collection<String> transformed = Arrays.asList("1", "2", FIZZ, "4", BUZZ,
FIZZ, "7", "8", FIZZ, BUZZ, "11", FIZZ, "13", "14", FIZZ + BUZZ, "16",
"17", FIZZ, "19", BUZZ, FIZZ, "22");
final Collection<String> noTransform = LongStream.range(1, MAGIC)
.mapToObj(Long::toString).collect(Collectors.toList());
return Stream.of(wrap(SourceWrapper.ENUM, transformed),
wrap(SourceWrapper.CLASS, noTransform),
wrap(SourceWrapper.COMBINED, transformed)).iterator();
}
/**
* Test for the default set-up.
*
* @param stream the {@link Stream} to derive the output with
* @param expected the expected output
* @see #getDefaultCases()
*/
@Test(dataProvider = "default")
public void testDefault(final SourceWrapper stream,
final Collection<String> expected) {
test(stream, expected);
}
/**
* Test for getting {@link FiBuEnum} values.
*/
@Test
public void testFiBuEnumOperations() {
assertBoolean(FiBuEnum.get(0).isPresent(), false);
final Optional<FiBu> value = FiBuEnum.get(FiBuEnum.THREE.getFactor());
assertBoolean(value.isPresent(), true);
assertThat(value.get(), equalTo(FiBuEnum.THREE));
final LongStream stream = FiBuEnum.valueStream().mapToLong(FiBu::getFactor);
assertThat(FiBuEnum.getAll(stream.toArray()), equalTo(FiBuEnum.valueStream()
.collect(Collectors.toList())));
}
/**
* Test for the addition and removal of {@link FiBuClass} instances.
*/
@Test
public void testFiBuClassOperations() {
FiBuClass.reset();
final long[] newFactors = new long[] { 7, 11, 13 };
final String[] newOutputs = new String[] { "Jazz", "Fuzz", "Bazz" };
final FiBu newValue = FiBuClass.add(newFactors[0], newOutputs[0]);
final Map<Long, String> map = new HashMap<>();
for (int i = 1; i < newFactors.length; i++) {
map.put(Long.valueOf(newFactors[i]), newOutputs[i]);
}
final Collection<FiBu> newValues = FiBuClass.addAll(map);
FiBuUtils.validate(FiBuMain.CLASS, FiBuMain.COMBINED);
final Iterator<FiBu> newIterator = newValues.iterator();
final FiBu firstValue = newIterator.next();
final FiBu secondValue = newIterator.next();
assertThat(firstValue, not(equalTo(secondValue)));
assertBoolean(firstValue.hashCode() == secondValue.hashCode(), false);
assertBoolean(newIterator.hasNext(), false);
final Iterator<FiBu> streamIterator = FiBuClass.valueStream().iterator();
assertThat(streamIterator.next(), equalTo(newValue));
assertBoolean(FiBuClass.remove(newValue.getFactor()), true);
assertBoolean(FiBuClass.get(newValue.getFactor()).isPresent(), false);
assertBoolean(FiBuClass.remove(newValue.getFactor()), false);
assertThat(FiBuClass.getAll(newFactors), equalTo(newValues));
FiBuClass.reset();
assertThat(Long.valueOf(FiBuClass.valueStream().count()),
equalTo(Long.valueOf(0)));
}
@DataProvider(name = "updated")
public Iterator<Object[]> getUpdatedTestCases() {
final long newFactor = 7;
final String newOutput = "Jazz";
FiBuClass.reset();
FiBuClass.add(newFactor, newOutput);
final Collection<String> enumOutput = Arrays.asList("1", "2", FIZZ, "4", BUZZ,
FIZZ, "7", "8", FIZZ, BUZZ, "11", FIZZ, "13", "14", FIZZ + BUZZ, "16",
"17", FIZZ, "19", BUZZ, FIZZ, "22");
final Collection<String> classOutput = LongStream.range(1, MAGIC)
.mapToObj(v -> v % newFactor == 0 ? newOutput : Long.toString(v))
.collect(Collectors.toList());
final Collection<String> combined = Arrays.asList("1", "2", FIZZ, "4", BUZZ,
FIZZ, newOutput, "8", FIZZ, BUZZ, "11", FIZZ, "13", newOutput, FIZZ
+ BUZZ, "16", "17", FIZZ, "19", BUZZ, FIZZ + newOutput, "22");
return Stream.of(wrap(SourceWrapper.ENUM, enumOutput),
wrap(SourceWrapper.CLASS, classOutput),
wrap(SourceWrapper.COMBINED, combined)).iterator();
}
/**
* Test for the updated set-up.
*
* @param stream the {@link Stream} to derive the output with
* @param expected the expected output
* @see #getUpdatedTestCases()
*/
@Test(dataProvider = "updated")
public void testUpdated(final SourceWrapper stream,
final Collection<String> expected) {
test(stream, expected);
}
private static void test(final SourceWrapper stream,
final Collection<String> expected) {
assertThat(FiBuUtils.process(1, MAGIC, stream.source), equalTo(expected));
}
private static final String BAD_OUTPUT_MESSAGE = "output null, empty or all whitespaces";
private static final String FACTOR_OF_MESSAGE = "same/factor/multiple of ";
private static final String SAME_OUTPUT_MESSAGE = "same output as ";
private enum ExceptionWrapper {
INVALID_FACTOR(true, 1, "ONE", "factor < 2"),
NULL_OUTPUT(true, 2, null, BAD_OUTPUT_MESSAGE),
EMPTY_OUTPUT(true, 2, "", BAD_OUTPUT_MESSAGE),
WHITESPACE_OUTPUT(true, 2, " ", BAD_OUTPUT_MESSAGE),
MULTI_WITH_FACTOR(true, FiBuEnum.THREE.getFactor(), "THREE", FACTOR_OF_MESSAGE),
MULTI_WITH_SAME_OUTPUT(true, MAGIC, FiBuEnum.THREE.getOutput(), SAME_OUTPUT_MESSAGE),
FACTOR(false, FiBuEnum.THREE.getFactor(), "THREE", FACTOR_OF_MESSAGE),
SAME_OUTPUT(false, MAGIC, FiBuEnum.THREE.getOutput(), SAME_OUTPUT_MESSAGE);
private final boolean failOnAdd;
private final long newFactor;
private final String newOutput;
private final String expectedMessage;
private ExceptionWrapper(boolean failOnAdd, long newFactor,
final String newOutput, final String expectedExceptionMessage) {
this.failOnAdd = failOnAdd;
this.newFactor = newFactor;
this.newOutput = newOutput;
this.expectedMessage = expectedExceptionMessage;
}
/**
* @return a {@link Map} to (unsuccessfully) create new {@link FiBuClass}
* instances
*/
private Map<Long, String> getValues() {
final Map<Long, String> map = new HashMap<>();
map.put(Long.valueOf(newFactor), newOutput);
if (equals(MULTI_WITH_FACTOR)) {
map.put(Long.valueOf(newFactor * 2), newOutput + newOutput);
} else if (equals(MULTI_WITH_SAME_OUTPUT)) {
map.put(Long.valueOf(Long.MAX_VALUE), newOutput);
}
return map;
}
}
@DataProvider(name = "exception")
public Iterator<Object[]> getExceptionCases() {
return Stream.of(ExceptionWrapper.values()).map(FiBuTest::wrap).iterator();
}
@Test(dataProvider = "exception")
public void testExceptionCase(final ExceptionWrapper test) {
try {
FiBuClass.addAll(test.getValues());
if (test.failOnAdd) {
throw new AssertionError();
}
} catch (final IllegalStateException e) {
assertThat(e.getMessage(), containsString(test.expectedMessage));
return;
}
try {
FiBuUtils.validate(FiBuMain.CLASS, FiBuMain.COMBINED);
throw new AssertionError();
} catch (final IllegalStateException e) {
assertThat(e.getMessage(), containsString(test.expectedMessage));
FiBuClass.reset();
}
}
private static void assertBoolean(boolean actual, boolean expected) {
assertThat(Boolean.valueOf(actual), equalTo(Boolean.valueOf(expected)));
}
private static Object[] wrap(Object... values) {
return values;
}
}
|
package net.fornwall.jelf;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
class BasicTest {
private interface TestMethod {
void test(ElfFile file) throws Exception;
}
private void parseFile(String fileName, TestMethod consumer) throws Exception {
ElfFile fromStream = ElfFile.from(BasicTest.class.getResourceAsStream('/' + fileName));
consumer.test(fromStream);
Path path = Paths.get(BasicTest.class.getResource('/' + fileName).getPath());
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(path, EnumSet.of(StandardOpenOption.READ))) {
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
ElfFile fromMappedBuffer = ElfFile.from(mappedByteBuffer);
consumer.test(fromMappedBuffer);
}
}
private static void assertSectionNames(ElfFile file, String... expectedSectionNames) {
for (int i = 0; i < expectedSectionNames.length; i++) {
String expected = expectedSectionNames[i];
String actual = file.getSection(i).header.getName();
if (expected == null) {
Assertions.assertNull(actual);
} else {
Assertions.assertEquals(expected, actual);
}
}
}
private void validateHashTable(ElfFile file) {
ElfSymbolTableSection dynsym = (ElfSymbolTableSection) file.firstSectionByType(ElfSectionHeader.SHT_DYNSYM);
ElfHashTable hashTable = file.firstSectionByType(ElfHashTable.class);
if (hashTable != null) {
for (ElfSymbol s : dynsym.symbols) {
if (s.getName() != null) {
Assertions.assertSame(s, hashTable.lookupSymbol(s.getName(), dynsym));
}
}
Assertions.assertNull(hashTable.lookupSymbol("non_existing", dynsym));
}
ElfGnuHashTable gnuHashTable = file.firstSectionByType(ElfGnuHashTable.class);
if (gnuHashTable != null) {
int i = 0;
for (ElfSymbol s : dynsym.symbols) {
if (i++ < gnuHashTable.symbolOffset) continue;
Assertions.assertSame(s, gnuHashTable.lookupSymbol(s.getName(), dynsym));
}
Assertions.assertNull(gnuHashTable.lookupSymbol("non_existing", dynsym));
}
}
@Test
void testAndroidArmBinTset() throws Exception {
parseFile("android_arm_tset", file -> {
Assertions.assertEquals(ElfFile.CLASS_32, file.objectSize);
Assertions.assertEquals(ElfFile.DATA_LSB, file.encoding);
Assertions.assertEquals(ElfFile.ET_EXEC, file.e_type);
Assertions.assertEquals(ElfFile.ARCH_ARM, file.arch);
Assertions.assertEquals(32, file.ph_entry_size);
Assertions.assertEquals(7, file.num_ph);
Assertions.assertEquals(52, file.ph_offset);
Assertions.assertEquals(40, file.sh_entry_size);
Assertions.assertEquals(25, file.num_sh);
Assertions.assertEquals(15856, file.sh_offset);
assertSectionNames(file, null, ".interp", ".dynsym", ".dynstr", ".hash", ".rel.dyn", ".rel.plt", ".plt", ".text");
Assertions.assertEquals("/system/bin/linker", file.getInterpreter());
ElfDynamicSection dynamic = file.getDynamicSection();
Assertions.assertNotNull(dynamic);
Assertions.assertEquals(".dynamic", dynamic.header.getName());
Assertions.assertEquals(8, dynamic.header.entry_size);
Assertions.assertEquals(248, dynamic.header.size);
Assertions.assertEquals(ElfDynamicSection.DF_BIND_NOW, dynamic.getFlags());
Assertions.assertEquals(ElfDynamicSection.DF_1_NOW, dynamic.getFlags1());
Assertions.assertEquals(Arrays.asList("libncursesw.so.6", "libc.so", "libdl.so"), dynamic.getNeededLibraries());
Assertions.assertEquals("/data/data/com.termux/files/usr/lib", dynamic.getRunPath());
Assertions.assertEquals(26, dynamic.entries.size());
Assertions.assertEquals(new ElfDynamicSection.ElfDynamicStructure(3, 0xbf44), dynamic.entries.get(0));
Assertions.assertEquals(new ElfDynamicSection.ElfDynamicStructure(2, 352), dynamic.entries.get(1));
Assertions.assertEquals(new ElfDynamicSection.ElfDynamicStructure(0x17, 0x8868), dynamic.entries.get(2));
Assertions.assertEquals(new ElfDynamicSection.ElfDynamicStructure(0x6ffffffb, 1), dynamic.entries.get(24));
Assertions.assertEquals(new ElfDynamicSection.ElfDynamicStructure(0, 0), dynamic.entries.get(25));
validateHashTable(file);
});
}
@Test
void testAndroidArmLibNcurses() throws Exception {
parseFile("android_arm_libncurses", file -> {
Assertions.assertEquals(ElfFile.CLASS_32, file.objectSize);
Assertions.assertEquals(ElfFile.DATA_LSB, file.encoding);
Assertions.assertEquals(ElfFile.ET_DYN, file.e_type);
Assertions.assertEquals(ElfFile.ARCH_ARM, file.arch);
Assertions.assertEquals("/system/bin/linker", file.getInterpreter());
List<ElfSection> noteSections = file.sectionsOfType(ElfSectionHeader.SHT_NOTE);
Assertions.assertEquals(1, noteSections.size());
Assertions.assertEquals(".note.gnu.gold-version", noteSections.get(0).header.getName());
Assertions.assertEquals("GNU", ((ElfNoteSection) noteSections.get(0)).getName());
Assertions.assertEquals(ElfNoteSection.NT_GNU_GOLD_VERSION, ((ElfNoteSection) noteSections.get(0)).type);
Assertions.assertEquals("gold 1.11", ((ElfNoteSection) noteSections.get(0)).descriptorAsString());
ElfNoteSection noteSection = file.firstSectionByType(ElfNoteSection.class);
Assertions.assertEquals(".note.gnu.gold-version", noteSection.header.getName());
Assertions.assertSame(noteSection, noteSections.get(0));
ElfSymbolTableSection dynsym = (ElfSymbolTableSection) file.firstSectionByType(ElfSectionHeader.SHT_DYNSYM);
Assertions.assertEquals(".dynsym", dynsym.header.getName());
Assertions.assertEquals(768, dynsym.symbols.length);
ElfSymbol symbol = dynsym.symbols[0];
Assertions.assertNull(symbol.getName());
Assertions.assertEquals(ElfSymbol.STT_NOTYPE, symbol.getType());
Assertions.assertEquals(0, symbol.st_size);
Assertions.assertEquals(ElfSymbol.BINDING_LOCAL, symbol.getBinding());
Assertions.assertEquals(ElfSymbol.Visibility.STV_DEFAULT, symbol.getVisibility());
symbol = dynsym.symbols[1];
Assertions.assertEquals("__cxa_finalize", symbol.getName());
Assertions.assertEquals(ElfSymbol.STT_FUNC, symbol.getType());
Assertions.assertEquals(0, symbol.st_size);
Assertions.assertEquals(ElfSymbol.BINDING_GLOBAL, symbol.getBinding());
Assertions.assertEquals(ElfSymbol.Visibility.STV_DEFAULT, symbol.getVisibility());
symbol = dynsym.symbols[767];
Assertions.assertEquals("_Unwind_GetTextRelBase", symbol.getName());
Assertions.assertEquals(ElfSymbol.STT_FUNC, symbol.getType());
Assertions.assertEquals(8, symbol.st_size);
Assertions.assertEquals(ElfSymbol.BINDING_GLOBAL, symbol.getBinding());
Assertions.assertEquals(ElfSymbol.Visibility.STV_DEFAULT, symbol.getVisibility());
ElfSymbolTableSection symtab = (ElfSymbolTableSection) file.firstSectionByType(ElfSectionHeader.SHT_SYMTAB);
Assertions.assertEquals(".symtab", symtab.header.getName());
Assertions.assertEquals(2149, symtab.symbols.length);
symbol = symtab.symbols[0];
Assertions.assertNull(symbol.getName());
Assertions.assertEquals(ElfSymbol.STT_NOTYPE, symbol.getType());
Assertions.assertEquals(ElfSymbol.BINDING_LOCAL, symbol.getBinding());
Assertions.assertEquals(ElfSymbol.Visibility.STV_DEFAULT, symbol.getVisibility());
symbol = symtab.symbols[1];
Assertions.assertEquals("crtbegin_so.c", symbol.getName());
Assertions.assertEquals(ElfSymbol.STT_FILE, symbol.getType());
Assertions.assertEquals(ElfSymbol.BINDING_LOCAL, symbol.getBinding());
Assertions.assertEquals(ElfSymbol.Visibility.STV_DEFAULT, symbol.getVisibility());
symbol = symtab.symbols[2148];
Assertions.assertEquals("_Unwind_GetTextRelBase", symbol.getName());
Assertions.assertEquals(ElfSymbol.STT_FUNC, symbol.getType());
Assertions.assertEquals(ElfSymbol.BINDING_GLOBAL, symbol.getBinding());
Assertions.assertEquals(ElfSymbol.Visibility.STV_DEFAULT, symbol.getVisibility());
validateHashTable(file);
ElfDynamicSection dynamic = file.firstSectionByType(ElfDynamicSection.class);
Assertions.assertEquals(ElfDynamicSection.DF_SYMBOLIC | ElfDynamicSection.DF_BIND_NOW, dynamic.getFlags());
Assertions.assertEquals(ElfDynamicSection.DF_1_NOW, dynamic.getFlags1());
Assertions.assertTrue(file.getProgramHeader(0).isReadable());
Assertions.assertFalse(file.getProgramHeader(0).isWriteable());
Assertions.assertFalse(file.getProgramHeader(0).isExecutable());
Assertions.assertTrue(file.getProgramHeader(2).isReadable());
Assertions.assertFalse(file.getProgramHeader(2).isWriteable());
Assertions.assertTrue(file.getProgramHeader(2).isExecutable());
});
}
@Test
void testLinxAmd64BinDash() throws Exception {
parseFile("linux_amd64_bindash", file -> {
Assertions.assertEquals(ElfFile.CLASS_64, file.objectSize);
Assertions.assertEquals(ElfFile.DATA_LSB, file.encoding);
Assertions.assertEquals(ElfFile.ET_DYN, file.e_type);
Assertions.assertEquals(ElfFile.ARCH_X86_64, file.arch);
Assertions.assertEquals(56, file.ph_entry_size);
Assertions.assertEquals(9, file.num_ph);
Assertions.assertEquals(64, file.sh_entry_size);
Assertions.assertEquals(64, file.ph_offset);
Assertions.assertEquals(27, file.num_sh);
Assertions.assertEquals(119544, file.sh_offset);
assertSectionNames(file, null, ".interp", ".note.ABI-tag", ".note.gnu.build-id", ".gnu.hash", ".dynsym");
ElfDynamicSection ds = file.getDynamicSection();
Assertions.assertEquals(Collections.singletonList("libc.so.6"), ds.getNeededLibraries());
Assertions.assertEquals("/lib64/ld-linux-x86-64.so.2", file.getInterpreter());
ElfSection rodata = file.firstSectionByName(ElfSectionHeader.NAME_RODATA);
Assertions.assertNotNull(rodata);
Assertions.assertEquals(ElfSectionHeader.SHT_PROGBITS, rodata.header.type);
List<ElfSection> noteSections = file.sectionsOfType(ElfSectionHeader.SHT_NOTE);
Assertions.assertEquals(2, noteSections.size());
ElfNoteSection note1 = (ElfNoteSection) noteSections.get(0);
ElfNoteSection note2 = (ElfNoteSection) noteSections.get(1);
Assertions.assertEquals(".note.ABI-tag", note1.header.getName());
Assertions.assertEquals("GNU", note1.getName());
Assertions.assertEquals(ElfNoteSection.NT_GNU_ABI_TAG, note1.type);
Assertions.assertEquals(ElfNoteSection.GnuAbiDescriptor.ELF_NOTE_OS_LINUX, note1.descriptorAsGnuAbi().operatingSystem);
Assertions.assertEquals(2, note1.descriptorAsGnuAbi().majorVersion);
Assertions.assertEquals(6, note1.descriptorAsGnuAbi().minorVersion);
Assertions.assertEquals(24, note1.descriptorAsGnuAbi().subminorVersion);
Assertions.assertEquals(".note.gnu.build-id", note2.header.getName());
Assertions.assertEquals("GNU", note2.getName());
Assertions.assertEquals(ElfNoteSection.NT_GNU_BUILD_ID, note2.type);
Assertions.assertEquals(0x14, note2.descriptorBytes().length);
Assertions.assertEquals(0x0f, note2.descriptorBytes()[0]);
Assertions.assertArrayEquals(new byte[]{0x0f, 0x7f, (byte) 0xf2, (byte) 0x87, (byte) 0xcf, 0x26, (byte) 0xeb, (byte) 0xa9, (byte) 0xa6, 0x64, 0x3b, 0x12, 0x26, 0x08, (byte) 0x9e, (byte) 0xea, 0x57, (byte) 0xcb, 0x7e, 0x44},
note2.descriptorBytes());
validateHashTable(file);
});
}
@Test
public void testObjectFile() throws Exception {
parseFile("objectFile.o", file -> {
Assertions.assertEquals(ElfFile.CLASS_32, file.objectSize);
Assertions.assertEquals(ElfFile.DATA_LSB, file.encoding);
Assertions.assertEquals(ElfFile.ET_REL, file.e_type);
assertSectionNames(file, null, ".text", ".rel.text", ".data", ".bss",
".comment", ".ARM.attributes", ".symtab", ".strtab", ".shstrtab");
List<ElfSection> sections = file.sectionsOfType(ElfSectionHeader.SHT_REL);
Assertions.assertEquals(1, sections.size());
ElfRelocationSection relocations = (ElfRelocationSection) sections.get(0);
Assertions.assertEquals(1, relocations.relocations.length);
ElfRelocation rel = relocations.relocations[0];
Assertions.assertEquals(0x0000_0006, rel.r_offset);
Assertions.assertEquals(0x0000_080A, rel.r_info);
});
}
}
|
package tars.logic;
import com.google.common.eventbus.Subscribe;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.Assert;
import org.junit.rules.TemporaryFolder;
import tars.commons.core.Config;
import tars.commons.core.EventsCenter;
import tars.commons.core.Messages;
import tars.commons.events.model.TarsChangedEvent;
import tars.commons.events.ui.ShowHelpRequestEvent;
import tars.commons.exceptions.DataConversionException;
import tars.commons.util.ConfigUtil;
import tars.logic.Logic;
import tars.logic.LogicManager;
import tars.logic.commands.AddCommand;
import tars.logic.commands.CdCommand;
import tars.logic.commands.ClearCommand;
import tars.logic.commands.Command;
import tars.logic.commands.CommandResult;
import tars.logic.commands.ConfirmCommand;
import tars.logic.commands.DeleteCommand;
import tars.logic.commands.EditCommand;
import tars.logic.commands.ExitCommand;
import tars.logic.commands.FindCommand;
import tars.logic.commands.HelpCommand;
import tars.logic.commands.ListCommand;
import tars.logic.commands.RedoCommand;
import tars.logic.commands.RsvCommand;
import tars.logic.commands.TagCommand;
import tars.logic.commands.UndoCommand;
import tars.logic.parser.ArgumentTokenizer;
import tars.logic.parser.Prefix;
import tars.model.Tars;
import tars.model.Model;
import tars.model.ModelManager;
import tars.model.ReadOnlyTars;
import tars.model.task.*;
import tars.model.task.rsv.RsvTask;
import tars.model.tag.ReadOnlyTag;
import tars.model.tag.Tag;
import tars.model.tag.UniqueTagList;
import tars.storage.StorageManager;
import tars.ui.Formatter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static tars.commons.core.Messages.*;
public class LogicManagerTest {
@Rule
public TemporaryFolder saveFolder = new TemporaryFolder();
private Model model;
private Logic logic;
private Config originalConfig;
private static final String configFilePath = "config.json";
// These are for checking the correctness of the events raised
private ReadOnlyTars latestSavedTars;
private boolean helpShown;
@Subscribe
private void handleLocalModelChangedEvent(TarsChangedEvent abce) {
latestSavedTars = new Tars(abce.data);
}
@Subscribe
private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) {
helpShown = true;
}
@Before
public void setup() {
try {
originalConfig = ConfigUtil.readConfig(configFilePath).get();
} catch (DataConversionException e) {
e.printStackTrace();
}
model = new ModelManager();
String tempTarsFile = saveFolder.getRoot().getPath() + "TempTars.xml";
String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json";
logic = new LogicManager(model, new StorageManager(tempTarsFile, tempPreferencesFile));
EventsCenter.getInstance().registerHandler(this);
latestSavedTars = new Tars(model.getTars()); // last saved assumed to be
// up to date before.
helpShown = false;
}
@After
public void teardown() throws IOException {
undoChangeInTarsFilePath();
EventsCenter.clearSubscribers();
}
@Test
public void execute_invalid() throws Exception {
String invalidCommand = " ";
assertCommandBehavior(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
/**
* Executes the command and confirms that the result message is correct.
* Both the 'tars' and the 'last shown list' are expected to be empty.
*
* @see #assertCommandBehavior(String, String, ReadOnlyTars, List)
*/
private void assertCommandBehavior(String inputCommand, String expectedMessage) throws Exception {
assertCommandBehavior(inputCommand, expectedMessage, new Tars(), Collections.emptyList());
}
/**
* Executes the command and confirms that the result message is correct and
* also confirms that the following three parts of the LogicManager object's
* state are as expected:<br>
* - the internal tars data are same as those in the {@code expectedTars}
* <br>
* - the backing list shown by UI matches the {@code shownList} <br>
* - {@code expectedTars} was saved to the storage file. <br>
*/
private void assertCommandBehavior(String inputCommand, String expectedMessage, ReadOnlyTars expectedTars,
List<? extends ReadOnlyTask> expectedShownList) throws Exception {
// Execute the command
CommandResult result = logic.execute(inputCommand);
// Confirm the ui display elements should contain the right data
assertEquals(expectedMessage, result.feedbackToUser);
assertEquals(expectedShownList, model.getFilteredTaskList());
// Confirm the state of data (saved and in-memory) is as expected
assertEquals(expectedTars, model.getTars());
assertEquals(expectedTars, latestSavedTars);
}
/**
* @@author A0140022H
*/
private void assertCommandBehaviorForList(String inputCommand, String expectedMessage, ReadOnlyTars expectedTars,
List<? extends ReadOnlyTask> expectedShownList) throws Exception {
// Execute the command
CommandResult result = logic.execute(inputCommand);
// Confirm the ui display elements should contain the right data
assertEquals(expectedMessage, result.feedbackToUser);
assertEquals(expectedShownList, model.getFilteredTaskList());
// Confirm the state of data (saved and in-memory) is as expected
assertEquals(expectedTars, latestSavedTars);
}
private void assertCommandBehaviorWithRsvTaskList(String inputCommand, String expectedMessage,
ReadOnlyTars expectedTars, List<? extends ReadOnlyTask> expectedShownTaskList,
List<? extends RsvTask> expectedShownRsvTaskList) throws Exception {
// Execute the command
CommandResult result = logic.execute(inputCommand);
// Confirm the ui display elements should contain the right data
assertEquals(expectedMessage, result.feedbackToUser);
assertEquals(expectedShownTaskList, model.getFilteredTaskList());
assertEquals(expectedShownRsvTaskList, model.getFilteredRsvTaskList());
// Confirm the state of data (saved and in-memory) is as expected
assertEquals(expectedTars, model.getTars());
assertEquals(expectedTars, latestSavedTars);
}
@Test
public void execute_unknownCommandWord() throws Exception {
String unknownCommand = "uicfhmowqewca";
assertCommandBehavior(unknownCommand, MESSAGE_UNKNOWN_COMMAND);
}
@Test
public void execute_help() throws Exception {
assertCommandBehavior("help", HelpCommand.SHOWING_HELP_MESSAGE);
assertTrue(helpShown);
}
@Test
public void execute_exit() throws Exception {
assertCommandBehavior("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT);
}
@Test
public void execute_clear() throws Exception {
TestDataHelper helper = new TestDataHelper();
model.addTask(helper.generateTask(1));
model.addTask(helper.generateTask(2));
model.addTask(helper.generateTask(3));
assertCommandBehavior("clear", ClearCommand.MESSAGE_SUCCESS, new Tars(), Collections.emptyList());
}
@Test
public void execute_undo_emptyCmdHistStack() throws Exception {
assertCommandBehavior("undo", UndoCommand.MESSAGE_EMPTY_UNDO_CMD_HIST);
}
@Test
public void execute_redo_emptyCmdHistStack() throws Exception {
assertCommandBehavior("redo", RedoCommand.MESSAGE_EMPTY_REDO_CMD_HIST);
}
@Test
public void execute_undo_and_redo_add_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.meetAdam();
Tars expectedTars = new Tars();
expectedTars.addTask(toBeAdded);
// execute command and verify result
assertCommandBehavior(helper.generateAddCommand(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded + "\n"), expectedTars, expectedTars.getTaskList());
expectedTars.removeTask(toBeAdded);
assertCommandBehavior("undo",
String.format(UndoCommand.MESSAGE_SUCCESS, String.format(AddCommand.MESSAGE_UNDO, toBeAdded)),
expectedTars, expectedTars.getTaskList());
expectedTars.addTask(toBeAdded);
assertCommandBehavior("redo",
String.format(RedoCommand.MESSAGE_SUCCESS, String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded + "\n")),
expectedTars, expectedTars.getTaskList());
}
@Test
public void execute_undo_and_redo_add_unsuccessful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.meetAdam();
Tars expectedTars = new Tars();
expectedTars.addTask(toBeAdded);
// execute command and verify result
assertCommandBehavior(helper.generateAddCommand(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded + "\n"), expectedTars, expectedTars.getTaskList());
expectedTars.removeTask(toBeAdded);
model.deleteTask(toBeAdded);
assertCommandBehavior("undo",
String.format(UndoCommand.MESSAGE_UNSUCCESS, MESSAGE_TASK_CANNOT_BE_FOUND), expectedTars,
expectedTars.getTaskList());
model.addTask(toBeAdded);
expectedTars.addTask(toBeAdded);
assertCommandBehavior("redo", String.format(RedoCommand.MESSAGE_UNSUCCESS, MESSAGE_DUPLICATE_TASK),
expectedTars, expectedTars.getTaskList());
}
@Test
public void execute_undo_and_redo_delete_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeRemoved = helper.meetAdam();
Tars expectedTars = new Tars();
expectedTars.addTask(toBeRemoved);
// execute command and verify result
assertCommandBehavior(helper.generateAddCommand(toBeRemoved),
String.format(AddCommand.MESSAGE_SUCCESS, toBeRemoved + "\n"), expectedTars,
expectedTars.getTaskList());
expectedTars.removeTask(toBeRemoved);
// execute command and verify result
assertCommandBehavior("del 1", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, toBeRemoved),
expectedTars, expectedTars.getTaskList());
expectedTars.addTask(toBeRemoved);
assertCommandBehavior("undo",
String.format(UndoCommand.MESSAGE_SUCCESS, String.format(DeleteCommand.MESSAGE_UNDO, toBeRemoved)),
expectedTars, expectedTars.getTaskList());
expectedTars.removeTask(toBeRemoved);
assertCommandBehavior("redo",
String.format(RedoCommand.MESSAGE_SUCCESS, String.format(DeleteCommand.MESSAGE_REDO, toBeRemoved)),
expectedTars, expectedTars.getTaskList());
}
@Test
public void execute_undo_and_redo_delete_unsuccessful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeRemoved = helper.meetAdam();
Tars expectedTars = new Tars();
expectedTars.addTask(toBeRemoved);
// execute command and verify result
assertCommandBehavior(helper.generateAddCommand(toBeRemoved),
String.format(AddCommand.MESSAGE_SUCCESS, toBeRemoved + "\n"), expectedTars,
expectedTars.getTaskList());
expectedTars.removeTask(toBeRemoved);
// execute command and verify result
assertCommandBehavior("del 1", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, toBeRemoved),
expectedTars, expectedTars.getTaskList());
expectedTars.addTask(toBeRemoved);
model.addTask(toBeRemoved);
assertCommandBehavior("undo",
String.format(UndoCommand.MESSAGE_UNSUCCESS, String.format(DeleteCommand.MESSAGE_UNDO, toBeRemoved)),
expectedTars, expectedTars.getTaskList());
expectedTars.removeTask(toBeRemoved);
model.deleteTask(toBeRemoved);
assertCommandBehavior("redo",
String.format(RedoCommand.MESSAGE_UNSUCCESS, MESSAGE_TASK_CANNOT_BE_FOUND), expectedTars,
expectedTars.getTaskList());
}
@Test
public void execute_undo_and_redo_edit_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task taskToAdd = helper.meetAdam();
Tars expectedTars = new Tars();
expectedTars.addTask(taskToAdd);
Prefix namePrefix = new Prefix("/n");
Prefix priorityPrefix = new Prefix("/p");
Prefix dateTimePrefix = new Prefix("/dt");
Prefix addTagPrefix = new Prefix("/ta");
Prefix removeTagPrefix = new Prefix("/tr");
// edit task
String args = " /n Meet Betty Green /dt 20/09/2016 1800 to 21/09/2016 1800 /p h /ta tag3 /tr tag2";
ArgumentTokenizer argsTokenizer = new ArgumentTokenizer(namePrefix, priorityPrefix,
dateTimePrefix, addTagPrefix, removeTagPrefix);
argsTokenizer.tokenize(args);
model.addTask(taskToAdd);
Task editedTask = expectedTars.editTask(taskToAdd, argsTokenizer);
String inputCommand = "edit 1 /n Meet Betty Green /dt 20/09/2016 1800 "
+ "to 21/09/2016 1800 /p h /tr tag2 /ta tag3";
// execute command
assertCommandBehavior(inputCommand, String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, editedTask),
expectedTars, expectedTars.getTaskList());
expectedTars.replaceTask(editedTask, taskToAdd);
assertCommandBehavior("undo",
String.format(UndoCommand.MESSAGE_SUCCESS, String.format(EditCommand.MESSAGE_UNDO, taskToAdd)),
expectedTars, expectedTars.getTaskList());
expectedTars.replaceTask(taskToAdd, editedTask);
assertCommandBehavior("redo",
String.format(RedoCommand.MESSAGE_SUCCESS, String.format(EditCommand.MESSAGE_REDO, taskToAdd)),
expectedTars, expectedTars.getTaskList());
}
@Test
public void execute_add_invalidArgsFormat() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE);
assertCommandBehavior("add /dt 22/04/2016 1400 to 23/04/2016 2200 /p h Valid Task Name", expectedMessage);
assertCommandBehavior("add", expectedMessage);
}
@Test
public void execute_add_invalidTaskData() throws Exception {
assertCommandBehavior("add []\\[;] /dt 05/09/2016 1400 to 06/09/2016 2200 /p m", Name.MESSAGE_NAME_CONSTRAINTS);
assertCommandBehavior("add name - hello world /dt 05/09/2016 1400 to 06/09/2016 2200 /p m",
Name.MESSAGE_NAME_CONSTRAINTS);
assertCommandBehavior("add Valid Task Name /dt @@@notAValidDate@@@ -p m", MESSAGE_INVALID_DATE);
assertCommandBehavior("add Valid Task Name /dt 05/09/2016 1400 to 01/09/2016 2200 /p m",
MESSAGE_INVALID_END_DATE);
assertCommandBehavior("add Valid Task Name /dt 05/09/2016 1400 to 06/09/2016 2200 /p medium",
Priority.MESSAGE_PRIORITY_CONSTRAINTS);
assertCommandBehavior("add Valid Task Name /dt 05/09/2016 1400 to 06/09/2016 2200 /p m /t invalid_-[.tag",
Tag.MESSAGE_TAG_CONSTRAINTS);
}
@Test
public void execute_add_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.meetAdam();
Tars expectedTars = new Tars();
expectedTars.addTask(toBeAdded);
// execute command and verify result
assertCommandBehavior(helper.generateAddCommand(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded + "\n"), expectedTars, expectedTars.getTaskList());
}
@Test
public void execute_add_end_date_successful() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.generateTaskWithEndDateOnly("Jane");
Tars expectedTars = new Tars();
expectedTars = new Tars();
expectedTars.addTask(toBeAdded);
// execute command and verify result
assertCommandBehavior(helper.generateAddCommand(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded + "\n"), expectedTars, expectedTars.getTaskList());
}
@Test
public void execute_add_float_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.floatTask();
Tars expectedTars = new Tars();
expectedTars.addTask(toBeAdded);
// execute command and verify result
assertCommandBehavior(helper.generateAddCommand(toBeAdded),
String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded + "\n"), expectedTars, expectedTars.getTaskList());
}
@Test
public void execute_add_empty_task_name_invalid_format() throws Exception {
assertCommandBehavior("add ", String
.format(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)));
}
@Test
public void execute_tag_unsuccessful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.meetAdam();
Tars expectedAB = new Tars();
expectedAB.addTask(toBeAdded);
model.addTask(toBeAdded);
assertCommandBehavior("tag abcde",
String.format(MESSAGE_INVALID_COMMAND_FORMAT, TagCommand.MESSAGE_USAGE), expectedAB,
expectedAB.getTaskList());
assertCommandBehavior("tag /e 1 INVALID_TAG_NAME", Tag.MESSAGE_TAG_CONSTRAINTS, expectedAB,
expectedAB.getTaskList());
}
@Test
public void execute_tag_invalid_index() throws Exception {
// EP: negative number
assertCommandBehavior("tag /e -1 VALIDTASKNAME",
String.format(MESSAGE_INVALID_COMMAND_FORMAT, TagCommand.MESSAGE_USAGE));
// EP: zero
assertCommandBehavior("tag /e 0 VALIDTASKNAME", MESSAGE_INVALID_TAG_DISPLAYED_INDEX);
// EP: signed number
assertCommandBehavior("tag /e +1 VALIDTASKNAME",
String.format(MESSAGE_INVALID_COMMAND_FORMAT, TagCommand.MESSAGE_USAGE));
assertCommandBehavior("tag /e -2 VALIDTASKNAME",
String.format(MESSAGE_INVALID_COMMAND_FORMAT, TagCommand.MESSAGE_USAGE));
}
@Test
public void execute_tag_empty_parameters() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.meetAdam();
Tars expectedAB = new Tars();
expectedAB.addTask(toBeAdded);
model.addTask(toBeAdded);
// EP: empty parameters
assertCommandBehavior("tag", String.format(MESSAGE_INVALID_COMMAND_FORMAT, TagCommand.MESSAGE_USAGE),
expectedAB, expectedAB.getTaskList());
assertCommandBehavior("tag ", String.format(MESSAGE_INVALID_COMMAND_FORMAT, TagCommand.MESSAGE_USAGE),
expectedAB, expectedAB.getTaskList());
assertCommandBehavior("tag -e", String.format(MESSAGE_INVALID_COMMAND_FORMAT, TagCommand.MESSAGE_USAGE),
expectedAB, expectedAB.getTaskList());
assertCommandBehavior("tag -e ", String.format(MESSAGE_INVALID_COMMAND_FORMAT, TagCommand.MESSAGE_USAGE),
expectedAB, expectedAB.getTaskList());
}
@Test
public void execute_tag_listing_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.meetAdam();
Tars expectedAB = new Tars();
expectedAB.addTask(toBeAdded);
model.addTask(toBeAdded);
// execute command and verify result
assertCommandBehavior("tag /ls", new Formatter().formatTags(model.getUniqueTagList()), expectedAB,
expectedAB.getTaskList());
}
@Test
public void execute_tag_rename_successful() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.meetAdam();
Tars expectedAB = new Tars();
expectedAB.addTask(toBeAdded);
model.addTask(toBeAdded);
ReadOnlyTag tagToBeRenamed = expectedAB.getUniqueTagList().getInternalList().get(0);
Tag newTag = new Tag("tag3");
expectedAB.getUniqueTagList().update(tagToBeRenamed, newTag);
expectedAB.getUniqueTaskList().renameTag(tagToBeRenamed, newTag);
// execute command and verify result
assertCommandBehavior("tag /e 1 tag3",
String.format(String.format(TagCommand.MESSAGE_RENAME_TAG_SUCCESS, "tag1", "tag3")), expectedAB,
expectedAB.getTaskList());
}
@Test
public void execute_tag_rename_duplicate() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.meetAdam();
Tars expectedAB = new Tars();
expectedAB.addTask(toBeAdded);
model.addTask(toBeAdded);
// execute command and verify result
assertCommandBehavior("tag /e 1 tag2", MESSAGE_DUPLICATE_TAG, expectedAB, expectedAB.getTaskList());
}
@Test
public void execute_tag_rename_invalid_index() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.meetAdam();
Tars expectedAB = new Tars();
expectedAB.addTask(toBeAdded);
model.addTask(toBeAdded);
// execute command and verify result
assertCommandBehavior("tag /e 3 VALIDTAGNAME", String.format(MESSAGE_INVALID_TAG_DISPLAYED_INDEX),
expectedAB, expectedAB.getTaskList());
assertCommandBehavior("tag /e 4 VALIDTAGNAME", String.format(MESSAGE_INVALID_TAG_DISPLAYED_INDEX),
expectedAB, expectedAB.getTaskList());
}
/**
* @@author A0140022H
*/
@Test
public void execute_add_recurring() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.meetAdam();
Task toBeAdded2 = helper.meetAdam();
toBeAdded2.setDateTime(new DateTime("08/09/2016 1400", "08/09/2016 1500"));
Tars expectedAB = new Tars();
expectedAB.addTask(toBeAdded);
expectedAB.addTask(toBeAdded2);
// execute command and verify result
String expectedMessage = String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded + "\n");
expectedMessage += String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded2 + "\n");
assertCommandBehavior(helper.generateAddCommand(toBeAdded).concat(" /r 2 every week"), expectedMessage,
expectedAB, expectedAB.getTaskList());
}
@Test
public void execute_addDuplicate_notAllowed() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task toBeAdded = helper.meetAdam();
Tars expectedTars = new Tars();
expectedTars.addTask(toBeAdded);
// setup starting state
model.addTask(toBeAdded); // task already in internal address book
// execute command and verify result
assertCommandBehavior(helper.generateAddCommand(toBeAdded), MESSAGE_DUPLICATE_TASK, expectedTars,
expectedTars.getTaskList());
}
@Test
public void execute_listInvalidFlags_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("ls -", expectedMessage);
}
/**
* Test for list command
*
* @@author A0140022H
* @throws Exception
*/
@Test
public void execute_list_showsAllTasks() throws Exception {
// prepare expectations
TestDataHelper helper = new TestDataHelper();
Tars expectedTars = helper.generateTars(2);
List<? extends ReadOnlyTask> expectedList = expectedTars.getTaskList();
// prepare tars state
helper.addToModel(model, 2);
assertCommandBehavior("ls", ListCommand.MESSAGE_SUCCESS, expectedTars, expectedList);
}
/**
* Test for list command
*
* @@author A0140022H
* @throws Exception
*/
@Test
public void execute_list_showsAllTasksByPriority() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task task1 = helper.generateTaskWithName("task1");
Task task2 = helper.generateTaskWithName("task2");
Task task3 = helper.generateTaskWithName("task3");
task1.setPriority(new Priority("l"));
task2.setPriority(new Priority("m"));
task3.setPriority(new Priority("h"));
Tars expectedTars = new Tars();
expectedTars.addTask(task3);
expectedTars.addTask(task2);
expectedTars.addTask(task1);
List<Task> listToSort = helper.generateTaskList(task3, task2, task1);
List<Task> expectedList = helper.generateTaskList(task1, task2, task3);
helper.addToModel(model, listToSort);
assertCommandBehaviorForList("ls -p", ListCommand.MESSAGE_SUCCESS_PRIORITY, expectedTars, expectedList);
}
/**
* Test for list command
*
* @@author A0140022H
* @throws Exception
*/
@Test
public void execute_list_showsAllTasksByPriorityDescending() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task task1 = helper.generateTaskWithName("task1");
Task task2 = helper.generateTaskWithName("task2");
Task task3 = helper.generateTaskWithName("task3");
task1.setPriority(new Priority("l"));
task2.setPriority(new Priority("m"));
task3.setPriority(new Priority("h"));
Tars expectedTars = new Tars();
expectedTars.addTask(task1);
expectedTars.addTask(task2);
expectedTars.addTask(task3);
List<Task> listToSort = helper.generateTaskList(task1, task2, task3);
List<Task> expectedList = helper.generateTaskList(task3, task2, task1);
helper.addToModel(model, listToSort);
assertCommandBehaviorForList("ls -p dsc", ListCommand.MESSAGE_SUCCESS_PRIORITY_DESCENDING, expectedTars,
expectedList);
}
/**
* Test for list command
*
* @@author A0140022H
* @throws Exception
*/
@Test
public void execute_list_showsAllTasksByDatetime() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task task1 = helper.generateTaskWithName("task1");
Task task2 = helper.generateTaskWithName("task2");
Task task3 = helper.generateTaskWithName("task3");
task1.setDateTime(new DateTime("", "01/02/2016 1600"));
task2.setDateTime(new DateTime("", "02/02/2016 1600"));
task3.setDateTime(new DateTime("", "03/02/2016 1600"));
Tars expectedTars = new Tars();
expectedTars.addTask(task3);
expectedTars.addTask(task2);
expectedTars.addTask(task1);
List<Task> listToSort = helper.generateTaskList(task3, task2, task1);
List<Task> expectedList = helper.generateTaskList(task1, task2, task3);
helper.addToModel(model, listToSort);
assertCommandBehaviorForList("ls -dt", ListCommand.MESSAGE_SUCCESS_DATETIME, expectedTars, expectedList);
}
/**
* Test for list command
*
* @@author A0140022H
* @throws Exception
*/
@Test
public void execute_list_showsAllTasksByDatetimeDescending() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task task1 = helper.generateTaskWithName("task1");
Task task2 = helper.generateTaskWithName("task2");
Task task3 = helper.generateTaskWithName("task3");
task1.setDateTime(new DateTime("", "01/02/2016 1600"));
task2.setDateTime(new DateTime("", "02/02/2016 1600"));
task3.setDateTime(new DateTime("", "03/02/2016 1600"));
Tars expectedTars = new Tars();
expectedTars.addTask(task1);
expectedTars.addTask(task2);
expectedTars.addTask(task3);
List<Task> listToSort = helper.generateTaskList(task1, task2, task3);
List<Task> expectedList = helper.generateTaskList(task3, task2, task1);
helper.addToModel(model, listToSort);
assertCommandBehaviorForList("ls -dt dsc", ListCommand.MESSAGE_SUCCESS_DATETIME_DESCENDING, expectedTars,
expectedList);
}
/**
* Confirms the 'invalid argument index number behaviour' for the given
* command targeting a single task in the shown list, using visible index.
*
* @param commandWord
* to test assuming it targets a single task in the last shown
* list based on visible index.
*/
private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage)
throws Exception {
assertCommandBehavior(commandWord, expectedMessage); // index missing
assertCommandBehavior(commandWord + " +1", expectedMessage); // index
// should
// unsigned
assertCommandBehavior(commandWord + " -1", expectedMessage); // index
// should
// unsigned
assertCommandBehavior(commandWord + " 0", expectedMessage); // index
// cannot be
assertCommandBehavior(commandWord + " not_a_number", expectedMessage);
}
/**
* Confirms the 'invalid argument index number behaviour' for the given
* command targeting a single task in the shown list, using visible index.
*
* @param commandWord
* to test assuming it targets a single task in the last shown
* list based on visible index.
*/
private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception {
String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX;
TestDataHelper helper = new TestDataHelper();
List<Task> taskList = helper.generateTaskList(2);
// set AB state to 2 tasks
model.resetData(new Tars());
for (Task p : taskList) {
model.addTask(p);
}
if ("edit".equals(commandWord)) { // Only For Edit Command
assertCommandBehavior(commandWord + " 3 /n changeTaskName", expectedMessage, model.getTars(), taskList);
} else { // For Select & Delete Commands
assertCommandBehavior(commandWord + " 3", expectedMessage, model.getTars(), taskList);
}
}
// @@author A0124333U
private void assertInvalidInputBehaviorForEditCommand(String inputCommand, String expectedMessage)
throws Exception {
TestDataHelper helper = new TestDataHelper();
List<Task> taskList = helper.generateTaskList(2);
// set Tars state to 2 tasks
model.resetData(new Tars());
for (Task p : taskList) {
model.addTask(p);
}
assertCommandBehavior(inputCommand, expectedMessage, model.getTars(), taskList);
}
@Test
public void execute_rsvInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, RsvCommand.MESSAGE_USAGE);
assertCommandBehavior("rsv ", expectedMessage);
}
@Test
public void execute_rsvAddInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessageForNullDate = String.format(MESSAGE_INVALID_COMMAND_FORMAT,
RsvCommand.MESSAGE_DATETIME_NOTFOUND);
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, RsvCommand.MESSAGE_USAGE);
assertCommandBehavior("rsv Rsv Task Without Date", expectedMessageForNullDate);
assertCommandBehavior("rsv Rsv Task with flags other than date -p h", expectedMessageForNullDate);
assertCommandBehavior("rsv /dt tomorrow", expectedMessage);
assertCommandBehavior("rsv Rsv Task with invalid Date /dt invalidDate", MESSAGE_INVALID_DATE);
}
@Test
public void execute_rsvDelInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, RsvCommand.MESSAGE_USAGE_DEL);
assertCommandBehavior("rsv invalidArgs /del 1", expectedMessage);
assertCommandBehavior("rsv /del invalidValue", expectedMessage);
}
@Test
public void execute_rsvDel_success() throws Exception {
TestDataHelper helper = new TestDataHelper();
// Create a reserved task
RsvTask rsvTask = helper.generateReservedTaskWithOneDateTimeOnly("Test Task");
// Create empty taskList
List<Task> taskList = new ArrayList<Task>();
// Create empty end state rsvTaskList
List<RsvTask> rsvTaskList = new ArrayList<RsvTask>();
// Create empty end state Tars
Tars expectedTars = new Tars();
// Set Tars start state to 1 reserved task, and 0 tasks.
model.resetData(new Tars());
model.addRsvTask(rsvTask);
String expectedMessage = String.format(RsvCommand.MESSAGE_SUCCESS_DEL, rsvTask);
assertCommandBehaviorWithRsvTaskList("rsv /del 1", expectedMessage, expectedTars, taskList, rsvTaskList);
}
@Test
public void execute_confirmInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, ConfirmCommand.MESSAGE_USAGE);
assertCommandBehavior("confirm ", expectedMessage);
assertCommandBehavior("confirm -p h 1 2", expectedMessage);
assertCommandBehavior("confirm 1 1 -dt invalidFlag", expectedMessage);
assertCommandBehavior("confirm 1 1 3", expectedMessage);
}
@Test
public void execute_confirmInvalidRsvTaskIndex_errorMessageShown() throws Exception {
assertCommandBehavior("confirm 2 3", MESSAGE_INVALID_RSV_TASK_DISPLAYED_INDEX);
}
@Test
public void execute_confirm_success() throws Exception {
TestDataHelper helper = new TestDataHelper();
// Create added task
Task addedTask = helper.generateTaskWithName("Test Task");
// Create end state taskList with one confirmed task
List<Task> taskList = new ArrayList<Task>();
taskList.add(addedTask);
// Create Empty end state rsvTaskList
List<RsvTask> rsvTaskList = new ArrayList<RsvTask>();
RsvTask rsvTask = helper.generateReservedTaskWithOneDateTimeOnly("Test Task");
Tars expectedTars = new Tars();
expectedTars.addTask(addedTask);
// Set Tars start state to 1 reserved task, and 0 tasks.
model.resetData(new Tars());
model.addRsvTask(rsvTask);
String expectedMessage = String.format(ConfirmCommand.MESSAGE_CONFIRM_SUCCESS, addedTask);
assertCommandBehaviorWithRsvTaskList("confirm 1 1 /p h /t tag", expectedMessage, expectedTars, taskList,
rsvTaskList);
}
@Test
public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE);
assertIncorrectIndexFormatBehaviorForCommand("del ", expectedMessage);
}
@Test
public void execute_deleteIndexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("del");
}
@Test
public void execute_delete_removesCorrectTask() throws Exception {
TestDataHelper helper = new TestDataHelper();
List<Task> threeTasks = helper.generateTaskList(3);
Tars expectedTars = helper.generateTars(threeTasks);
expectedTars.removeTask(threeTasks.get(1));
helper.addToModel(model, threeTasks);
assertCommandBehavior("del 2", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, threeTasks.get(1)),
expectedTars, expectedTars.getTaskList());
}
@Test
public void execute_delete_Range() throws Exception {
TestDataHelper helper = new TestDataHelper();
List<Task> threeTasks = helper.generateTaskList(3);
Tars expectedTars = helper.generateTars(threeTasks);
helper.addToModel(model, threeTasks);
// delete tasks within range
expectedTars.removeTask(threeTasks.get(0));
expectedTars.removeTask(threeTasks.get(1));
expectedTars.removeTask(threeTasks.get(2));
ArrayList<ReadOnlyTask> deletedTasks = new ArrayList<ReadOnlyTask>();
deletedTasks.add(threeTasks.get(0));
deletedTasks.add(threeTasks.get(1));
deletedTasks.add(threeTasks.get(2));
String result = CommandResult.formatTasksList(deletedTasks);
assertCommandBehavior("del 1..3", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, result),
expectedTars, expectedTars.getTaskList());
}
@Test
public void execute_find_invalidArgsFormat() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE);
assertCommandBehavior("find ", expectedMessage);
}
@Test
public void execute_find_quickSearch_onlyMatchesFullWordsInNames() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla");
Task pTarget2 = helper.generateTaskWithName("bla KEY bla bceofeia");
Task p1 = helper.generateTaskWithName("KE Y");
Task p2 = helper.generateTaskWithName("KEYKEYKEY sduauo");
List<Task> fourTasks = helper.generateTaskList(p1, pTarget1, p2, pTarget2);
Tars expectedTars = helper.generateTars(fourTasks);
List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2);
helper.addToModel(model, fourTasks);
String searchKeywords = "\nQuick Search Keywords: [KEY]";
assertCommandBehavior("find KEY",
Command.getMessageForTaskListShownSummary(expectedList.size()) + searchKeywords, expectedTars,
expectedList);
}
@Test
public void execute_find_quickSearch_isNotCaseSensitive() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task p1 = helper.generateTaskWithName("bla bla KEY bla");
Task p2 = helper.generateTaskWithName("bla KEY bla bceofeia");
Task p3 = helper.generateTaskWithName("key key");
Task p4 = helper.generateTaskWithName("KEy sduauo");
List<Task> fourTasks = helper.generateTaskList(p3, p1, p4, p2);
Tars expectedTars = helper.generateTars(fourTasks);
List<Task> expectedList = fourTasks;
helper.addToModel(model, fourTasks);
String searchKeywords = "\nQuick Search Keywords: [KEY]";
assertCommandBehavior("find KEY",
Command.getMessageForTaskListShownSummary(expectedList.size()) + searchKeywords, expectedTars,
expectedList);
}
@Test
public void execute_find_quickSearch_matchesIfAllKeywordPresent() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task p1 = helper.generateTaskWithName("bla bla KEY bla");
Task p2 = helper.generateTaskWithName("bla rAnDoM bla bceofeia");
Task p3 = helper.generateTaskWithName("sduauo");
Task pTarget1 = helper.generateTaskWithName("key key rAnDoM");
List<Task> fourTasks = helper.generateTaskList(p1, p2, p3, pTarget1);
Tars expectedTars = helper.generateTars(fourTasks);
List<Task> expectedList = helper.generateTaskList(pTarget1);
helper.addToModel(model, fourTasks);
String searchKeywords = "\nQuick Search Keywords: [key, rAnDoM]";
assertCommandBehavior("find key rAnDoM",
Command.getMessageForTaskListShownSummary(expectedList.size()) + searchKeywords, expectedTars,
expectedList);
}
@Test
public void execute_find_filterSearch_matchesIfAllKeywordPresent() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task pTarget1 = helper.meetAdam();
Task p1 = helper.generateTask(2);
Task p2 = helper.generateTask(3);
List<Task> threeTasks = helper.generateTaskList(pTarget1, p1, p2);
Tars expectedTars = helper.generateTars(threeTasks);
List<Task> expectedList = helper.generateTaskList(pTarget1);
helper.addToModel(model, threeTasks);
String searchKeywords = "\nFilter Search Keywords: [Task Name: adam] "
+ "[DateTime: 01/09/2016 1400 to 01/09/2016 1500] [Priority: medium] "
+ "[Status: Undone] [Tags: tag1]";
assertCommandBehavior("find /n adam /dt 01/09/2016 1400 to 01/09/2016 1500 /p medium /ud /t tag1",
Command.getMessageForTaskListShownSummary(expectedList.size()) + searchKeywords, expectedTars,
expectedList);
}
@Test
public void execute_find_filterSearch_withoutDateTimeQuery() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task pTarget1 = helper.meetAdam();
Task p1 = helper.generateTask(2);
Task p2 = helper.generateTask(3);
List<Task> threeTasks = helper.generateTaskList(pTarget1, p1, p2);
Tars expectedTars = helper.generateTars(threeTasks);
List<Task> expectedList = helper.generateTaskList(pTarget1);
helper.addToModel(model, threeTasks);
String searchKeywords = "\nFilter Search Keywords: [Task Name: adam] " + "[Priority: medium] "
+ "[Status: Undone] [Tags: tag1]";
assertCommandBehavior("find /n adam /p medium /ud /t tag1",
Command.getMessageForTaskListShownSummary(expectedList.size()) + searchKeywords, expectedTars,
expectedList);
}
@Test
public void execute_find_filterSearch_singleDateTimeQuery() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task pTarget1 = helper.meetAdam();
Task p1 = helper.generateTask(2);
Task p2 = helper.generateTask(3);
List<Task> threeTasks = helper.generateTaskList(pTarget1, p1, p2);
Tars expectedTars = helper.generateTars(threeTasks);
List<Task> expectedList = helper.generateTaskList(pTarget1);
helper.addToModel(model, threeTasks);
String searchKeywords = "\nFilter Search Keywords: [DateTime: 01/09/2016 1400] ";
assertCommandBehavior("find /dt 01/09/2016 1400",
Command.getMessageForTaskListShownSummary(expectedList.size()) + searchKeywords, expectedTars,
expectedList);
}
@Test
public void execute_find_filterSearch_taskNotFound() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task pTarget1 = helper.meetAdam();
Task p1 = helper.generateTask(2);
Task p2 = helper.generateTask(3);
List<Task> threeTasks = helper.generateTaskList(pTarget1, p1, p2);
Tars expectedTars = helper.generateTars(threeTasks);
List<Task> expectedList = helper.generateTaskList();
helper.addToModel(model, threeTasks);
String searchKeywords = "\nFilter Search Keywords: [DateTime: 01/09/2010 1400] ";
assertCommandBehavior("find /dt 01/09/2010 1400",
Command.getMessageForTaskListShownSummary(expectedList.size()) + searchKeywords, expectedTars,
expectedList);
}
@Test
public void execute_find_filterSearch_bothDoneAndUndoneSearched() throws Exception {
assertCommandBehavior("find /do /ud", TaskQuery.MESSAGE_BOTH_STATUS_SEARCHED_ERROR);
}
@Test
public void execute_find_filterSearch_multipleFlagsUsed() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task pTarget1 = helper.meetAdam();
Task p1 = helper.generateTask(2);
Task p2 = helper.generateTask(3);
List<Task> threeTasks = helper.generateTaskList(pTarget1, p1, p2);
Tars expectedTars = helper.generateTars(threeTasks);
List<Task> expectedList = helper.generateTaskList(pTarget1);
helper.addToModel(model, threeTasks);
String searchKeywords = "\nFilter Search Keywords: [Task Name: meet adam] " + "[Priority: medium] "
+ "[Status: Undone] [Tags: tag2 tag1]";
assertCommandBehavior("find /n meet adam /p medium /ud /t tag1 /t tag2",
Command.getMessageForTaskListShownSummary(expectedList.size()) + searchKeywords, expectedTars,
expectedList);
}
/**
* @@author A0124333U
*/
@Test
public void execute_edit_invalidArgsFormat_errorMessageShown() throws Exception {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE);
assertInvalidInputBehaviorForEditCommand("edit ", expectedMessage);
assertInvalidInputBehaviorForEditCommand("edit 1 -invalidFlag invalidArg", expectedMessage);
}
@Test
public void execute_edit_indexNotFound_errorMessageShown() throws Exception {
assertIndexNotFoundBehaviorForCommand("edit");
}
@Test
public void execute_edit_invalidTaskData() throws Exception {
assertInvalidInputBehaviorForEditCommand("edit 1 /n []\\[;]", Name.MESSAGE_NAME_CONSTRAINTS);
assertInvalidInputBehaviorForEditCommand("edit 1 /dt @@@notAValidDate@@@", Messages.MESSAGE_INVALID_DATE);
assertInvalidInputBehaviorForEditCommand("edit 1 /p medium", Priority.MESSAGE_PRIORITY_CONSTRAINTS);
assertInvalidInputBehaviorForEditCommand("edit 1 /n validName /dt invalidDate", Messages.MESSAGE_INVALID_DATE);
assertInvalidInputBehaviorForEditCommand("edit 1 /tr $#$", Tag.MESSAGE_TAG_CONSTRAINTS);
}
@Test
public void execute_edit_editsCorrectTask() throws Exception {
// setup expectations
TestDataHelper helper = new TestDataHelper();
Task taskToAdd = helper.meetAdam();
List<Task> listToEdit = new ArrayList<Task>();
listToEdit.add(taskToAdd);
Tars expectedTars = new Tars();
expectedTars.addTask(taskToAdd);
Prefix namePrefix = new Prefix("/n");
Prefix priorityPrefix = new Prefix("/p");
Prefix dateTimePrefix = new Prefix("/dt");
Prefix addTagPrefix = new Prefix("/ta");
Prefix removeTagPrefix = new Prefix("/tr");
// edit task
String args = " /n Meet Betty Green /dt 20/09/2016 1800 to 21/09/2016 1800 /p h /ta tag3 /tr tag2";
ArgumentTokenizer argsTokenizer = new ArgumentTokenizer(namePrefix, priorityPrefix,
dateTimePrefix, addTagPrefix, removeTagPrefix);
argsTokenizer.tokenize(args);
Task taskToEdit = taskToAdd;
Task editedTask = expectedTars.editTask(taskToEdit, argsTokenizer);
helper.addToModel(model, listToEdit);
String inputCommand = "edit 1 /n Meet Betty Green /dt 20/09/2016 1800 "
+ "to 21/09/2016 1800 /p h /tr tag2 /ta tag3";
// execute command
assertCommandBehavior(inputCommand, String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, editedTask),
expectedTars, expectedTars.getTaskList());
}
@Test
public void execute_cd_incorrectArgsFormat_errorMessageShown() throws Exception {
assertCommandBehavior("cd ", CdCommand.MESSAGE_INVALID_FILEPATH);
}
@Test
public void execute_cd_invalidFileType_errorMessageShown() throws Exception {
assertCommandBehavior("cd invalidFileType", CdCommand.MESSAGE_INVALID_FILEPATH);
}
@Test
public void execute_cd_success() throws Exception {
String tempTestTarsFilePath = saveFolder.getRoot().getPath() + "TempTestTars.xml";
assertCommandBehavior("cd " + tempTestTarsFilePath,
String.format(CdCommand.MESSAGE_SUCCESS, tempTestTarsFilePath));
}
/**
* Logic tests for mark command
*
* @@author A0121533W
*/
@Test
public void execute_mark_allTaskAsDone() throws Exception {
Status done = new Status(true);
TestDataHelper helper = new TestDataHelper();
Task task1 = helper.generateTaskWithName("task1");
Task task2 = helper.generateTaskWithName("task2");
List<Task> taskList = helper.generateTaskList(task1, task2);
Tars expectedTars = new Tars();
helper.addToModel(model, taskList);
Task task1Expected = helper.generateTaskWithName("task1");
Task task2Expected = helper.generateTaskWithName("task2");
task1Expected.setStatus(done);
task2Expected.setStatus(done);
expectedTars.addTask(task1Expected);
expectedTars.addTask(task2Expected);
assertCommandBehavior("mark /do 1 2", "Task: 1, 2 marked done successfully.\n", expectedTars,
expectedTars.getTaskList());
}
@Test
public void execute_mark_alreadyDone() throws Exception {
Status done = new Status(true);
TestDataHelper helper = new TestDataHelper();
Task task1 = helper.generateTaskWithName("task1");
Task task2 = helper.generateTaskWithName("task2");
task1.setStatus(done);
task2.setStatus(done);
List<Task> taskList = helper.generateTaskList(task1, task2);
Tars expectedTars = new Tars();
helper.addToModel(model, taskList);
Task task1Expected = helper.generateTaskWithName("task1");
Task task2Expected = helper.generateTaskWithName("task2");
task1Expected.setStatus(done);
task2Expected.setStatus(done);
expectedTars.addTask(task1Expected);
expectedTars.addTask(task2Expected);
assertCommandBehavior("mark /do 1 2", "Task: 1, 2 already marked done.\n", expectedTars,
expectedTars.getTaskList());
}
@Test
public void execute_mark_allTaskAsUndone() throws Exception {
Status done = new Status(true);
TestDataHelper helper = new TestDataHelper();
Task task1 = helper.generateTaskWithName("task1");
Task task2 = helper.generateTaskWithName("task2");
task1.setStatus(done);
task2.setStatus(done);
List<Task> taskList = helper.generateTaskList(task1, task2);
Tars expectedTars = new Tars();
helper.addToModel(model, taskList);
Task task1Expected = helper.generateTaskWithName("task1");
Task task2Expected = helper.generateTaskWithName("task2");
expectedTars.addTask(task1Expected);
expectedTars.addTask(task2Expected);
assertCommandBehavior("mark /ud 1 2", "Task: 1, 2 marked undone successfully.\n", expectedTars,
expectedTars.getTaskList());
}
@Test
public void execute_mark_alreadyUndone() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task task1 = helper.generateTaskWithName("task1");
Task task2 = helper.generateTaskWithName("task2");
List<Task> taskList = helper.generateTaskList(task1, task2);
Tars expectedTars = new Tars();
helper.addToModel(model, taskList);
Task task1Expected = helper.generateTaskWithName("task1");
Task task2Expected = helper.generateTaskWithName("task2");
expectedTars.addTask(task1Expected);
expectedTars.addTask(task2Expected);
assertCommandBehavior("mark /ud 1 2", "Task: 1, 2 already marked undone.\n", expectedTars,
expectedTars.getTaskList());
}
@Test
public void execute_mark_rangeDone() throws Exception {
Status done = new Status(true);
TestDataHelper helper = new TestDataHelper();
Task task1 = helper.generateTaskWithName("task1");
Task task2 = helper.generateTaskWithName("task2");
Task task3 = helper.generateTaskWithName("task3");
List<Task> taskList = helper.generateTaskList(task1, task2, task3);
Tars expectedTars = new Tars();
helper.addToModel(model, taskList);
Task task1Expected = helper.generateTaskWithName("task1");
Task task2Expected = helper.generateTaskWithName("task2");
Task task3Expected = helper.generateTaskWithName("task3");
task1Expected.setStatus(done);
task2Expected.setStatus(done);
task3Expected.setStatus(done);
expectedTars.addTask(task1Expected);
expectedTars.addTask(task2Expected);
expectedTars.addTask(task3Expected);
assertCommandBehavior("mark /do 1..3", "Task: 1, 2, 3 marked done successfully.\n", expectedTars,
expectedTars.getTaskList());
}
@Test
public void execute_mark_rangeUndone() throws Exception {
Status done = new Status(true);
TestDataHelper helper = new TestDataHelper();
Task task1 = helper.generateTaskWithName("task1");
Task task2 = helper.generateTaskWithName("task2");
Task task3 = helper.generateTaskWithName("task3");
task1.setStatus(done);
task2.setStatus(done);
task3.setStatus(done);
List<Task> taskList = helper.generateTaskList(task1, task2, task3);
Tars expectedTars = new Tars();
helper.addToModel(model, taskList);
Task task1Expected = helper.generateTaskWithName("task1");
Task task2Expected = helper.generateTaskWithName("task2");
Task task3Expected = helper.generateTaskWithName("task3");
expectedTars.addTask(task1Expected);
expectedTars.addTask(task2Expected);
expectedTars.addTask(task3Expected);
assertCommandBehavior("mark /ud 1..3", "Task: 1, 2, 3 marked undone successfully.\n", expectedTars,
expectedTars.getTaskList());
}
@Test
public void check_task_equals() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task taskA = helper.meetAdam();
Task taskB = taskA;
Assert.assertEquals(taskA, taskB);
Assert.assertEquals(taskA.hashCode(), taskB.hashCode());
}
@Test
public void check_name_equals() throws Exception {
TestDataHelper helper = new TestDataHelper();
Task taskA = helper.meetAdam();
Task taskB = taskA;
Assert.assertEquals(taskA.getName(), taskB.getName());
Assert.assertEquals(taskA.getName().hashCode(), taskB.getName().hashCode());
}
/*
* A method to undo any changes to the Tars File Path during tests
*/
public void undoChangeInTarsFilePath() throws IOException {
ConfigUtil.saveConfig(originalConfig, configFilePath);
}
/**
* A utility class to generate test data.
*/
class TestDataHelper {
Task meetAdam() throws Exception {
Name name = new Name("Meet Adam Brown");
DateTime dateTime = new DateTime("01/09/2016 1400", "01/09/2016 1500");
Priority priority = new Priority("m");
Status status = new Status(false);
Tag tag1 = new Tag("tag1");
Tag tag2 = new Tag("tag2");
UniqueTagList tags = new UniqueTagList(tag1, tag2);
return new Task(name, dateTime, priority, status, tags);
}
Task floatTask() throws Exception {
Name name = new Name("Do homework");
DateTime dateTime = new DateTime("", "");
Priority priority = new Priority("");
Status status = new Status(false);
UniqueTagList tags = new UniqueTagList();
return new Task(name, dateTime, priority, status, tags);
}
/**
* Generates a valid task using the given seed. Running this function
* with the same parameter values guarantees the returned task will have
* the same state. Each unique seed will generate a unique Task object.
*
* @param seed
* used to generate the task data field values
*/
Task generateTask(int seed) throws Exception {
int seed2 = (seed + 1) % 31 + 1; // Generate 2nd seed for DateTime
// value
return new Task(new Name("Task " + seed), new DateTime(seed + "/01/2016 1400", seed2 + "/01/2016 2200"),
new Priority("h"), new Status(false),
new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1))));
}
/** Generates the correct add command based on the task given */
String generateAddCommand(Task p) {
StringBuffer cmd = new StringBuffer();
cmd.append("add ").append(p.getName().toString());
if (p.getDateTime().toString().length() > 0) {
cmd.append(" /dt ").append(p.getDateTime().toString());
}
if (p.getPriority().toString().length() > 0) {
cmd.append(" /p ").append(p.getPriority().toString());
}
UniqueTagList tags = p.getTags();
for (Tag t : tags) {
cmd.append(" /t ").append(t.tagName);
}
return cmd.toString();
}
/**
* Generates an Tars with auto-generated undone tasks.
*/
Tars generateTars(int numGenerated) throws Exception {
Tars tars = new Tars();
addToTars(tars, numGenerated);
return tars;
}
/**
* Generates an Tars based on the list of Tasks given.
*/
Tars generateTars(List<Task> tasks) throws Exception {
Tars tars = new Tars();
addToTars(tars, tasks);
return tars;
}
/**
* Adds auto-generated Task objects to the given Tars
*
* @param tars
* The Tars to which the Tasks will be added
*/
void addToTars(Tars tars, int numGenerated) throws Exception {
addToTars(tars, generateTaskList(numGenerated));
}
/**
* Adds the given list of Tasks to the given Tars
*/
void addToTars(Tars tars, List<Task> tasksToAdd) throws Exception {
for (Task p : tasksToAdd) {
tars.addTask(p);
}
}
/**
* Adds auto-generated Task objects to the given model
*
* @param model
* The model to which the Tasks will be added
*/
void addToModel(Model model, int numGenerated) throws Exception {
addToModel(model, generateTaskList(numGenerated));
}
/**
* Adds the given list of Tasks to the given model
*/
void addToModel(Model model, List<Task> tasksToAdd) throws Exception {
for (Task p : tasksToAdd) {
model.addTask(p);
}
}
/**
* Generates a list of Tasks based on the flags.
*/
List<Task> generateTaskList(int numGenerated) throws Exception {
List<Task> tasks = new ArrayList<>();
for (int i = 1; i <= numGenerated; i++) {
tasks.add(generateTask(i));
}
return tasks;
}
List<Task> generateTaskList(Task... tasks) {
return Arrays.asList(tasks);
}
/**
* Generates a Task object with given name. Other fields will have some
* dummy values.
*/
Task generateTaskWithName(String name) throws Exception {
return new Task(new Name(name), new DateTime("05/09/2016 1400", "06/09/2016 2200"), new Priority("h"),
new Status(false), new UniqueTagList(new Tag("tag")));
}
/**
* Generates a Task object with given name. Other fields will have some
* dummy values.
*/
Task generateTaskWithEndDateOnly(String name) throws Exception {
return new Task(new Name(name), new DateTime(null, "06/09/2016 2200"), new Priority("h"), new Status(false),
new UniqueTagList(new Tag("tag")));
}
RsvTask generateReservedTaskWithOneDateTimeOnly(String name) throws Exception {
ArrayList<DateTime> dateTimeList = new ArrayList<DateTime>();
dateTimeList.add(new DateTime("05/09/2016 1400", "06/09/2016 2200"));
return new RsvTask(new Name(name), dateTimeList);
}
}
}
|
package com.nucc.hackwinds.models;
import android.content.Context;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.nucc.hackwinds.types.Forecast;
import com.nucc.hackwinds.listeners.ForecastChangedListener;
import com.nucc.hackwinds.types.ForecastDailySummary;
import com.nucc.hackwinds.types.Swell;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class ForecastModel {
// Public Member Variables
public String locationName;
public String waveModelName;
public String waveModelRun;
public String windModelName;
public String windModelRun;
public ArrayList<Forecast> forecasts;
public ArrayList<ForecastDailySummary> dailyForecasts;
public final int FORECAST_DATA_COUNT = 61;
// Private Member variables
private Context mContext;
private static ForecastModel mInstance;
private ArrayList<ForecastChangedListener> mForecastChangedListeners;
private int dayCount;
private int dayIndices[];
public static ForecastModel getInstance( Context context ) {
if ( mInstance == null ) {
mInstance = new ForecastModel( context );
}
return mInstance;
}
private ForecastModel( Context context ) {
// Initialize the context
mContext = context.getApplicationContext();
// Initialize the forecast changed listener
mForecastChangedListeners = new ArrayList<>();
// Initialize the data arrays
forecasts = new ArrayList<>();
dailyForecasts = new ArrayList<>();
// Set up the day indices array indicating its empty
dayIndices = new int[8];
for (int i = 0; i < 8; i++) {
dayIndices[i] = -1;
}
dayCount = 0;
}
public void addForecastChangedListener( ForecastChangedListener forecastListener ) {
mForecastChangedListeners.add(forecastListener);
}
public void fetchForecastData() {
synchronized (this) {
if (!forecasts.isEmpty()) {
for(ForecastChangedListener listener : mForecastChangedListeners) {
if (listener != null) {
listener.forecastDataUpdated();
}
}
return;
}
// Make the data URL
final String dataURL = "https://rhodycast.appspot.com/forecast_as_json";
Ion.with(mContext).load(dataURL).asString().setCallback(new FutureCallback<String>() {
@Override
public void onCompleted(Exception e, String result) {
if (e != null) {
for(ForecastChangedListener listener : mForecastChangedListeners) {
if (listener != null) {
listener.forecastDataUpdateFailed();
}
}
return;
}
Boolean successfulParse = parseForecasts(result);
if (successfulParse) {
// Parse out the forecasts for the summaries
createDailyForecasts();
for(ForecastChangedListener listener : mForecastChangedListeners) {
if (listener != null) {
listener.forecastDataUpdated();
}
}
} else {
for(ForecastChangedListener listener : mForecastChangedListeners) {
if (listener != null) {
listener.forecastDataUpdateFailed();
}
}
}
}
});
}
}
public ArrayList<Forecast> getForecastsForDay( int day ) {
// Return the array of conditions
if (forecasts.size() != FORECAST_DATA_COUNT) {
return null;
}
int startIndex = 0;
int endIndex = 0;
if (day < 8) {
startIndex = dayIndices[day];
}
if (day < 7) {
endIndex = dayIndices[day+1];
if (endIndex < 0) {
endIndex = forecasts.size();
}
} else {
endIndex = forecasts.size();
}
return new ArrayList<>(forecasts.subList(startIndex, endIndex));
}
private boolean parseForecasts(String rawData) {
// Get the raw data
if (rawData == null) {
return false;
}
if (!forecasts.isEmpty()) {
forecasts.clear();
}
try {
// Make a json array from the response string
JSONObject jsonObj = new JSONObject( rawData );
locationName = jsonObj.getString("LocationName");
waveModelName = jsonObj.getJSONObject("WaveModel").getString("Description");
waveModelRun = jsonObj.getJSONObject("WaveModel").getString("ModelRun");
windModelName = jsonObj.getJSONObject("WindModel").getString("Description");
windModelRun = jsonObj.getJSONObject("WindModel").getString("ModelRun");
// Get alllllll of the forecast data!
JSONArray forecastJsonAray = jsonObj.getJSONArray("ForecastData");
dayCount = 0;
for (int i = 0; i < FORECAST_DATA_COUNT; i++) {
Forecast newForecast = new Forecast();
// Grab the next forecast object from the raw array
JSONObject rawForecast = forecastJsonAray.getJSONObject(i);
newForecast.date = rawForecast.getString("Date");
newForecast.time = rawForecast.getString("Time");
newForecast.minimumBreakingHeight = rawForecast.getDouble("MinimumBreakingHeight");
newForecast.maximumBreakingHeight = rawForecast.getDouble("MaximumBreakingHeight");
newForecast.windSpeed = rawForecast.getDouble("WindSpeed");
newForecast.windDirection = rawForecast.getDouble("WindDirection");
newForecast.windCompassDirection = rawForecast.getString("WindCompassDirection");
Swell primarySwell = new Swell();
primarySwell.waveHeight = rawForecast.getJSONObject("PrimarySwellComponent").getDouble("WaveHeight");
primarySwell.period = rawForecast.getJSONObject("PrimarySwellComponent").getDouble("Period");
primarySwell.direction = rawForecast.getJSONObject("PrimarySwellComponent").getDouble("Direction");
primarySwell.compassDirection = rawForecast.getJSONObject("PrimarySwellComponent").getString("CompassDirection");
newForecast.primarySwellComponent = primarySwell;
Swell secondarySwell = new Swell();
secondarySwell.waveHeight = rawForecast.getJSONObject("SecondarySwellComponent").getDouble("WaveHeight");
secondarySwell.period = rawForecast.getJSONObject("SecondarySwellComponent").getDouble("Period");
secondarySwell.direction = rawForecast.getJSONObject("SecondarySwellComponent").getDouble("Direction");
secondarySwell.compassDirection = rawForecast.getJSONObject("SecondarySwellComponent").getString("CompassDirection");
newForecast.secondarySwellComponent = secondarySwell;
Swell tertiarySwell = new Swell();
tertiarySwell.waveHeight = rawForecast.getJSONObject("TertiarySwellComponent").getDouble("WaveHeight");
tertiarySwell.period = rawForecast.getJSONObject("TertiarySwellComponent").getDouble("Period");
tertiarySwell.direction = rawForecast.getJSONObject("TertiarySwellComponent").getDouble("Direction");
tertiarySwell.compassDirection = rawForecast.getJSONObject("TertiarySwellComponent").getString("CompassDirection");
newForecast.tertiarySwellComponent = tertiarySwell;
if (newForecast.time.equals("01 AM") || newForecast.time.equals("02 AM")) {
dayIndices[dayCount] = i;
dayCount++;
} else if (forecasts.size() == 0) {
dayIndices[dayCount] = i;
dayCount++;
}
forecasts.add(newForecast);
}
} catch ( JSONException e ) {
e.printStackTrace();
return false;
}
return true;
}
private void createDailyForecasts() {
if (dailyForecasts.size() > 0) {
dailyForecasts.clear();
}
for (int i = 0; i < dayCount; i++) {
ForecastDailySummary newSummary = new ForecastDailySummary();
ArrayList<Forecast> dailyForecastData = getForecastsForDay(i);
if (dailyForecastData.size() < 8) {
newSummary.morningMinimumWaveHeight = 0;
newSummary.morningMaximumWaveHeight = 0;
newSummary.morningWindSpeed = 0;
newSummary.morningWindCompassDirection = "";
newSummary.afternoonMinimumWaveHeight = 0;
newSummary.afternoonMaximumWaveHeight = 0;
newSummary.afternoonWindSpeed = 0;
newSummary.afternoonWindCompassDirection = "";
if (dailyForecasts.size() == 0) {
if (dailyForecastData.size() >= 6) {
newSummary.morningMinimumWaveHeight = (int)(dailyForecastData.get(0).minimumBreakingHeight + dailyForecastData.get(1).minimumBreakingHeight) / 2;
newSummary.morningMaximumWaveHeight = (int)(dailyForecastData.get(0).maximumBreakingHeight + dailyForecastData.get(1).maximumBreakingHeight) / 2;
newSummary.morningWindSpeed = dailyForecastData.get(1).windSpeed;
newSummary.morningWindCompassDirection = dailyForecastData.get(1).windCompassDirection;
newSummary.afternoonMinimumWaveHeight = (int)(dailyForecastData.get(2).minimumBreakingHeight + dailyForecastData.get(3).minimumBreakingHeight) / 2;
newSummary.afternoonMaximumWaveHeight = (int)(dailyForecastData.get(2).maximumBreakingHeight + dailyForecastData.get(3).maximumBreakingHeight) / 2;
newSummary.afternoonWindSpeed = dailyForecastData.get(3).windSpeed;
newSummary.afternoonWindCompassDirection = dailyForecastData.get(3).windCompassDirection;
} else {
newSummary.afternoonMinimumWaveHeight = (int)(dailyForecastData.get(1).minimumBreakingHeight + dailyForecastData.get(2).minimumBreakingHeight + dailyForecastData.get(3).minimumBreakingHeight) / 3;
newSummary.afternoonMaximumWaveHeight = (int)(dailyForecastData.get(1).maximumBreakingHeight + dailyForecastData.get(3).maximumBreakingHeight + dailyForecastData.get(3).maximumBreakingHeight) / 3;
newSummary.afternoonWindSpeed = dailyForecastData.get(2).windSpeed;
newSummary.afternoonWindCompassDirection = dailyForecastData.get(2).windCompassDirection;
}
} else {
if (dailyForecastData.size() >= 4) {
newSummary.morningMinimumWaveHeight = (int)(dailyForecastData.get(1).minimumBreakingHeight + dailyForecastData.get(2).minimumBreakingHeight + dailyForecastData.get(3).minimumBreakingHeight) / 3;
newSummary.morningMaximumWaveHeight = (int)(dailyForecastData.get(1).maximumBreakingHeight + dailyForecastData.get(3).maximumBreakingHeight + dailyForecastData.get(3).maximumBreakingHeight) / 3;
newSummary.morningWindSpeed = dailyForecastData.get(2).windSpeed;
newSummary.morningWindCompassDirection = dailyForecastData.get(2).windCompassDirection;
if (dailyForecastData.size() >= 6) {
newSummary.afternoonMinimumWaveHeight = (int)(dailyForecastData.get(4).minimumBreakingHeight + dailyForecastData.get(5).minimumBreakingHeight) / 2;
newSummary.afternoonMaximumWaveHeight = (int)(dailyForecastData.get(4).maximumBreakingHeight + dailyForecastData.get(5).maximumBreakingHeight) / 2;
newSummary.afternoonWindSpeed = dailyForecastData.get(5).windSpeed;
newSummary.afternoonWindCompassDirection = dailyForecastData.get(5).windCompassDirection;
}
}
}
} else {
newSummary.morningMinimumWaveHeight = (int)(dailyForecastData.get(1).minimumBreakingHeight + dailyForecastData.get(2).minimumBreakingHeight + dailyForecastData.get(3).minimumBreakingHeight) / 3;
newSummary.morningMaximumWaveHeight = (int)(dailyForecastData.get(1).maximumBreakingHeight + dailyForecastData.get(3).maximumBreakingHeight + dailyForecastData.get(3).maximumBreakingHeight) / 3;
newSummary.morningWindSpeed = dailyForecastData.get(2).windSpeed;
newSummary.morningWindCompassDirection = dailyForecastData.get(2).windCompassDirection;
newSummary.afternoonMinimumWaveHeight = (int)(dailyForecastData.get(4).minimumBreakingHeight + dailyForecastData.get(5).minimumBreakingHeight + dailyForecastData.get(6).minimumBreakingHeight) / 3;
newSummary.afternoonMaximumWaveHeight = (int)(dailyForecastData.get(4).maximumBreakingHeight + dailyForecastData.get(5).maximumBreakingHeight + dailyForecastData.get(6).maximumBreakingHeight) / 3;
newSummary.afternoonWindSpeed = dailyForecastData.get(5).windSpeed;
newSummary.afternoonWindCompassDirection = dailyForecastData.get(5).windCompassDirection;
}
dailyForecasts.add(newSummary);
}
}
}
|
package com.ehpefi.iforgotthat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* Receives notifications from the system on boot and sets up all the alarms
*
* @author Even Holthe
* @since 1.0.0
*/
public class BootNotificationReceiver extends BroadcastReceiver {
private static final String TAG = "BootNotificationReceiver";
@Override
public void onReceive(Context context, Intent intent) {
// Helpers
ListHelper lh = new ListHelper(context);
ListElementHelper leh = new ListElementHelper(context);
// Create a new alarm manager
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// Get all lists
ArrayList<ListObject> allLists = lh.getAllLists(ListHelper.COL_ID);
// Exit if there are no lists
if (allLists.size() == 0) {
Log.i(TAG, "No lists in the database. I am not needed");
return;
}
// Loop through all lists
for (ListObject list : allLists) {
// Ensure that we aren't operating on a null object
if (list != null) {
// Get all reminders
ArrayList<ListElementObject> allReminders = leh.getListElementsForListId(list.getId(), ListElementHelper.COL_ID);
// Exit if there are no lists
if (allReminders.size() == 0) {
Log.i(TAG, "No reminders for list #" + list.getId() + ". Moving along to the next list...");
return;
}
// Loop through reminders
for (ListElementObject reminder : allReminders) {
// Current time minus 3 minutes
long currentTime = (new Date().getTime()) - ((60 * 3) * 100);
// As long as the object isn't null and has a valid alarm
if (reminder != null && reminder.getAlarmAsString() != ListElementObject.noAlarmString && reminder.isCompleted() == false) {
if (((reminder.getAlarm().getTime()) - currentTime) > 0) {
// Temporary calendar object
Calendar tmp = Calendar.getInstance();
tmp.setTime(reminder.getAlarm());
Long time = tmp.getTimeInMillis();
// Create a new intent
Intent alarmIntent = new Intent(context, AlarmReceiver.class);
alarmIntent.putExtra("id", reminder.getId());
// Set the alarm
alarmManager.set(AlarmManager.RTC_WAKEUP, time, PendingIntent.getBroadcast(context, reminder.getId(), alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Log.i(TAG, "Added alarm for reminder with id " + reminder.getId());
}
}
// Geofence alarms
if (reminder != null && reminder.getGeofenceId() > 0) {
Log.i(TAG, "Got reminder " + reminder.getId() + " with geofence");
reminder.registerGeofence(context);
}
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.